text:
Q: Length of header or names does not match length of data when using pd.read_csv I tried to read a .dat file in python and convert to pandas dataframe using the below code
DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat', encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+')

(Note: I was not able to read the dt file through notepad++ or even vs code and hence tried to use all delimiters in sep. Also I tried with other encodings starting with utf-8, but they didn't work and so switched to latin1)
As there was error I read through other stackoverflow posts and finally used the below piece of code
DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', index_col = False, header =0)

and the problem I had was

MemoryError: Unable to allocate 75.6 GiB for an array with shape
(1189027, 8538) and data type object

So, I used nrows as below
DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', nrows=50, index_col = False, header =0)

Now the error I'm seeing is

ParserWarning: Length of header or names does not match length of
data. This leads to a loss of data with index_col=False.

Please let me know how to deal with this. Is there any better way to inspect dat files? I tried pr.read_fwf as well but doesnt seem to work.
Just to mention. Using encoding = 'utf-8' throws this error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position
0: invalid start byte

What is the mistake I'm making or is there an issue with the data itself....please clarify.


text:
Q: Как упростить код PHP? function display_soc()
{
    function push_array($array, $name, $class){
        $arr = array(
            'n' => $name,
            'c' => $class
        );
        array_push($array, $arr);
        return $array;
    }

    $soc = array();
    ($vk = get_field('vk_link', 'option'))? $soc = push_array($soc, $vk, 'vk__icon') : '';
    ($fb = get_field('fb_link', 'option')) ? $soc = push_array($soc, $fb, 'fb__icon') : '';
    ($ig = get_field('ig_link', 'option')) ? $soc = push_array($soc, $ig, 'insta__icon') : '';
    ($viber = get_field('viber', 'option')) ? $soc =  push_array($soc, $viber, 'viber__icon') : '';
    ($whatsapp = get_field('whatsapp', 'option')) ? $soc = push_array($soc, $whatsapp, 'wapp__icon') : '';
    ($telegram = get_field('telegram', 'option')) ? $soc = push_array($soc, $telegram, 'telegram__icon') : '';

    $result = '';
    if ($soc) {
        foreach ($soc as $item) {
            $result .= '' . PHP_EOL;
        }
    }
    return $result;
}

Сдается, что есть более простой способ вывода. Спасибо

A: Как минимум, вот это:
($vk = get_field('vk_link', 'option'))? $soc = push_array($soc, $vk, 'vk__icon') : '';
($fb = get_field('fb_link', 'option')) ? $soc = push_array($soc, $fb, 'fb__icon') : '';
($ig = get_field('ig_link', 'option')) ? $soc = push_array($soc, $ig, 'insta__icon') : '';
($viber = get_field('viber', 'option')) ? $soc =  push_array($soc, $viber, 'viber__icon') : '';
($whatsapp = get_field('whatsapp', 'option')) ? $soc = push_array($soc, $whatsapp, 'wapp__icon') : '';
($telegram = get_field('telegram', 'option')) ? $soc = push_array($soc, $telegram, 'telegram__icon') : '';

можно записать как:
          // array('vk', 'fb', 'insta', 'viber', 'wapp', 'telegram');
$soc_icons = ['vk', 'fb', 'insta', 'viber', 'wapp', 'telegram'];

foreach ($soc_icons as $icon) {
    $link = $icon.'_link';
    if ($net_name = get_field($link, 'option'))
        $soc = push_array($soc, $net_name, $icon.'__icon');
}

чтоб втыкать вообще любые сети, если их количество будет расти.

А еще я не понял зачем в данном случае посредник в виде массива, если возвращаете все равно чисто ссылки.. поэтому вот это:
if ($soc) {
    foreach ($soc as $key => $item) {
        $result .= 'item№'.$key.'' . PHP_EOL;
    }
}

мне кажется можно опустить и писать сразу:
$soc_icons = ['vk', 'fb', 'insta', 'viber', 'wapp', 'telegram'];

$result = '';
foreach ($soc_icons as $icon) {
    $link = $icon.'_link';
    if ($net_name = get_field($link, 'option'))
        $result .= '' . PHP_EOL;
}

return $result;

А вот если вы делаете по-умному и хотите разделить логику от представления, то тогда вам надо будет возвращать из функции массив $soc.  А уже где-то в представлении делать цикл по данному массиву с формированием ссылок..

Итог у меня получился как-то так (не разделенный на логику и представление):
$soc_icons = ['vk', 'fb', 'insta', 'viber', 'wapp', 'telegram'];

function display_soc($icons_arr) {
    // не знаю что это за функция get_field и что она у вас делает
    // у меня она будет такая тупая))
    function get_field($link, $option) {
        return $link;
    }

    $result = '';
    foreach ($icons_arr as $icon) {
        $link = $icon.'_link';
        if ($net_name = get_field($link, 'option'))
            $result .= '' . PHP_EOL;
    }

    return $result;
}

print_r(display_soc($soc_icons));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to read sensor data from Cloudant NoSQL db using the sync-android library I'm not able fetch sensor data uploaded to a Cloudant NoSQL DB through the IoT Platform using the sync-android library for some reason.
Please find the code, the error message and the line where the error is occurring below:
try {
    uri = new URI("https://user:password@somehost.cloudant.com/database");
} catch (URISyntaxException e) {
    e.printStackTrace();
}
try {
    ds = manager.openDatastore("my_datastores");
} catch (DatastoreNotCreatedException e) {

            }
Replicator replicator = ReplicatorBuilder.pull().from(uri).to(ds).build();
Log.e("aaaaa",String.valueOf(replicator));
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
Toast.makeText(MainActivity.this,String.valueOf(listener),Toast.LENGTH_LONG).show();
replicator.getEventBus().register(listener);
replicator.start();
try {
    latch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}
replicator.getEventBus().unregister(listener);
if (replicator.getState() != Replicator.State.COMPLETE) {
    System.out.println("Error replicating FROM remote");
    System.out.println(listener.error);
}

Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.cloudant.sync.datastore.Datastore com.cloudant.sync.datastore.DatastoreManager.openDatastore(java.lang.String)' on a null object reference
                                                                                at com.example.imb_bng_04.cloudserver.MainActivity.onCreate(MainActivity.java:42)

error in line:
   ds = manager.openDatastore("my_datastores");

A: Looks like maybe you are getting null pointer because you did not initialize an object.  See this Stack overflow post which has similar error.

A: Caused by: java.lang.NullPointerException:

something was null
Attempt to invoke virtual method
  'com.cloudant.sync.datastore.Datastore com.cloudant.sync.datastore.DatastoreManager
  ...openDatastore(java.lang.String)'
on a null object reference

so the thing that was null was the object you called openDatastore on
at com.example.imb_bng_04.cloudserver.MainActivity.onCreate(MainActivity.java:42)

on this particular line:
ds = manager.openDatastore("my_datastores");

So, what is this object reference, on which we called openDatastore, and which turned out to be null?
It was manager, very obviously. The variable manager is null. You haven't shown where it comes from, so no-one can possibly help tell you why it is null, but your fix consists of figuring that out, initializing it to something sensible, and then not calling methods on a null object reference.


text:
Q: Calling Button in Featherlight Lightbox This is a follow up question from Featherlight hide div on Close
I have successfully resolved the problem opening the lightbox, but i've added a submit button which I wish to call on('submit',function) when clicked.
jQuery(document).ready(function() {
//Triggle when Preview Button is Clicked.
jQuery('.OpenLightBox').off('click').on('click', function( e ) {

   var pa_firstname=   jQuery('input[name="pa-name_first"]').val();
   var pa_lastname=    jQuery('input[name="pa-name_last"]').val();
   if (pa_firstname == null || pa_firstname == '') {
       alert('Cannot be empty');
       return false;
   } else {
       var content = '
First Name in Ajax is ' + pa_firstname + ' And Last Name in Ajax is ' + pa_lastname + '<button type="button" value="submit" class="LightBoxSubmit">Send Now</button><button type="button" value="back">Back</button>
';
       jQuery('#preview').html("");
       jQuery('#preview').html(content);
       jQuery.featherlight('#preview', {});
   }
});

//Added function that detects click on .LightBoxSubmit which is a button in the lightbox to call a Submit event, which will trigger the function below.
  jQuery(".LightBoxSubmit").off('click').on('click',function(e) {
  document.getElementById("pd_test").submit();
  alert('LightBoxSubmit Called');

  });

//Once LightBoxSubmit button is clicked, this function is suppose to call so the Ajax (I removed the code for simplicity) event can process the $_POST data.

jQuery('#pd_test').on('submit',function(event) {
    event.preventDefault();
alert('Called Submit')
    var pa_firstname=   jQuery('input[name="pa-[name_first]"]').val();
    var pa_lastname=    jQuery('input[name="pa-[name_last]"]').val();
if (pa_firstname == null || pa_firstname == '') {
    alert('Cannot be empty');
} else
    alert('Form Submitted');

 console.log (pa_firstname);

});
return false;
})

Problem: I cannot get the submit button to close the lightbox and submit the form. It doesn't detect the on('click') event.

A: You were pretty close but you need to do the following:
// We first gave that dynamically generated button an id "submitformbtn". Since your button is dynamically generated, we select it as follows:
   $(document).on('click', '#submitformbtn', function(){
// This is the method to close current featherlight :
      $.featherlight.current().close();
// Then we submit the form
      jQuery('#pd_test').submit();
   });

Demo: https://jsfiddle.net/rdawkins/vvvo5ays/2/


text:
Q: Dealing with the environment url in the "build" version of react I'm trying to deploy a react-django app to production using digitalocean droplet. I have a file where I check for the current environment (development or production), and based on the current environment assign the appropriate url to use to connect to the django backend like so:
export const server = enviroment ? "http://localhost:8000" : "domain-name.com";

My app is working perfectly both on development and production modes in local system (I temporarily still used http://localhost:8000 in place of domain-name.com). But I observed something rather strange. It's the fact that when I tried to access the site (still in my local computer) with "127.0.0.1:8000" ON THE BROWSER, the page is blank with a console error "No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' ....".
When I changed it back to "http://localhost:8000", everything was back working. My worry is isn't 127.0.0.1:8000 the same as http://localhost:8000? From this I conclude that whatever you have in the domain-name.com place when you build your react frontend is exactly what will be used.
Like I said, I'm trying to deploy to a digital ocean droplet, and I plan to install ssl certificate so the site could be served on https. Now my question is given the scenario painted above, what should be the right way to write the url in production? Should it be "serverIP-address", "domain-name.com", "http://domain-name.com", "https://domain-name.com" ?.
I must mentioned that I had previously attempted to deploy to the said platform using the IP-address in the domain-name.com place. After following all the steps. I got a 502 (Bad gateway) error. However, I'm not saying using Ip address was responsible for the error in that case.
Please I would appreciate any help especially from someone who had previously deployed a react-django app to the said platform. Thanks

A:
From this I conclude that whatever you have in the domain-name.com
place when you build your react frontend is exactly what will be used.

Not exactly true, the domain from which the react app is served will be used. If you build it local and upload it to the server and configure domain.com to serve it, then domain.com will be used for cors. The best idea is to allow all CORS until your project is deployment ready. Once done, whitelist the domain.com

A: The solution actually lies in providing the host(s) allowed to connect to the Back-end in the setting.py file like so: CORS_ALLOWED_ORIGINS = [ domain-name.com, https:domain-name.com , ... ] etc. That way, you wouldn't be tied to using the url provided in the react environment variable. Though I have not deployed to the server, my first worry within the local machine is taken care off.


text:
Q: Is this efficient way to use Nim ref data structure? I'm keeping in memory huge list of companies, and need to do lots of operations of getting individual company.
Like getting individual company "Microsoft" by its symbol "MSFT".
Would the data structure below be a proper way to model that? There should be no copy-by-value of the whole list or map.
It is ok if the individual company would be copied by value.
import tables

type
  Company = object
    name:        string
    symbol:      string
    description: string

  CompaniesRef = ref object
    list: seq[Company]
    map:  Table[string, Company]

# Cached data structure to keep thousands of different companies
var cached_companies: CompaniesRef
proc companies(): CompaniesRef =
  if cached_companies == nil:
    # Here will be a proper code of loading companies into the
    # CompaniesRef data structure
    cached_companies = CompaniesRef()
  cached_companies

# Lots of operations of getting a specific company from the list
# or from the map by its symbol
for i in 1..1000:
  # it's ok if individual company will be copied by value,
  # but the whole list should be passed by reference
  let company1 = companies().list[0].name

  # it's ok if individual company will be copied by value
  # but the whole map should be passed by reference
  let company2 = companies().map["MSFT"]

A: That global structure should be fine as it is, an object reference is just a memory managed pointer, so passing its reference around only copies the memory address. Unless you are going to do something with that pointer, why not create it as a global? Hiding it behind a proc call reeks of the I'm-afraid-of-globals-but-can't-live-without-them-singleton pattern.
let companies = CompaniesRef()

With regards to the contents of the structure, you are storing twice each Company object, you might want to store a reference to the Company in the Table or simply use an OrderedTable if you need to keep the order of the inserted keys.


text:
Q: Endless wave animation with paper.js and reactJS. TypeError: Cannot read property 'point' of undefined I'm trying to create an endlessly waving line (animation) the same way it's done here http://paperjs.org/tutorials/animation/creating-animations/
with paper.js & React JS.
But I get the error

"TypeError: Cannot read property 'point' of undefined."

whenever I try to loop over the segments inside the path.
Funny thing is, that, If I don't loop, I don't get this error with 'point' property and everything works perfectly fine (I see the animation).
    import React from 'react';
    import './Canvas.css';
    import Paper, { Path, Point, onFrame } from "paper";

    const Wdivider = Math.round(window.innerWidth / 6);
    const linesNumber = Math.round(window.innerHeight / 10);
    const points = [[0, 0], [Wdivider, 25], [2*Wdivider, 0], [3*Wdivider, 25], [4*Wdivider, 0], [5*Wdivider, 25],[window.innerWidth, 0]];

    var topLeft = [0, window.innerHeight/2];
    var bottomRight = [window.innerWidth, window.innerHeight/2];

    let myPath;
    let copy;

    class Canvas extends React.Component{

        componentDidMount() {
            this.createLines();
            Paper.view.onFrame = event => {
                  this.onFrameAnim(event, myPath);
            };
        }

        createLines(){
            var myCanvas = document.getElementById("myCanvas");
            Paper.setup(myCanvas);

                myPath = new Path({segments: points});

                myPath.smooth();

            }

            //Animation

            onFrameAnim(event, path) {

                for (let i=0; i < myPath.length; i++ ) {
                    if (myPath.segments[i].point.y >= 0) {
                        myPath.segments[i].point.y -= 50;
                    }

                    else {
                        myPath.segments[i].point.y += 50;
                    }
                }

            }

        render(){
            return (
                <canvas id="myCanvas" resize="true" />
            );
        }
    }

    export default Canvas;


text:
Q: Анимация на css 3 Добрый день, подскажите пожалуйста, как сделать бесконечную анимацию на css 3

Нужно, что бы картинки плавно исчезали и появлялись, что бы первая картина быстрее появлялась и исчезала, чем вторая.
Без js.

A:

img {
  position: absolute;
  animation: blink 5s linear infinite;
}

img + img {
  animation-duration: 10s;
}

@keyframes blink {
    0% { opacity: 1 }
   50% { opacity: 0 }
  100% { opacity: 1 }
}


text:
Q: Store (almost) all objects in workspace in a list Let's say that I have many objects in my workspace (global environment) and I want to store most of those in a list. Here's a simplified example:
# Put some objects in the workspace
A <- 1
B <- 2
C <- 3

I would like to store objects A and C in a list. Of course, I can do that explicitly:
mylist <- list(A,C)

However, when the number of objects in the workspace is very large, this would become rather cumbersome. Hence, I would like to do this differently and attempted the following:
mylist <- list(setdiff(ls(),B))

But this obviously is not what I want, as it only stores the names of the objects in the workspace.
Any suggestions on how I can do this?
Many thanks!

A: EDIT : I think using lapply / sapply here raises too many problems. You should definitely use the mget answer.
You can try :
mylist <- sapply(setdiff(ls(),"B"), get)

In certain cases, ie if all the objects in your workspace are of the same type, sapply will return a vector. For example :
sapply(setdiff(ls(),"B"), get)
# A C
# 1 3

Otherwise, it will return a list :
v <- list(1:2)
sapply(setdiff(ls(),"B"), get)
# $A
# [1] 1
#
# $C
# [1] 3
#
# $v
# [1] 1 2

So using lapply instead of sapply here could be safer, as Josh O'Brien pointed out.

A: mget is definitely the easiest to use in this situation. However, you can achieve the same with as.list.environment and eapply:
e2l <- as.list(.GlobalEnv)
# or: e2l <- as.list(environment())
# using environment() within a function returns the function's env rather than .GlobalEnv
e2l[! names(e2l) %in "B"]

# the following one sounds particularly manly with `force`
e2l <- eapply(environment(), force)
e2l[! names(e2l) %in "B"]

And one-liners:
 (function(x) x[!names(x)%in%"B"])(eapply(environment(), force))
 (function(x) x[!names(x)%in%"B"])(as.list(environment()))

A: Another option is to use mget:
mget(setdiff(ls(),"B"))


text:
Q: How to calculate current day value based on previous day, in pyspark? I have the following scenario. On day o1, I have the balance, and day by day it is subtracting the transactions. I need to calculate the balance at the beginning and end of the day. I'm trying to use the lag function.
follows the logic in sql, remembering that it makes a loop to go through the whole month, always taking the previous ia and the current day
if month('day')=1 then
do;
begin_day = saldo + trans - vl_dis
+ vl_car + vl_ret;
end_day = saldo ;
end;
IF month('day')>1 then
do;
begin_day = end_day;
end_day = begin_day - trans
+ vl_dis - vl_car - vl_ret;
end;

output expected:
 +--------+--------+------+------+------+------+---------+--------+----------+
 | key    |   saldo| trans|vl_dis|vl_car|vl_ret|begin_day| end_day|       day|
 +--------+--------+------+------+------+------+---------+--------+----------+
 |123     |   100.0|   1.0|   2.0|   0.0|   0.0|     99.0|   100.0|2022-02-01|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|    100.0|    99.0|2022-02-02|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|     99.0|    98.0|2022-02-03|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|     98.0|    97.0|2022-02-04|
 |123     |     0.0|   1.0|   2.0|   0.0|   0.0|     97.0|    98.0|2022-02-05|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|     98.0|    97.0|2022-02-06|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|     97.0|    96.0|2022-02-07|
 |123     |     0.0|   1.0|   2.0|   0.0|   0.0|     96.0|    97.0|2022-02-08|
 |123     |     0.0|   1.0|   0.0|   0.0|   0.0|     97.0|    96.0|2022-02-09|
 +--------+--------+------+------+------+------+---------+--------+----------+

A: This when first looked at looks like a recursion problem as we have to keep looking back to value in previous row to calculate next value and recursive cte or tables are not supported in pyspark
But when looked closely this can be solved with running sum and lag so below first preparing the above data without start_day and end_day value which will be calculated with required imports
from io import StringIO
import pandas as pd
import pyspark.sql.functions as F
from pyspark.sql import Window

s=StringIO("""
key|saldo|trans|vl_dis|vl_car|vl_ret|day
123|100.0|1.0|2.0|0.0|0.0|2022-02-01
123|0.0|1.0|0.0|0.0|0.0|2022-02-02
123|0.0|1.0|0.0|0.0|0.0|2022-02-03
123|0.0|1.0|0.0|0.0|0.0|2022-02-04
123|0.0|1.0|2.0|0.0|0.0|2022-02-05
123|0.0|1.0|0.0|0.0|0.0|2022-02-06
123|0.0|1.0|0.0|0.0|0.0|2022-02-07
123|0.0|1.0|2.0|0.0|0.0|2022-02-08
123|0.0|1.0|0.0|0.0|0.0|2022-02-09""")

dfp=pd.read_csv(s,sep='|')
dfs=spark.createDataFrame(dfp)

Now below we will create the dataframe with the required start_day and end_day column
r_w=Window.partitionBy("month").orderBy("dom")
dfs.withColumn("month",F.month(F.col("day"))).\
withColumn("dom",F.date_format(F.col("day"), "d")).\
withColumn("trans_sum",F.sum("trans").over(r_w)-F.first("trans").over(r_w)).\
withColumn("vl_dis_sum",F.sum("vl_dis").over(r_w)-F.first("vl_dis").over(r_w)).\
withColumn("vl_car_sum",F.sum("vl_car").over(r_w)-F.first("vl_car").over(r_w)).\
withColumn("vl_ret_sum",F.sum("vl_ret").over(r_w)-F.first("vl_ret").over(r_w)).\
withColumn("start_day",F.when(F.col("dom")==1,F.col("saldo")+ F.col("trans")-F.col("vl_dis")+F.col("vl_car")+F.col("vl_ret")).otherwise(F.first("saldo").over(r_w)- F.lag(F.col("trans_sum"),1).over(r_w)+F.lag(F.col("vl_dis_sum"),1).over(r_w)-F.lag(F.col("vl_car_sum"),1).over(r_w)-F.lag(F.col("vl_ret_sum"),1).over(r_w))).\
withColumn("end_day",F.when(F.col("dom")==1,F.col("saldo")).otherwise(F.first("saldo").over(r_w)- F.col("trans_sum")+F.col("vl_dis_sum")-F.col("vl_car_sum")-F.col("vl_ret_sum"))).\
drop("month","dom","trans_sum","vl_car_sum","vl_dis_sum","vl_ret_sum").\
show()

#output
+---+-----+-----+------+------+------+----------+---------+-------+
|key|saldo|trans|vl_dis|vl_car|vl_ret|       day|start_day|end_day|
+---+-----+-----+------+------+------+----------+---------+-------+
|123|100.0|  1.0|   2.0|   0.0|   0.0|2022-02-01|     99.0|  100.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-02|    100.0|   99.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-03|     99.0|   98.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-04|     98.0|   97.0|
|123|  0.0|  1.0|   2.0|   0.0|   0.0|2022-02-05|     97.0|   98.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-06|     98.0|   97.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-07|     97.0|   96.0|
|123|  0.0|  1.0|   2.0|   0.0|   0.0|2022-02-08|     96.0|   97.0|
|123|  0.0|  1.0|   0.0|   0.0|   0.0|2022-02-09|     97.0|   96.0|
+---+-----+-----+------+------+------+----------+---------+-------+


text:
Q: Как вывести значения в TextBox в режиме реального времени? Всем привет! Как вывести значения с метода PrintInfo() в форму?
Я получаю эти значения, но хочу видеть их в приложении в режиме реального времени. Они не отображаются пока работает цикл do-wile в методе StartBrowser.
Иными словами с сайта я получаю значение к примеру таймера каждые две секунды и хочу сразу его видеть на своей форму в TextBox'e.
Заранее спасибо за потраченное на меня время.
  namespace ParserFavorit
    {
        public partial class Favorit : Form
        {
            public Favorit()
            {
                InitializeComponent();
            }

            private void bStart_Click(object sender, EventArgs e)
            {
                string ID = tbGetID.Text;
                Second.StartBrowser(Second.GetDriver(), ID, this);
            }

            public void PrintInfo(string Command1Name, string Command2Name, string Command1Goals, string Command2Goals, string TimeOfGame, int TotalGoals)
            {
                string TimeGame = TimeOfGame;
                tbCommandName1.Text = Command1Name;
                tbCommandName2.Text = Command2Name;
                tbGetID.Text = "Time game: " + TimeGame;
                tbCommand1Goals.Text = Command1Goals;
                tbCommand2Goals.Text = Command2Goals;
                tbTotalGoals.Text = Convert.ToString(TotalGoals);
            }
        }
        public class Second
        {
            private static ChromeDriver driver = null;
            public static ChromeDriver GetDriver()
            {
                if (driver == null)
                {
                    driver = new ChromeDriver();
                }
                return driver;
            }
            public static void StartBrowser(ChromeDriver driver, string ID, Favorit MainForm)
            {
                string Time;
                driver.Navigate().GoToUrl("myURL" + ID);
                do
                    Time = GetInfo(MainForm);
                while (Time != "90:00");
            }

            public static string GetInfo(Favorit MainForm)
            {
                System.Threading.Thread.Sleep(2000);
                string CommandName1 = driver.FindElement(By.XPath(".//*[@id='react-root']/div/div[2]/div/div[1]/div/div[1]/div/div[1]/div/header/div[2]/span[1]")).Text;
                string CommandName2 = driver.FindElement(By.XPath(".//*[@id='react-root']/div/div[2]/div/div[1]/div/div[1]/div/div[1]/div/header/div[2]/span[2]")).GetAttribute("innerHTML");
                string Command1Goals = driver.FindElement(By.XPath(".//*[@id='react-root']/div/div[2]/div/div[1]/div/div[1]/div/div[1]/div/header/div[4]/div[1]/div[1]")).GetAttribute("innerHTML");
                string Command2Goals = driver.FindElement(By.XPath(".//*[@id='react-root']/div/div[2]/div/div[1]/div/div[1]/div/div[1]/div/header/div[4]/div[1]/div[2]")).GetAttribute("innerHTML");
                string TimeOfGame = driver.FindElement(By.XPath("html/body/div/div/div//div/div[@class='headroom-wrapper']/div//div[3]/div")).GetAttribute("innerHTML");//timer eeeeeeeee
                int TotalGoals = Convert.ToInt32(Command1Goals) + Convert.ToInt32(Command2Goals);
                MainForm.PrintInfo(CommandName1, CommandName2, Command1Goals, Command2Goals, TimeOfGame, TotalGoals);
                return TimeOfGame;
            }
        }
    }


text:
Q: Want to sent mail to different mail id's of a user using Laravel Mail Notifcation Company.php
public function routeNotificationForMail() {
    return $this->office_mail;
}

This is my company modal where i can specify only one mail id.but I want to send mail to 2 mail id's
App\Notifications\JobApplication.php
public function toMail($notifiable) {
    $message = 'A candidate applied for your job posting, ' . $this->job['job_title'];
    return (new MailMessage)
        ->line($message)
        ->line('Thank you for using our application!');
}

when a candidate apply for a company's job posting, A mail should be sent to the company's office mail address and company's login mail address. ie)my company table contans email field and office_mail field
I have seen this link "https://github.com/laravel/framework/issues/15694". but not clear about how to use htis.

A: public function routeNotificationForMail() {
    return [$this->office_mail, $this->email];
}

can return as an array


text:
Q: Python Subprocess Pass Argument of Filename I know there is a better way to do this than subprocess.Popen but for the sake of time, thats what I am using. I have a script called save_input.cgi which saves a file to my linux box through a web app. When it has saved the file, I need it to pass that filename as an argument to another script. This is probably something simple I am missing, but here is what I have so far:
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename here.
fileitem = form['filename']

# Test if the file was uploaded
if fileitem.filename:
  # strip leading path from file name to avoid
  # directory traversal attacks
  fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
  open('/tmp/' + fn, 'wb').write(fileitem.file.read())

  message = 'The file "' + fn + '" was uploaded successfully'
  subprocess.Popen(["python", "mod_check.py", '/tmp/' + fn])

else:
   message = 'No file was uploaded'

print """\
Content-Type: text/html\n
<html>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)

Thoughts? Thanks a lot, I owe this community a lot haha.
*I just update it to include the subprocess in the if fileitem.filename block, but it does not seem to pass the filename and location to the script as an argument. To answer another one of the comments, yes this script does work if I manually enter "sudo python mod_check.py filename.txt"

A: Just a simple thing I overlooked. Resolved using jordanm's response. Added to the codeblock 'if fileitem.filename'


text:
Q: How to make image placeholder? How to get image placeholder? It should looks like empty place (16*16) in gray color.
And when i select image- it places into placeholder.
I know how to select image from files, but i do not know how to make empty space (16*16 with gray color).
Can you get me some links or simple example?
Thank you!

A: You can do something as simple as:
<Grid Background="Gray">
   <Image />
</Grid>

When image loads, it will cover the gray color.


text:
Q: OpenCV How can I calculate area of binary object? I am using OpenCV and c++. I have black and white image after binarization. How can I calculate area of object when I have only one coordinate of point (x,y) belongs to this object??

A: since it's a binary image, you can easily get the blobs. Once you get the blobs, you can easily calculate the blob area.
You can use cvBlobsLib to get the blobs. OpenCV hasn't integrated cvBlobsLib. You can do it by yourself. But OpenCV has functionality for contours. You can use findContours to get blobs/contours and then get the area. OpenCV - findContours
OpenCV - Structural Analysis and Shape Description
You'll find information about moments, huMoments, contours, etc. Using moments, you can create your own blobs and it will also help you in getting the blob area.
Here's an Open Source framework for machine vision which uses Python bindings of OpenCV - SimpleCV
They have implemented a complete blob functionality using contours and moments. You can have a look.
Blob
BlobMaker
It's written in Python, but you can port it to C++ and use blobs.

A: The algorithm is very easy and should be the following:

*

*Find all contours on your image.

*Cycle through all contours and check if point is inside a contour.

*If contour is found than calculate it's area.

A: You have to write some kind of region growing algorithm, starting from your startpoint, incrementally adding adjacent pixels that are of the same color.
A lazy (and much slower) way to do it would be to use cv::floodFill function, setting up the pixels in your shape to a specific color, then counting the pixels in you image that have this specific color.


text:
Q: How do I fix my React Bootstrap Navbar? (Navbar Brand Collapse) Updated I have created a navbar in my React.js website using bootstrap for react. The navbar currently collapses at a certain point however my menu button does not appear. Please could someone check through the code below and let me know what I'm missing/need to do?
I have tried to add in the toggle using an example on a bootstrap tutorial site however it doesn't seem to work, I'm assuming that something is missing? Or i'm doing something wrong?
EDIT: I have fixed the original issue however all the alignment has been thrown off, I have changed the code below to the new code.

*

*I need everything on the navbar desktop view to be aligned right except the logo which should remain where it is.

*In tablet view, the navbar is automatically toggled on so always viewable? I don't want this.

*In the mobile view, I need the logo to remain where it is and the button to be aligned vertically central and to the right.
Thanks in advance!
Navbar.js:
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Button from 'react-bootstrap/Button';
import {
  Link
} from 'react-router-dom';

class NavBar extends React.Component {
  render() {
    return (
      <Navbar collapseOnSelect expand="lg" className="custom-nav-bg fixed-top">
        <Navbar.Brand href="#home">
        <Link to="/home"></Link>
        </Navbar.Brand>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" className="navbar-toggler-css" />
        <Navbar.Collapse id="responsive-navbar-nav">

            <Link to="/about">ABOUT</Link>

            <Link to="/stats">STATS</Link>

            <Link to="/faq">FAQS</Link>

            <Link to="/contact">CONTACT</Link>

              <Link to="/signup"><Button className="custom-nav-button">SIGN UP</Button></Link>

            <Link to="/login">LOGIN</Link>

        </Navbar.Collapse>
    </Navbar>
    )
  }
}
export default NavBar;

Navbar CSS (For some context):
  background-color: red ! important;
  display: flex;
  align-items: flex-end;
}

.align-nav {
  display: flex;
  align-content: flex-end;
}

.custom-nav-bg {
  max-width: 100%;
  padding-right: 50px;
  padding-left: 60px;

  border-radius: 0px;
  background-color: #132A42;
}

.custom-nav-logo {
  height: 100%;
}

a.custom-nav-text:hover {
  color: #00DF8D ! important;

  font-family: 'Assistant', sans-serif ! important;
}

a.custom-nav-button:hover {
  color: #00DF8D ! important;

  font-family: 'Assistant', sans-serif ! important;
}

.custom-nav-text {
  max-width: 100%;
  padding-top:10px ! important;
  padding-right:20px ! important;
  padding-bottom:10px ! important;
  padding-left:20px ! important;

  color: white ! important;

  font-family: 'Assistant', sans-serif;
  font-size: 20px;
  font-weight: 600;
}

.custom-nav-button {
  padding-right: 15px;
  padding-left: 15px;

  border-color: #00DF8D;
  border-radius: 10px;
  background-color: #00DF8D;

  font-size: 20px;
  font-weight: 600;
  }

  @media only screen and (max-width: 768px) {
    .custom-nav-text {
      max-width: 100%;
      padding-top:10px ! important;
      padding-right:10px ! important;
      padding-bottom:10px ! important;
      padding-left:10px ! important;

      font-size: 15px;
    }
    .custom-nav-logo {
      align-items: flex-start;
      justify-content: flex-start;
    }
    .custom-nav-bg {
      padding-left: 0px;
      padding-right: 0px;
      display: block;
    }
  }

  @media only screen and (max-width: 768px) {
    .custom-nav-button {
      padding-right: 10px;
      padding-left: 10px;

      border-color: #00DF8D;
      border-radius: 5px;
      background-color: #00DF8D;

      font-size: 15px;
      }
    }

A: This is the example from react-boostrap
import React from "react";
import{ Navbar, Nav, Button, NavDropdown}  from "react-bootstrap";

class NavBar extends React.Component {
  render() {
    return (
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
  <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
  <Navbar.Toggle aria-controls="responsive-navbar-nav" />
  <Navbar.Collapse id="responsive-navbar-nav">

      Features
      Pricing
      <NavDropdown title="Dropdown" id="collasible-nav-dropdown">
        <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
        <NavDropdown.Divider />
        <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
      </NavDropdown>

      More deets

        Dank memes

  </Navbar.Collapse>
</Navbar>
    );
  }
}
export default NavBar;

check also the doc of react-boostrap for the responsive behaviours
https://react-bootstrap.github.io/components/navbar/#navbars-mobile-friendly
I would recommend you to keep align with bootstrap classes for alignment, without touching directly the css (you can do that, but try to use as much as possible their alignments). Have a look in the docs on how to position things.

A: I'm new to the web , but maybe so like this for the desktop version
import {Navbar,Nav} from 'react-bootstrap';
import '../styless/topBar.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import logo from '../assets/logo.svg';

const  Header = () => {
    return(
<>
<Navbar  collapseOnSelect  variant='dark' expand="lg" >
<Navbar.Brand className='logo-app' >

  </Navbar.Brand>
  <Navbar.Brand className='brand ' href='/'>
    Header
  </Navbar.Brand>
  <Navbar.Toggle aria-controls="responsive-navbar-nav" className="navbar-toggler-css"/>
  <Navbar.Collapse id="responsive-navbar-nav" className = "justify-content-end">

      Home
      Article
      About Us

      login

</Navbar.Collapse>
</Navbar>
</>
 )}
    export default Header;
'''


text:
Q: How to reuse VirtualBox disk "snapshots" I have a "suite" of 5 VMs I'd like to make, all Ubuntu Server 12.04 guest OSes but with radically different software stacks on top of the OS (one server is a "build server" with Subversion, Hudson, etc. installed on it; another server is an app server with JBoss, etc.).
Installing and configuring Ubuntu Server takes several hours. If at all possible, I'd like to only have to do this once (to get a "base" version of the OS installed on a VM) and then copy this "base" to the other 4. That way I save 2 - 3 hrs per machine and just need to focus on installing and configuring the applications for each server.
When I create a VM, I see three files created:

*

*my-vm.vbox - I assume this is the VM

*my-vm.vbox-prev - No idea what this is

*my-vm.vdi - I assume this is the actual disk where the guest OS (my "base") is installed

Unfortunately I've already created all 5 VMs, and am in the process of installing Ubuntu Server on the first one, so my setup is like this:

*

*build-srv.vbox, build-srv.vbox-prev, build-srv.vdi (the VDI is initialized but has nothing in it)

*app-srv.vbox, app-srv.vbox-prev, app-srv.vdi (same, initialized, but with nothing in it)

*etc... (for all 5)

I'm in the process of installing Ubuntu Server on the build server (build-srv). I'm hoping that once I'm finished, all of that configuration info will just be contained to build-srv.vdi. In theory, I should be able to just copy-n-paste build-srv.vdi to each of the other servers, and swap out their respective VDIs, right?
I'm sure I would have to also go into the VM settings and change the VDI somehow as well, but I'm not even sure if I'm on the right track.
Is what I need possible? If so, what do I need to do to configure each VM with the same copy of the OS instance I am currently in the middle of? If not, what are my options (besides repeating the same 2-hour install for each VM!)? Thanks in advance!

A: Each VDI file contains an identifier on the form of an UUID.
Virtualbox record these UUIDs into a database, and refuse to use a VDI you just copied (but this is okay on another computer because it doesn't recorder anything about this UUID).
I know 2 methods:
- copy the VDI (with a file manager or command line), then use vboxmanage internalcommands sethduuid "path/yourdisk.vdi" and you'll have a brand new UUID for this VDI
- or use Virtualbox mediamanager (into the menu). Select the disk you want to copy... and click the "copy" button. It will do the same thing with ease

*

*my-vm.vbox - this is a XML file describing the VM. You can open it with a text editor or a web browser

*my-vm.vbox-prev - this is a backup of my-vm.vbox

*my-vm.vdi - this is the virtual disk

edit : the copy feature seems to be present only on Windows. My Linux box doesn't have it, my Windows box has

A: What you may be looking for is the multiattach disk mode - which can be applied after the initial disk image is created and configured.  You can then use it as the core for multiple VMs and each will have thier own differencing image based on the original - no copying or cloning necessary.  Please see the docs at: http://www.virtualbox.org/manual/ch05.html#hdimagewrites


text:
Q: How to position elements in a webpage CSS How would I be able to position all these elements in the middle of the webpage?
for example the h1 a bit above the input, but all relative to each other, also taking into account that it should be responsive. I know how to position them using position: absolute; but I'd like to know what a better practice would be.
https://jsfiddle.net/w75ksg69/3/

html {
     background-color: rgb(171, 248, 235);
        font-family: sans-serif,Tahoma, Verdana, 'Times New Roman';
    }

    h1#maintitle {
        margin: 0 0 0 0;
        text-align: center;
    }

    div#info {
        font-size: 1em;
        margin: 0.5em;
    }

Find your new abcde

        <input name="arrive" type="date" placeholder="Arrival date:">
        <input name="departure" type="date" placeholder="Departure      date:">
        <input name="guests" type="number" placeholder="Guests:">
        <button id="search_button" type="button">Search</button>

A: I made all your inputs on the center using just text-align: center:
div#info {
    font-size: 1em;
    text-align: center;
}

Hope, it helps


text:
Q: How can I ignore whitespace changes in TortoiseGit blame If I want to ignore whitespace changes in git blame I can use -w option. But how can I do it in TortoiseGit Blame GUI tool? Is this even possible?

A: See the following figure for -w(Ignore whitespace) feature:

A: No, it is not possible to ignore whitespace changes in TortoiseGitBlame.
In Git Extensions blame view, whitespace is ignored (feature added in version 1.51).


text:
Q: php - simplexml issue I have an xml file that has attributes/tags for mutliple levels in the feed however simplexml isn't showing them in the print_r dump.
Example:
<types tag1="1287368759" tag2="1287368759">
    <locations>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
    </locations>
</types>

Problem is the tags in the <types> works fine and shows up in the xml dump, however the tags in each of the segments are not there. Any help?

A: SimpleXML is more like a resource, so var_dumping / print_ring will not yield any usable results.
A simple foreach($xml->types->segment->locations as $location) should work to loop through your locations, and use getAttributes() to get attributes of a node.
I'd suggest taking a closer look at the examples & functions in the manual (look at the comments too), as working with SimpleXML may be simple after you know how, you do need some background on how to use it as the usual introspection is not possible.

A: SimpleXML will not show the attributes if the element has normal data in it, you need to use  as the example below:
<?php
$xml = '<types tag1="1287368759" tag2="1287368759">
    <locations>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
    </locations>
</types>';

$xml_data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

print_r($xml_data);

foreach ($xml_data->locations->segment as $segment) {
    print $segment['prefix'] . ' - ' . ((string) $segment) . "\n";
}

I'm not sure why this is, but I found that that works,
Hope it helps.


text:
Q: Checking is args[0] contains no element? Pretty much the program I am writing has a 'Usage' method which gets called if args[0] contains nothing. Here is the program, When ever I try something of the sort such as (args[0].isEmpty()...) I get an ArrayIndexOutOfBounds.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Desk {

public static void main(String[] args) throws FileNotFoundException {
    if(args[0].isEmpty()){
        Usuage();
    }

    try{
        count(new TreeSet<String>(),  new File("C:\\Users\\Ceri\\workspace1\\Cw2Task2\\src\\" + args[0]));
    }catch(FileNotFoundException e){
        System.out.println("Error: File not found");
    }

}

private static void count(TreeSet<String> treeSet, File file) throws FileNotFoundException {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(file);

    while(in.hasNext()){
        String temp = in.next();
        treeSet.add(temp);
    }

    System.out.println("There are " +  treeSet.size() + "Unique words in the text file ");
}

private static void Usuage(){
        System.out.println("Not entered");
}

}

A: You should check :
if(args.length < 1) {


text:
Q: Cake PHP: Find condition on deeper level of recursion My Models are related as follows:
Post BELONGS_TO Parent
Parent HAS_MANY ParentAdmin

Now I wish to find all Parent admins of all post if a post's attribute's value is met. The equivalent sql query is :
SELECT parent_admins.* FROM posts
LEFT JOIN parents AS Parent ON Parent.id = posts.target_id
LEFT JOIN parent_admins ON parent_admins.parent_id = Parent.id
WHERE posts.admin_notification = 0 AND Parent.maxtime > posts.created

Assuming Models are linked in cakephp accordingly and recursive = 2, what will be the condition array in find query?

A: You can both use the bindModel & unbindModel methods to get the exact query you want or you can use the Containable behavior.
More information about how to create and destroy associations on the fly with CakePHP: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
And you'll need this array of conditions:
$conditions = array(
    'Post.admin_notification' => 0,
    'Parent.maxtime >' => 'Post.created'
);

A: according to your query :-
$conditions=array(
                 'posts.admin_notification'=>0,
                 'Parent.maxtime >'=>'posts.created'
                 );

A: If your query do the job:
Inside PostsController:
    $query = "SELECT parent_admins.* FROM posts
    LEFT JOIN parents AS Parent ON Parent.id = posts.target_id
    LEFT JOIN parent_admins ON parent_admins.parent_id = Parent.id
    WHERE posts.admin_notification = 0 AND Parent.maxtime > posts.created"

    $result = $this->Posts->query($query);
    $debug($result);


text:
Q: KSQLDB streams flow visualisation KSQLDB allows stream joins which is quite a handy solution. As the queries get complicated and the time pass on it is handy to see how the data flow is designed in a visual manner.
My question is are there any existing tooling that allow to visualise the current message flow designed by the KSQL queries? Even perhaps the underlying Kafka streams visualisation would be a good start too.


text:
Q: Creating a custom JSON tokenizer I am trying to parse JSON into a token object. Right now Im using JSON.Net to generate a static class, and parsing it using Json2csharp, but I would like to make each array element its own Token object and I'm not quite sure how to do that. Do I need to implement my own JSON parser? I can modify the JSON object as needed.
My JSON Deserializer: JSONopMap jo = JsonConvert.DeserializeObject<JSONopMap>(myjson2);
public class JSONopMap
{
List<List<string>>addr  {get;set;}
}

JSON
{
  'addr':[['~address'],['removeall','.'],['append',' ','~age']]
}

My end goal is to create a MyToken class like this:
public class MyToken
{
public enum tokenType {get;set;}
public List<string> parts {get;set;}
}

public class TokenParent{
public string ResultName{get;set;}
public List<MyToken> mytokens{get;set;}
}

public enum tokenType{Map,Append,Removeall,Lower}

So I would have three MyToken objects like this:
new MyToken{
 tokenType=Map,
 parts=new List<string>(){"~address"}
}

new MyToken{
 tokenType=Removeall,
 parts=new List<string>(){"."}
}

new MyToken{
 tokenType=Append,
 parts=new List<string>(){" ","~age"}
}

and a parent which contained them all:
new TokenParent{
 ResultName="addr",
 mytokens = (the tokens created above)
}


text:
Q: Internal server error 500 when submitting form for POST request Jira API Good day everyone, I have some questions and errors about using the Jira API for my WordPress website and I need your help on this
So I am building a WPForm in WordPress to take the data from the inputs and submit them with Jira API POST request to create a task on Jira. However, I encountered some errors when submitting the form. Below is the code
function sendingDataToJira( $fields, $entry, $form_data, $entry_id) {

  $user = 'MY_USERNAME';
  $token = 'MY_TOKEN';

  $entry = wpforms()->entry->get( $entry_id );
  $entry_fields = json_decode( $entry->fields, true);

  if ($form_data['id'] == 3809) {
    $api_url = 'https://MY_URL/rest/api/2/issue/';
    $body = array (
      'fields' => array (
        'project'=> array (
          'key'=> 'ATS',
         ),
        'summary' => 'New Applicant',
        'description' => 'null',
        'customfield_10034' => $form_data[4]['value'],
        'customfield_10035' => $form_data[5]['value'],
        'issuetype' => array(
          'name' => 'Task',
        ),
     ),
   );

  $request = wp_remote_post( $api_url, array(
    'method' => 'POST',
    'headers' => array(
      'Authorization' => 'Basic' . base64_encode( $user . ':' . $token),
      'Content-Type' => 'application/json'),
    'body' => json_encode( $body ),
    'data_format' => 'body'
) );

  };
}

add_action( 'wpforms_process_complete', 'sendingDataToJira', 10, 4 );

I tried using other third party plugins but they might require premium version as well as my boss told me not to use any third parties.
I also tried switching to Contact Form 7 with API integration but it didn't work as well.
I want it to work like after pressing the submit button, the form will send a POST request to Jira and create a task.
Here are the errors that I got from the console:
errors

POST https://olinno.com/wp-admin/admin-ajax.php 500

WPForms AJAX submit error

Here is the debug.log file after the errors
    [08-Dec-2022 07:37:38 UTC] PHP Fatal error:  Uncaught Error: Call to a member function get() on null in /home/u435205697/domains/olinno.com/public_html/wp-content/themes/landio/functions.php:127
    Stack trace:
    #0 /home/u435205697/domains/olinno.com/public_html/wp-includes/class-wp-hook.php(307): sendingDataToJira(Array, Array, Array, 0)
    #1 /home/u435205697/domains/olinno.com/public_html/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters(NULL, Array)
    #2 /home/u435205697/domains/olinno.com/public_html/wp-includes/plugin.php(476): WP_Hook->do_action(Array)
    #3 /home/u435205697/domains/olinno.com/public_html/wp-content/plugins/wpforms-lite/includes/class-process.php(450): do_action('wpforms_process...', Array, Array, Array, 0)
    #4 /home/u435205697/domains/olinno.com/public_html/wp-content/plugins/wpforms-lite/includes/class-process.php(109): WPForms_Process->process(Array)
    #5 /home/u435205697/domains/olinno.com/public_html/wp-content/plugins/wpforms-lite/includes/class-process.php(875): WPForms_Process->listen()
    #6 /home/u435205697/domains/olinno.com/pu in /home/u435205697/domains/olinno.com/public_html/wp-content/themes/landio/functions.php on line 127

A: Most likely this add_action( ... ); is called too early, before WPForms plugin was able to load itself (but after WordPress, given that there is some output in the debug.log file).
Create a /mu-plugins/custom-wpforms.php file, and put your code over there, or create a custom plugin for that purpose, or use a plugin like WPCode for this.
Also, why do you re-declare the $entry variable? You receive it in function parameters from the hook, so you already have all the entry information - technically you don't need to make an additional request for that.
$entry_fields is also an unused variable.
You can also use
add_action( 'wpforms_process_complete_3809', 'sendingDataToJira', 10, 4 );

instead and remove the if form ID check in your function completely.


text:
Q: Hibernate multi thread and synchronization I have the following code:
public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
Configuration cfg = new Configuration();

cfg=cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
    System.out.println("** Initial SessionFactory creation failed: " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal hibernateSession = new ThreadLocal();

public static Session currentSession() {
    Session s = (Session) hibernateSession.get();
    if (s == null) {
        s = sessionFactory.openSession();
        //System.out.println("sessionFactory.openSession()");
        hibernateSession.set(s);
    }
    return s;
}

public static void closeSession() {
    Session s = (Session) hibernateSession.get();
    if (s != null)
        s.close();
    hibernateSession.set(null);
}
}

Also
public class Db {
    public static synchronized void Insert(Object updateBean) {
    org.hibernate.Session hibernateSession = HibernateUtil.currentSession();
    try {
        Transaction tx = hibernateSession.beginTransaction();
        hibernateSession.save(updateBean);
        tx.commit();
    } catch(Exception e) {
        System.out.println("*hibernate insert Exception: "+e.getMessage());
    }

    HibernateUtil.closeSession();
}
}

Hibernate is using c3p0 pooling.
The Db.Insert is then called from JSP pages in a busy server production environment.
My question is, if I removed the 'synchronized' on Db.Insert(Object) Would this cause issues?
I realise it's something I should most likely know already, but don't and don't want to try it out and get errors.
Also if it's likely to cause said issues, then I'm not sure if I understand the point of using c3p0 for connection pooling... my understanding at the moment is calling HibernateUtil.currentSession(); or hibernateSession.beginTransaction(); calls an available connection from the c3p0 pool and never the twain shall meet.
Sorry for the first bit of code not being 'code' displayed, this webform just does not want to work correctly.
Thanks for reading

A: There won't be any problems if you do remove synchronized in fact your Application might just perform a little better.
Depending on the your hibernate configuration. Hibernate will request a connection from the pool for either the life of the session or for the life of the transaction.


text:
Q: Pandas shifted value calculation I'd like to create a new column, containing values calculated from shifted value in other columns.
As you see the code below, first I created a time series data.
'price' is randomly generated time series data, and momentum is average momentum value of recent 12 periods.
I'd like to add a new columns, containing data with average 'n' momentum value, in which 'n' correspond to the value of df['shift'], not with fixed 12 value in the momentum function, but with the value in the 'shift' column.
How can I do this?
(In the example below, momentum was calculated with fixed 12)
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.uniform(low=0.8, high=1.3, size=100).cumprod(),columns = ['price'])
df['shift'] =  np.random.randint(5, size=100)+3
df

def momentum(x):
    init = 0
    for i in range(1, 13):
        init = x.price / x.price.shift(i) + init
    return init / 12

df['momentum'] = momentum(df)

       price  shift  momentum
0   1.069857      3       NaN
1   0.986563      7       NaN
2   0.809052      5       NaN
3   0.991204      3       NaN
4   0.846159      6       NaN
5   0.717344      4       NaN
6   0.599436      3       NaN
7   0.596711      7       NaN
8   0.543450      4       NaN
9   0.511640      3       NaN
10  0.496865      3       NaN
11  0.460142      4       NaN
12  0.435862      4  0.657192
13  0.410519      4  0.665493
14  0.368428      5  0.640927
15  0.335583      7  0.625128
16  0.313470      7  0.635423
17  0.321265      4  0.704990
18  0.319503      7  0.746885
19  0.365991      4  0.900135
20  0.300793      4  0.766266
21  0.274449      6  0.733104

A: This is my approach
def momentum(shift,price,array,index):
    if shift > index:
        return 0
    else:
        init = 0
        for i in range(1,int(shift)+1):
            init += price / array[int(index)-i]
        return init

df = pd.DataFrame(np.random.uniform(low=0.8, high=1.3, size=100).cumprod(),columns = ['price'])
df['shift'] = np.random.randint(5, size=100)+3
df['Index'] = df.index
series = df['price'].tolist()

df['momentum'] = df.apply(lambda row: momentum(row['shift'],row['price'],series,row['Index']),axis=1)
print df


text:
Q: get selected option of multi dropdown jquery angular dosn't work Hello I'm workig with jquery in angular app, I want to get all selected option of many select list in my component ts file with jquery, what I did :

    $("#selectProp select").each(() => {

      var t = $(this);
      console.log($(this))
      //arr.push($(this).val());
    });
    console.log(arr)

Here with this I want to get the select with selected option from user but in this I get :

0 => jQuery.fn.init(1)   AppComponent

Here I get the values declared in export class AppComponent
And Here my Html :

                Morceau {{i + 1}}

                  <select id="selectAttribut">
                    <option *ngFor="let prop of lstProp512" [value]="prop.Text">
                      {{prop.Text}}
                    </option>
                  </select>

A: Like this it is working :

    $('#selectProp select').each((index, element) => {
      var conceptName = $(element).find(":selected").text();
      console.log(conceptName);
    })


text:
Q: httpErrors - Redirect 403 to HTML file - How to? I am trying to redirect to a html file when I receive a 403 error in my application. This is handled by IIS, so i have added this into my web config:
<httpErrors errorMode="Custom" >
      <remove statusCode="403"/>
      <error statusCode="403" responseMode="File" path="/500.html"/>
    </httpErrors>

Which gives me this error:
You do not have permission to view this directory or page.

However if I change the response mode to ExecuteURL it will redirect to the page. But it will show a http status code of 200, whereas file will keep the 403 error. I just can't get it to redirect to this file.
Can anyone help me fix this issue?

A: According to the description of the system.webserver/httperrors/error configuration node (https://www.iis.net/configreference/system.webserver/httperrors/error), setting the responseMode attribute to File requires provding an absolute Windows path to the error page. As in the example below:

<configuration>
   <system.webServer>
      <httpErrors errorMode="DetailedLocalOnly" defaultResponseMode="File" >
         <remove statusCode="500" />
         <error statusCode="500"
            prefixLanguageFilePath="C:\Contoso\Content\errors"
            path="500.htm" />
       </httpErrors>
   </system.webServer>
</configuration>


text:
Q: Unable to get the id of newly created record sails js I am creating a new record like this:
  Resource.create({
    title: req.body.title,
    address: {...req.body.address},
    email: req.body.email,
  }, (err, record) =>{
    if(err){
      res.send({'status': err});
    }else{
      res.send(
        {
          'status': 'it worked',
          'data': req.body
        }
      );
      sails.log(record.title)
    }
  });

The request process perfectly and the new record is added to the database(I can see it too). But I cant get the id right when its created for some weird reason.
I've been following a tutorial and record is supposed to not be undefined, I am using MongoDB with SailsJS

A: You have to chain a "fetch" after creating the record, for example:
let resource = Resource.create({...}).fetch();

This will fetch the record you just created with its associated id.


text:
Q: $H{'}$ is a subgroup of the quotient group $G/N$ $\Leftrightarrow$ $H{'}=H/N$ for some $H$ such that $H$ is a subgroup of $G$ and $H\supset N$. I am afraid that my question is very stupid.

Let $G$ be a group.
Let $N$ be a normal subgroup of $G$.
Then,
$H{'}$ is a subgroup of the quotient group $G/N$
$\Leftrightarrow$
$H{'}=H/N$ for some $H$ such that $H$ is a subgroup of $G$ and $H\supset N$.

Proof:
($\Rightarrow$)
Let $H:=\{a\in G\mid aN\in H{'}\}$.
Let $X\in H^{'}$.
Then, $X=aN$ for some $a\in G$.
So, $a\in H$.

Fact1:
Let $b\in H$.
Then the following holds:
$x\in\{x\in H\mid b^{-1}x\in N\}$.
$\Leftrightarrow$
$b^{-1}x=n$ for some $n\in N$ and $x\in H$.
$\Leftrightarrow\,\,\,\,$ (Note that $b\in H$ and $n\in N\subset H$)
$x=bn$ for some $n\in N$.
$\Leftrightarrow$
$x\in bN$.

By Fact1, $X=aN=\{x\in H\mid a^{-1}x\in N\}\in H/N$.
Conversely, let $X\in H/N$.
Then, $X=\{x\in H\mid a^{-1}x\in N\}$ for some $a\in H$.
By Fact1, $X=aN$.
Since $a\in H$, $aN\in H{'}$.
So, $X\in H{'}$.

($\Leftarrow$)
Suppose that $H{'}=H/N$ for some $H$ such that $H$ is a subgroup of $G$ and $H\supset N$.
We show $H{'}\subset G/N$ holds.
Let $X\in H{'}$.
Then, $X=\{x\in H\mid a^{-1}x\in N\}$ for some $a\in H$.
By Fact1, $X=aN$.
So, $X\in G/N$.
Since $H{'}$ itself is a group, $H{'}$ is a subgroup of the quotient group $G/N$.

https://math.stackexchange.com/a/3278269/384082
When I read the above answer to a question, I feel uncomfortable.
I proved the following fact:
$H{'}$ is a subgroup of the quotient group $G/N$
$\Leftrightarrow$
$H{'}=H/N$ for some $H$ such that $H$ is a subgroup of $G$ and $H\supset N$.
$H{'}$ is a set whose elements are left cosets of $N$ in $\color{blue}{G}$.
$H/N$ is the set of the left cosets of $N$ in $\color{red}{H}$.
So, when I write $H{'}=H/N$, I feel uncomfortable.
I want to write $H{'}\cong H/N$.
Is it really ok to write $H{'}=H/N$?


text:
Q: You cannot specify the same gem twice with different version requirements I have 2 plugins installed(redmine_backlogs and redmine_ldap_sync), but after upgrade of redmine_ldap_sync from 2.0.0 to 2.0.1 a Gemfile was added.
Here the backlogs's Gemfile https://github.com/backlogs/redmine_backlogs/blob/v1.0.2/Gemfile
and ldap sync's Gemfile https://github.com/thorin/redmine_ldap_sync/blob/2.0.1/Gemfile
In both cases, the simplecov is in the test group. I tried to run
bundle install --without development test

but I got this error:
You cannot specify the same gem twice with different version requirements.
You specified: simplecov (>= 0) and simplecov (~> 0.6)

This does not seem to make sense. Is there a way to bypass it without editing the file?
Thanks

A: All Gemfiles from plugins are merged with general one. Just delete simplecov (>= 0) statement in one of the plugins Gemfile. It is not criminal or illegal.


text:
Q: Jest mocked class force different response, typescript this is me again with very simple example.
In resumen i need a different response for the mocked class.
This is my simple class that return an object
            class Producer {
                hello() {
                    return {
                        message:'Class: Hello',
                    }
                }
            }
            export default Producer;

this is the mock class in the __mocks__ folder
            class Producer {
                hello() {
                    return {
                        message:'__mocks__: hello',
                    }
                }
            }
            export default Producer;

This is my test file that works as i expected
            import Consumer from './Consumer';
            jest.mock('./Producer');
            test('simple test 1', () => {
                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('__mocks__: hello')
                console.log(consumer.response)
                // prints on console { message: '__mocks__: hello' }
            });

My question is, for other test i need a different response from the mocked file Producer
            jest.mock('./Producer').updateOnTheFly( hello() {
                    return {
                        message:'UPDATE ON FLY: hello',
                    }
            })
            test('simple test 1', () => {

                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('UPDATE ON FLY: hello')
            });

A: For something like this it can be easier to not create a manual mock at __mocks__/Producer.js.
Instead, use jest.mock('./Producer'); to auto-mock the module...
...then mock the return value for Producer.prototype.hello as needed:
import Consumer from './Consumer';

import Producer from './Producer';
jest.mock('./Producer');  // <= auto-mock Producer

test('simple test 1', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'mocked: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('mocked: hello')  // Success!
});

test('simple test 2', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'UPDATED: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('UPDATED: hello')  // Success!
});

A: Well, after some re-search i resolved with this.
        class Producer {
            hello() {
                return {
                    message:' Class: Hello ',
                }
            }
        }
        export default Producer;

Mocking the Producer, it is not neccesary create mock file
        import Consumer from './Consumer';
        jest.mock('./Producer');

        test('simple test 1', () => {
            // mocking Producer.hello()
            Producer.mockImplementation(() => {
                return {
                    hello: () => {
                        return {
                            message: "ths is mocked "
                        }
                    },
                };
            });

            let consumer = new Consumer();
            consumer.call(); /// Consume.call() uses inside Producer.hello() mocked
        })


text:
Q: Why doesn't this work? Calling functions belonging to objects in a loop In my code jsc.tools is an object containing objects. Each sub-object contains a init() and run() method.
I have the following code running at startup:
for(tool in jsc.tools) {
    tool.init();
}

which gives me the error "tool.init is not a function".
A sample of a tool's declaration is:
jsc.tools.sometool = {};
jsc.tools.sometool.run = function() {
    // Apply tool
}
jsc.tools.sometool.init = function() {
    // Set bits of data needed for the tool to run
}

A: The for in x operator in javascript gives you the names of the properties off an object. Try:
for(tool in jsc.tools) {
    jsc.tools[tool].init();
}

A: you need to use
for(tool in jsc.tools) {
    jsc.tools[tool].init();
}


text:
Q: Magento Difference between checkout cart and checkout session Can anyone state what is the difference between
Mage::getSingleton('checkout/session');

and
Mage::getSingleton('checkout/cart');

A: *

*Mage::getSingleton('checkout/cart') is Shopping cart model class.It's create Varien_Object.
Mage::getSingleton('checkout/session') is session class with 'checkout' namespace. This stores information related to the quote, guest or not (cart totals, items, checkout progress)

*Mage::getSingleton('checkout/cart') class depends on Mage::getSingleton('checkout/session') when adding/updating/deleting product.


text:
Q: How to automatically display new sms in listview using gsm modem? So far i have this code
 public void read()
    {
        //port is already open
        port.Write("AT" + System.Environment.NewLine);
        //Thread.Sleep(1000);
        port.Write("AT+CMGF=1" + System.Environment.NewLine);
        //Thread.Sleep(1000);
        port.Write("AT+CMGL=\"ALL\"\r" + System.Environment.NewLine);
        //Thread.Sleep(3000);
        //MessageBox.Show(port.ReadExisting());

        Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
        Match m = r.Match(port.ReadExisting());
        while (m.Success)
        {
            string a = m.Groups[1].Value;
            string b = m.Groups[2].Value;
            string c = m.Groups[3].Value;
            string d = m.Groups[4].Value;
            string ee = m.Groups[5].Value;
            string f = m.Groups[6].Value;

            ListViewItem item = new ListViewItem(new string[] { a, b, c, d, ee, f });
            lvwMessages.Items.Add(item);
            m = m.NextMatch();
        }
        lvwMessages.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        lvwMessages.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        sd.Width = 0;
    }

this code gets triggered in a button click event, what im wondering is, is it possible to automatically display new sms without repeatedly calling read() in a timer? using timer causes the listview to blink and lose its selection.
i am working on a winform by the way.


text:
Q: What is the equivalent GWT/Java Syntax of some JavaScript expressions? I have an algorithm in JavaScript which I want to transform into Java.
Here is the JavaScript code:
    function downScaleCanvas(cv, scale) {
        if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number <1 ');
        var sqScale = scale * scale; // square scale = area of source pixel within target
        var sw = cv.width; // source image width
        var sh = cv.height; // source image height
        var tw = Math.ceil(sw * scale); // target image width
        var th = Math.ceil(sh * scale); // target image height
        var sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
        var tx = 0, ty = 0, yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
        var tX = 0, tY = 0; // rounded tx, ty
        var w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
        // weight is weight of current source point within target.
        // next weight is weight of current source point within next target's point.
        var crossX = false; // does scaled px cross its current px right border ?
        var crossY = false; // does scaled px cross its current px bottom border ?
        var sBuffer = cv.getContext('2d').getImageData(0, 0, sw, sh).data; // source buffer 8 bit rgba
        var tBuffer = new Float32Array(4 * sw * sh); // target buffer Float32 rgb
        var sR = 0, sG = 0,  sB = 0; // source's current point r,g,b
        // untested !
        var sA = 0;  //source alpha

        for (sy = 0; sy < sh; sy++) {
            ty = sy * scale; // y src position within target
            tY = 0 | ty;     // rounded : target pixel's y
            yIndex = 4 * tY * tw;  // line index within target array
            crossY = (tY != (0 | ty + scale));
            if (crossY) { // if pixel is crossing botton target pixel
                wy = (tY + 1 - ty); // weight of point within target pixel
                nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
            }
            for (sx = 0; sx < sw; sx++, sIndex += 4) {
                tx = sx * scale; // x src position within target
                tX = 0 |  tx;    // rounded : target pixel's x
                tIndex = yIndex + tX * 4; // target pixel index within target array
                crossX = (tX != (0 | tx + scale));
                if (crossX) { // if pixel is crossing target pixel's right
                    wx = (tX + 1 - tx); // weight of point within target pixel
                    nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
                }
                sR = sBuffer[sIndex    ];   // retrieving r,g,b for curr src px.
                sG = sBuffer[sIndex + 1];
                sB = sBuffer[sIndex + 2];
                sA = sBuffer[sIndex + 3];

                if (!crossX && !crossY) { // pixel does not cross
                    // just add components weighted by squared scale.
                    tBuffer[tIndex    ] += sR * sqScale;
                    tBuffer[tIndex + 1] += sG * sqScale;
                    tBuffer[tIndex + 2] += sB * sqScale;
                    tBuffer[tIndex + 3] += sA * sqScale;
                } else if (crossX && !crossY) { // cross on X only
                    w = wx * scale;
                    // add weighted component for current px
                    tBuffer[tIndex    ] += sR * w;
                    tBuffer[tIndex + 1] += sG * w;
                    tBuffer[tIndex + 2] += sB * w;
                    tBuffer[tIndex + 3] += sA * w;
                    // add weighted component for next (tX+1) px
                    nw = nwx * scale;
                    tBuffer[tIndex + 4] += sR * nw; // not 3
                    tBuffer[tIndex + 5] += sG * nw; // not 4
                    tBuffer[tIndex + 6] += sB * nw; // not 5
                    tBuffer[tIndex + 7] += sA * nw; // not 6
                } else if (crossY && !crossX) { // cross on Y only
                    w = wy * scale;
                    // add weighted component for current px
                    tBuffer[tIndex    ] += sR * w;
                    tBuffer[tIndex + 1] += sG * w;
                    tBuffer[tIndex + 2] += sB * w;
                    tBuffer[tIndex + 3] += sA * w;
                    // add weighted component for next (tY+1) px
                    nw = nwy * scale;
                    tBuffer[tIndex + 4 * tw    ] += sR * nw; // *4, not 3
                    tBuffer[tIndex + 4 * tw + 1] += sG * nw; // *4, not 3
                    tBuffer[tIndex + 4 * tw + 2] += sB * nw; // *4, not 3
                    tBuffer[tIndex + 4 * tw + 3] += sA * nw; // *4, not 3
                } else { // crosses both x and y : four target points involved
                    // add weighted component for current px
                    w = wx * wy;
                    tBuffer[tIndex    ] += sR * w;
                    tBuffer[tIndex + 1] += sG * w;
                    tBuffer[tIndex + 2] += sB * w;
                    tBuffer[tIndex + 3] += sA * w;
                    // for tX + 1; tY px
                    nw = nwx * wy;
                    tBuffer[tIndex + 4] += sR * nw; // same for x
                    tBuffer[tIndex + 5] += sG * nw;
                    tBuffer[tIndex + 6] += sB * nw;
                    tBuffer[tIndex + 7] += sA * nw;
                    // for tX ; tY + 1 px
                    nw = wx * nwy;
                    tBuffer[tIndex + 4 * tw    ] += sR * nw; // same for mul
                    tBuffer[tIndex + 4 * tw + 1] += sG * nw;
                    tBuffer[tIndex + 4 * tw + 2] += sB * nw;
                    tBuffer[tIndex + 4 * tw + 3] += sA * nw;
                    // for tX + 1 ; tY +1 px
                    nw = nwx * nwy;
                    tBuffer[tIndex + 4 * tw + 4] += sR * nw; // same for both x and y
                    tBuffer[tIndex + 4 * tw + 5] += sG * nw;
                    tBuffer[tIndex + 4 * tw + 6] += sB * nw;
                    tBuffer[tIndex + 4 * tw + 7] += sA * nw;
                }
            } // end for sx
        } // end for sy

        // create result canvas
        var resCV = document.createElement('canvas');
        resCV.width = tw;
        resCV.height = th;
        var resCtx = resCV.getContext('2d');
        var imgRes = resCtx.getImageData(0, 0, tw, th);
        var tByteBuffer = imgRes.data;
        // convert float32 array into a UInt8Clamped Array
        var pxIndex = 0; //
        for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 4, tIndex += 4, pxIndex++) {
            tByteBuffer[tIndex] = Math.ceil(tBuffer[sIndex]);
            tByteBuffer[tIndex + 1] = Math.ceil(tBuffer[sIndex + 1]);
            tByteBuffer[tIndex + 2] = Math.ceil(tBuffer[sIndex + 2]);
            tByteBuffer[tIndex + 3] = Math.ceil(tBuffer[sIndex + 3]);
        }
        // writing result to canvas.
        resCtx.putImageData(imgRes, 0, 0);
        return resCV;
    }

Here is what I did so far in Java:
    public static final CanvasElement scaleCanvas(CanvasElement cv, double scale) {

        if (!(scale < 1) || !(scale > 0)) {
//          throw new Exception("scale must be a positive number <1 ");
        }

        double sqScale = scale * scale; // square scale = area of source pixel within target
        int sw = cv.getWidth(); // source image width
        int sh = cv.getHeight(); // source image height
        double tw = Math.ceil(sw * scale); // target image width
        double th = Math.ceil(sh * scale); // target image height
        int sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
        double tx = 0, ty = 0;
        int yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
        double tX = 0, tY = 0; // rounded tx, ty
        double w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
        // weight is weight of current source point within target.
        // next weight is weight of current source point within next target's point.
        boolean crossX = false; // does scaled px cross its current px right border ?
        boolean crossY = false; // does scaled px cross its current px bottom border ?
        CanvasPixelArray sBuffer = cv.getContext2d().getImageData(0, 0, sw, sh).getData(); // source buffer 8 bit rgba
        Float32Array tBuffer = TypedArrays.createFloat32Array(4 * sw * sh);

        double sR = 0, sG = 0,  sB = 0; // source's current point r,g,b
        // untested !
        double sA = 0;  //source alpha

        for (sy = 0; sy < sh; sy++) {
             GWT.log("sy: "+sy+" sh: "+sh);

            ty = sy * scale; // y src position within target
            tY = (long)ty;     // rounded : target pixel's y                            // ?????
            yIndex = (int)Math.floor(4 * tY * tw);  // line index within target array
            crossY = (tY != ( (long)(ty + scale) ));                                                    // ?????
            if (crossY) { // if pixel is crossing botton target pixel
                wy = (tY + 1 - ty); // weight of point within target pixel
                nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
            }
            for (sx = 0; sx < sw; sx++, sIndex += 4) {
                tx = sx * scale; // x src position within target
                tX = (long)tx;    // rounded : target pixel's x                             // ?????
                tIndex = (int)Math.floor(yIndex + tX * 4); // target pixel index within target array                    // ?????
                crossX = (tX != ((int)Math.floor(tx + scale)));
                if (crossX) { // if pixel is crossing target pixel's right
                    wx = (tX + 1 - tx); // weight of point within target pixel
                    nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
                }
                sR = sBuffer.get(sIndex);   // retrieving r,g,b for curr src px.
                sG = sBuffer.get(sIndex + 1);
                sB = sBuffer.get(sIndex + 2);
                sA = sBuffer.get(sIndex + 3);

                if (!crossX && !crossY) { // pixel does not cross
                    // just add components weighted by squared scale.

                    tBuffer.set(tIndex    , (float)(tBuffer.get(tIndex)     + sR * sqScale));
                    tBuffer.set(tIndex + 1, (float)(tBuffer.get(tIndex + 1) + sG * sqScale));
                    tBuffer.set(tIndex + 2, (float)(tBuffer.get(tIndex + 2) + sB * sqScale));
                    tBuffer.set(tIndex + 3, (float)(tBuffer.get(tIndex + 3) + sA * sqScale));
                } else if (crossX && !crossY) { // cross on X only
                    w = wx * scale;
                    // add weighted component for current px
                    tBuffer.set(tIndex    , (float)(tBuffer.get(tIndex)     + sR * w));
                    tBuffer.set(tIndex + 1, (float)(tBuffer.get(tIndex + 1) + sG * w));
                    tBuffer.set(tIndex + 2, (float)(tBuffer.get(tIndex + 2) + sB * w));
                    tBuffer.set(tIndex + 3, (float)(tBuffer.get(tIndex + 3) + sA * w));

                    // add weighted component for next (tX+1) px
                    nw = nwx * scale;
                    tBuffer.set(tIndex + 4, (float)(tBuffer.get(tIndex + 4) + sR * nw));        // not 3
                    tBuffer.set(tIndex + 5, (float)(tBuffer.get(tIndex + 5) + sG * nw));        // not 4
                    tBuffer.set(tIndex + 6, (float)(tBuffer.get(tIndex + 6) + sB * nw));        // not 5
                    tBuffer.set(tIndex + 7, (float)(tBuffer.get(tIndex + 7) + sA * nw));        // not 6
                } else if (crossY && !crossX) { // cross on Y only
                    w = wy * scale;
                    // add weighted component for current px
                    tBuffer.set(tIndex    , (float)(tBuffer.get(tIndex)     + sR * w));
                    tBuffer.set(tIndex + 1, (float)(tBuffer.get(tIndex + 1) + sG * w));
                    tBuffer.set(tIndex + 2, (float)(tBuffer.get(tIndex + 2) + sB * w));
                    tBuffer.set(tIndex + 3, (float)(tBuffer.get(tIndex + 3) + sA * w));

                    // add weighted component for next (tY+1) px
                    nw = nwy * scale;
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw)    , (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw))     + sR * nw));    // *4, not 3
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 1), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 1)) + sG * nw));    // *4, not 3
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 2), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 2)) + sB * nw));    // *4, not 3
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 3), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 3)) + sA * nw));    // *4, not 3
                } else { // crosses both x and y : four target points involved
                    // add weighted component for current px
                    w = wx * wy;
                    tBuffer.set(tIndex    , (float)(tBuffer.get(tIndex) + sR * w));
                    tBuffer.set(tIndex + 1, (float)(tBuffer.get(tIndex + 1) + sG * w));
                    tBuffer.set(tIndex + 2, (float)(tBuffer.get(tIndex + 2) + sB * w));
                    tBuffer.set(tIndex + 3, (float)(tBuffer.get(tIndex + 3) + sA * w));
                    // for tX + 1; tY px
                    nw = nwx * wy;
                    tBuffer.set(tIndex + 4, (float)(tBuffer.get(tIndex + 4) + sR * nw));    // same for x
                    tBuffer.set(tIndex + 5, (float)(tBuffer.get(tIndex + 5) + sG * nw));
                    tBuffer.set(tIndex + 6, (float)(tBuffer.get(tIndex + 6) + sB * nw));
                    tBuffer.set(tIndex + 7, (float)(tBuffer.get(tIndex + 7) + sA * nw));
                    // for tX ; tY + 1 px
                    nw = wx * nwy;
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw)    , (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw))     + sR * nw));    // same for mul
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 1), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 1)) + sG * nw));
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 2), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 2)) + sB * nw));
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 3), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 3)) + sA * nw));
                    // for tX + 1 ; tY +1 px
                    nw = nwx * nwy;
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 4), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 4)) + sR * nw)); // same for both x and y
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 5), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 5)) + sG * nw));
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 6), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 6)) + sB * nw));
                    tBuffer.set((int)Math.floor(tIndex + 4 * tw + 7), (float)(tBuffer.get((int)Math.floor(tIndex + 4 * tw + 7)) + sA * nw));
                }
            } // end for sx
        } // end for sy

        // create result canvas
        Canvas resCV = Canvas.createIfSupported();
        resCV.getCanvasElement().setWidth((int)Math.floor(tw));
        resCV.getCanvasElement().setHeight((int)Math.floor(th));
        Context2d resCtx = resCV.getContext2d();
        ImageData imgRes = resCtx.getImageData(0, 0, tw, th);
        CanvasPixelArray tByteBuffer = imgRes.getData();
        // convert float32 array into a UInt8Clamped Array
        int pxIndex = 0;
        for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 4, tIndex += 4, pxIndex++) {
            tByteBuffer.set(tIndex, (int)Math.ceil(tBuffer.get(sIndex)));
            tByteBuffer.set(tIndex + 1, (int)Math.ceil(tBuffer.get(sIndex + 1)));
            tByteBuffer.set(tIndex + 2, (int)Math.ceil(tBuffer.get(sIndex + 2)));
            tByteBuffer.set(tIndex + 3, (int)Math.ceil(tBuffer.get(sIndex + 3)));
        }
        // writing result to canvas.
        resCtx.putImageData(imgRes, 0, 0);

        return resCV.getCanvasElement();

    }

I am not sure how to write an expression like thit tY = 0 | ty in Java. I am also not sure if canvas.width(value); transforms into canvas.setCoordinateSpaceWidth(value);
Edit:
Is (0 | ty + scale) in JS is ((long)ty + scale) in Java?
What is the translation of
var sBuffer = cv.getContext('2d').getImageData(0, 0, sw, sh).data

is it CanvasPixelArray
CanvasPixelArray sBuffer = cv.getContext2d().getImageData(0, 0, sw, sh).getData()

Can someone help me with the translation?
Edit: It turns out that my Java code is very slow. I cannot run it in dev mode. In prod mode  it is event slower than the JavaScript code. Why is this code slower?

A: 0 | tY is rounding a JS Number (equivalent to a Java double) to an integer value; equivalent to Math.floor(tY) or (long) tY (int is too small for all integer values that can be expressed in a double, but might be OK in this specific case).
canvas.width maps to Canvas#getCoordinateSpaceWidth, as you can see in GWT sources.
Finally, new Float32Array(n) maps to TypedArrays.createFloat32Array.


text:
Q: XPATH to count the occurrence of child nodes in ancestor I need to count the occurrence of the child <title> nodes in the <foreword><?> element. My problem is the parent nodes of the <title> element have different names, but they all have <title> elements.
I tried using count(*) but this didn't work, it comes back "0". And if I use count(/doc/front/foreword/*/title) it comes back with '16'. How do I count the occurrence of the <title> elements inside the <foreword><?> element?
    <doc>
    <front>
    <lep></lep>
    <verstat></verstat>
    <contents></contents>
    <illuslist></illuslist>
    <tablelist></tablelist>
    <foreword>
    <para0><title>para0</title></para0>
    <applicdef><title>applicdef</title></applicdef>
    <applicdef><title>applicdef</title></applicdef>
    <applicdef><title>applicdef</title></applicdef>
    <applicdef><title>applicdef</title></applicdef>
    <applicdef><title>applicdef</title></applicdef>
    <para0><title>para0</title></para0>
    <para0><title>para0</title></para0>
    <para0><title>para0</title></para0>
    <para0><title>para0</title></para0>
    </foreword>
    </front>
    </doc>

I numbered the title elements with the number that should be displayed (1.0 purpose, 2. applic...etc.
so the output would be like
    <para0><title>1. para0</title></para0>
    <applicdef><title>2.applicdef</title></applicdef>
    <applicdef><title>3.applicdef</title></applicdef>
    <applicdef><title>4.applicdef</title></applicdef>
    <applicdef><title>5.applicdef</title></applicdef>
    <applicdef><title>6.applicdef</title></applicdef>

A: Let's use your real life scenario, i.e. XSLT. Here is a solution by using identity transform.
Input XML
<?xml version="1.0"?>
<doc>
    <front>
        <lep></lep>
        <verstat></verstat>
        <contents></contents>
        <illuslist></illuslist>
        <tablelist></tablelist>
        <foreword>
            <para0>
                <title>para0</title>
            </para0>
            <applicdef>
                <title>applicdef</title>
            </applicdef>
            <applicdef>
                <title>applicdef</title>
            </applicdef>
            <applicdef>
                <title>applicdef</title>
            </applicdef>
            <applicdef>
                <title>applicdef</title>
            </applicdef>
            <applicdef>
                <title>applicdef</title>
            </applicdef>
            <para0>
                <title>para0</title>
            </para0>
            <para0>
                <title>para0</title>
            </para0>
            <para0>
                <title>para0</title>
            </para0>
            <para0>
                <title>para0</title>
            </para0>
        </foreword>
    </front>
</doc>

XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="title">
        <title>
            <xsl:value-of select="concat(count(../preceding-sibling::*)+1,'. ', .)"/>
        </title>
    </xsl:template>
</xsl:stylesheet>

Output
<doc>
  <front>
    <lep/>
    <verstat/>
    <contents/>
    <illuslist/>
    <tablelist/>
    <foreword>
      <para0>
        <title>1. para0</title>
      </para0>
      <applicdef>
        <title>2. applicdef</title>
      </applicdef>
      <applicdef>
        <title>3. applicdef</title>
      </applicdef>
      <applicdef>
        <title>4. applicdef</title>
      </applicdef>
      <applicdef>
        <title>5. applicdef</title>
      </applicdef>
      <applicdef>
        <title>6. applicdef</title>
      </applicdef>
      <para0>
        <title>7. para0</title>
      </para0>
      <para0>
        <title>8. para0</title>
      </para0>
      <para0>
        <title>9. para0</title>
      </para0>
      <para0>
        <title>10. para0</title>
      </para0>
    </foreword>
  </front>
</doc>


text:
Q: Show a loading image when page load in c# I need to show a loading image when page load in c#.
I've tried using this solution without success, because the error is:
Line 72:             this.Response.Write(@"dots++;");

I would greatly appreciate any help you can give me in working this problem.
Here is my code:
");

        this.Response.Write(@"");

        this.Response.Flush();
        System.Threading.Thread.Sleep(500);
    }
</script>

A: I guess you want to show a loading image when page load.
If that is the case the you can use Jquery Load event to show a loading image.
Try this: http://jsbin.com/izetOcAP/2/edit

A: Using Response.Writes like that is crazy! One way you could do it and keep your hair in the process is:
html

My hair is still here.

css
.load{
    background-color:#e6e6e6;
}

.load.complete{
    background-color:transparent;
}

js
$(document).ready(function(){
    this.body.className = 'load complete';
})

Here's a fiddle of a very quick example http://jsfiddle.net/rp6oourg/.


text:
Q: If I delete an existing project from Google Cloud API, will it increase my quota? Suppose I have only 1 project left in my quota. If I delete an existing project, will it make it 2 projects in my quota?

A: If you are left with fewer projects in your Quota, a notification will be displayed showing of projects you are left with to do in your Quota Page. If you have reached the Limit, either you can request for Quota increase or you can delete a project.
According to your concern , if you are left with only 1 project in your quota  and if you delete the existing project , it will not immediately make 2 projects in your quota.
Reason is : when we delete or shutdown a project it has a LifeCycle and it stays for 30 days. After 30 days it gets deleted completely.Until it is deleted, the project counts towards your project quota. so basically if you delete your existing project  it will not make 2 projects in your quota until the project  has got deleted completely.
Managing Project Quota
delete or shutdown a project


text:
Q: updating a dict inside a list I have the following data structure in TCL (list of dicts)
list [{1 a 2 b} {1 c 2 d} {1 e 2 d}]
as you can see there are three dicts with the same keys inside a list.
I want to update d with, lets say P only of e is there, else construct the dict {1 e 2 P} and append to the list.
Whether, I update or append, at the end I should have this
list [{1 a 2 b} {1 c 2 d} {1 e 2 P}]
I know I can iterate and achieve this, but that seems ugly. is there any shorter method to do this. I am not very familiar with TCL advanced dict commands, so any help much appreciated
thanks

A: Approach 1 :
% set input
{1 a 2 b} {1 c 2 d} {1 e 2 d}
% #index 2 3 points to 'd'
% lset x 2 3 P
{1 a 2 b} {1 c 2 d} {1 e 2 P}
%

Approach 2 :
% set input {{1 a 2 b} {1 c 2 d} {1 e 2 d}}
{1 a 2 b} {1 c 2 d} {1 e 2 d}
% #The element to search and replace...
% set elem {1 e 2 d}
1 e 2 d
%
% lset input [lsearch $input $elem] [dict replace $elem 2 P]
{1 a 2 b} {1 c 2 d} {1 e 2 P}
%

A: I think the easiest way is to use lmap to iterate over the list, conditionally doing the dictionary transform and setting a flag if it ever gets done. Then, if there was no such change done, append the new dictionary at the end.
set input {{1 a 2 b} {1 c 2 d} {1 e 2 d}}

set replaced 0
set output [lmap d $input {
    if {[dict exists $d 1] && [dict get $d 1] eq "e"} {
        set replaced 1
        dict set d 2 "P"
    }
    set d
}]
if {!$replaced} {
    lappend output [dict create 1 e 2 "P"]
}

If you're using 8.5, you can use foreach and lappend instead of lmap. The code is a bit longer if you do.


text:
Q: Selenium output url I need to test an output of a page without making it pop up, but just go to the url.
If you have a pdf or word export link how would you test its contents.

A: The answer is to step outside of Selenium

*

*To test a URL without making the window pop-up, consider downloading the contents of the URL without Selenium. I'm assuming you are using Java, so look into downloading the content of a URL in java. It also depends on what you are testing, this works if you want to just check if a URL is broken or not for example.

*To check the contents of a PDF or a Word file, you also can't use Selenium. You will need to find a Java library to parse the PDF and Word files and then use that to read the content.
As you can see both require a bit of research on your part. The key is not getting hung up on Selenium and making use of the rest of the programming language.


text:
Q: Block a command I don't want any admin users in my system to execute the following command other than root.
"sudo cp /etc/sudoers "
Is it possible to block it for admin users only?
I have tried lot but didn't get anything?

A: If you don't trust someone to have full shell access on your system, don't give them shell access at all.
You want to stop cp command what about other commands that acts like cp , what about if admins use scp command .
Am not saying its impossible to block this command , but a play around trick will defeat your goal .