text:
Q: Getting load average as variables I'm setting up a logging script with Ruby and am having some difficulties with getting the load averages as a variable.  I'm using:
uptime | awk '{print $10}'

to get the current 1 minute time stamp, but I'm having trouble getting it without a trailing comma.  I could edit the string later, but that seems less efficient.  Is there an edit that will simply remove the , from the return?

A: How about:
cut -f 1 -d " " /proc/loadavg

The uptime command reads /proc/loadavg and then adds the commas.

A: In the end, it also works through /proc/loadavg, but the usage is a little more idiomatic, so I thought I'd mention the sys-cpu Gem (which existed even in 2013 :)) as well:
gem install sys-cpu

require 'sys-cpu'
puts Sys::CPU.load_avg

... which will give you a nice array: [0.72, 1.14, 1.11].


text:
Q: Website is not loading in chrome and firefox My magento website is not loading in chrome and firefox.It works fine in IE only. I cleared the chrome cache and history but it not display my website it shows like "This webpage is not available  ERR_SSL_VERSION_OR_CIPHER_MISMATCH ". How to solve this error i am working on this issue for last 2 days.

A: That's nothing to do with your website as such, that's a server configuration issue.
Most likely your server is still trying to serve https requests using SSL3, which has been removed in Chrome 40 (and I guess firefox as well, but I don't have the changelogs to hand to check)
This is a good tool to check your SSL settings:
https://www.ssllabs.com/ssltest/
This will confirm any issues, and advise on fixes.
If you don't have full server access, then you'll need to speak to your host.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring boot + Angularjs + 3rd party resources I am working on a spring boot application. My AngularJS app is placed in the src/main/resources/static folder. I want to interact with a 3rd party application. This requires

*

*Load an external JS from cdn

*Use their JS SDK to connect to their REST APIs.

Issue is

*

*Added the external JS in index.html. But on loading it gives following error
Refused to load the script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'".
Added <meta http-equiv="Content-Security-Policy" content="script-src  <cdn-domain> 'self';"> but issue persists.

*Suppose I download the js, the above error goes away. But when I try to hit the API using the custom JS, again requests get blocked(same error, different domain).

Please suggest what can be done.


text:
Q: Python to Javascript >>> def clockwise(r):
...     return list(r[0]) + clockwise(list(reversed(zip(*r[1:])))) if r else []
...
>>> a = [
...   [ 1,  2,  3],
...   [ 5,  6,  7],
...   [ 9, 10, 11]]
>>> clockwise(a)
[1, 2, 3, 7, 11, 10, 9, 5, 6]

I'm trying to change the function clockwise into Javascript but can't seem to get it to work.
I've created some methods with similar functions:
function zip(masterArray){//zips 2 arrays
var innerLoop = masterArray.length; //inner loop
var outerLoop = 0;
//get length of shortest
for (var i = 0; i<masterArray.length;i++){
    var a = masterArray[i].length;
    if (outerLoop==0){outerLoop = a;}else if(a < outerLoop){outerLoop = a;}
}

var newOuterArray = new Array(outerLoop);
    for (var x = 0; x<outerLoop;x++){
        var newInnerArray = new Array(innerLoop);
            for (var y = 0; y<innerLoop;y++){
                newInnerArray[y] = masterArray[y][x];
                }
            newOuterArray[x] = newInnerArray;
}
 return newOuterArray;
}

function reversed(arr){
    var newArray = new Array(arr.length);
    var n = 0;
    for(var i=arr.length-1; i>=0; i--){
        newArray[n++] = arr[i];
    }
    return newArray;
}

function clockwise(r){

    if(r.length>0){
            var a = reversed(zip(r.slice(1)));
            a.splice(0,0,r[0]);
            return clockwise(a);
     }else{
        return [];
    }
}

Here's my progress. I'm stuck at the last part: clockwise error in firebug is too much recursion.

A: I think the problem lies in the use of splice.  Try something like this instead...
function clockwise(r){
    if(r.length>0){
        var remaining = r.slice(1)
        var a = reversed(zip(remaining));
        return r[0].concat(clockwise(a));
     } else {
        return [];
    }
}

A: I think you want the recursive call to clockwise() to be before you prepend r[0] otherwise you never get down to an empty string.

A: I don't follow what the algorithm is trying to do, but the Javascript version of clockwise looks like it can only ever return [].  There are two return paths.  One calls clockwise, the other returns [] so the only way out of that function is to return [].  That's not how your python version works.
I haven't looked at reversed and zip, but there is a logic difference in the javascript version of clockwise.  In the javascript version, you remove the first item in the array, then reverse and zip, then put the first item back on the array and call clockwise on the whole thing.  In the Python version, you remvoe the first item in the array, call clocks and reverse on only the item without the first version, then add the first one back on afterwards.  Very different logic.  The Python version is much more likely to end.
I haven't looked at the other functions reverse and zip, but this looks like a more faithful javascript version of clockwise:
function clockwise(r) {
    if (r.length > 0) {
        var a = clockwise(reversed(zip(r.slice(1))));   // call clockwise on array starting at index 1
        a.splice(0,0,r[0]);                             // put first value in original array back onto the beginning of the result
        return (a);                                     // return new array
    } else {
        return [];
    }
}


text:
Q: How to Bind DataGridTemplateColumn.ClipboardContentBinding to SelectedItem of a Combobox that placed inside it? I need to bind DataGridTemplateColumn.ClipboardContentBinding to SelectedItem of a Combobox that placed inside that.In fact I need to bind Combobox.SelectedItem to the current row of DataGrid.I tried the code below but it doesn't work.
 <DataGrid ItemsSource="{Binding CommentCollection}">
    <DataGrid.Columns>
       <DataGridTemplateColumn Header="Description" Width="*">
           <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                 <ComboBox DisplayMemberPath="Name"
                   ItemsSource="{Binding DataContext.CommentCollection,Source={x:Reference GrdSpecDataContext}}"
                   SelectedItem="{Binding .,Mode=TwoWay}"/>
               </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
          </DataGridTemplateColumn>
      </DataGrid.Columns>
  </DataGrid>

Please don't tell me I don't need to put ComboBox here or something like that.It's a simple sample,but I need to know it.


text:
Q: Can Shopp Commercial Plugin be hacked to display radio buttons instead of Dropdowns? I need to know if the 'Shopp' e-commerce plugin can be modified to display radio buttons instead of drop down menus for the product options. I don't need you to tell me how this can be done (though that would certainly be welcome), just if it is possible. I don't want to invest in Shopp unless it is something that has been done before and there is a thread or article on the Shopp board that explains the hack.
EDIT: Seriously, I just need someone w/ access to the Shopp user forums to login and run a quick search for that kind of mod.

A: This example highlights the versatility of interface options you can create by using radio inputs to select a product variation rather than the default  menus.
This section of code could be used in place of the variations code block in either the product.php template file or the category.php template file (if you want variation inputs in your category products list).
<?php if(shopp('product','has-variations')): ?>

    <?php while(shopp('product','variations')): ?>

            <input type="radio" name="products[<?php shopp('product','id'); ?>][price]" value="<?php shopp('product','variation','id'); ?>" />
            <?php shopp('product','variation','label'); ?>

    <?php endwhile; ?>

<?php endif; ?>

Warning
Using this will make it able to add empty products to your cart (if the product has variations)

A: Not sure how I reply to Roswell. I've updated his loop to help with empty variations
<?php if(shopp('product','has-variations')): ?>

    <?php while(shopp('product','variations')): ?>

            <?php if( shopp('product','variation','stock&return=1') > 0 ) : ?>

                    <input type="radio" name="products[<?php shopp('product','id'); ?>][price]" value="<?php shopp('product','variation','id'); ?>" />
                    <?php shopp('product','variation','label'); ?>

            <?php endif; ?>

    <?php endwhile; ?>

<?php endif; ?>


text:
Q: Enable bcmath module PHP 7.2 server CLI I have installed the php bcmath module for 7.2 via the command:
yum install php-bcmath

I can see that it's there, but it's not in the php ini file when I check with command php -i
How can I enable this module?
Server is CentOS 7 running Plesk 17.8.11
Any help much appreciated.


text:
Q: Is there a way to reference a view inside itself in a conditional statement in xml(or atleast use the view's properties) I am trying to make changes to a view based on its state onFocused like
<data>
    <import type="android.view.View"/>
</data>

...
android:hint="@{isFocused ? 'right' : 'left'}"

but it says that : cannot find identifier isFocused. Now i know that there is a way to do this using java/kotlin code, but i want to know if i can reference a view inside itself and use its properties to determine its actions. Something like:
android:hint="@{this.isFocused ? 'right' : 'left'}"


text:
Q: How to do regex renaming with Better File Rename (on Windows) I can't find any documentation at all about renaming files using the regex functions in BFR.
I know I can use other apps, but I want to use this one.
http://www.publicspace.net/windows/BetterFileRename/
I simply want to swap some numbers at the tail of the filename with the text at the head...
like
/(.*)-(\d{6})/

and
$2 $1

Are there some docs or examples out there?
Thanks

A: it's \1, \2, etc
The more recent versions of BFR actually show the column names as \1 and \2 to make things easier


text:
Q: ¿Como puedo esconder el codigo javascript de mi pagina web? Estoy haciendo una pagina html donde los usuarios hacen login con javascript, mi problema es que al pulsar click derecho > ver codigo fuente de la pagina y ctrl + u pueden acceder a las contraseñas que tengo almacenadas en javascript, yo quisiera esconder las contraseñas en javascript para que nadie mas pueda verlas ¿como puedo hacer esto? he intentado bloquear el click derecho y funciono, pero aun pueden ver el codigo js con ctrl + u ¿alguien me ayuda? aqui dejo el codigo:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login para varios usuario</title>

Ingresa Tus Datos

<form name="login">

Usuario

           <input name="usuario" type="text" class="Input" value="" size="20" />

Clave

           <input name="password" type="password" class="Input" value="" size="20" />

           <input value="Entrar" target="_parent" onclick="Login()" type="button" class="boton"/>

         <input type="reset" name="Borrar" id="Borrar" value="Reset" class="boton" />

</form>

 ```

A: Como te han comentado ese no es el lugar para tener contraseñas, pero si lo tienes que tener ahí sí o sí, podrías cifrar la contraseña, en lugar de tenerla en texto plano .
Aunque aún así podrían ver el algoritmo con el que cifras y la podrían obtener , pero ya se lo complicas un poco más

A: Primero que nada, no es el lugar para almacenar contraseñas.
De igual forma se me ocurre usar ofuscator para oculta tu código JavaScript:
https://obfuscator.io/
Esta herramienta transforma su código fuente JavaScript original en una nueva representación que es más difícil de entender. El resultado ofuscado tendrá la funcionalidad exacta del código original.


text:
Q: Download list of File Using RESTful Web Services with JAX-RS taken from, http://www.concretepage.com/webservices/download-file-using-restful-web-services-jax-rs, here is the code to download a File from a jax-rs rest service
@Path("/restwb")
public class FileResource {
    @GET
    @Path("/download/{fname}/{ext}")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response  downloadFile(@PathParam("fname") String fileName,@PathParam("ext") String fileExt){
        File file = new File("C:/temp/"+fileName+"."+fileExt);
        ResponseBuilder rb = Response.ok(file);
        rb.header("Content-Disposition", "attachment; filename=" + file.getName());
        Response response = rb.build();
        return response;
    }
}

My question now is what should the response look like in order to download a list of File objects (ArrayList)?
Can we just write:
List<File> lFiles = new ArrayList<File>();
...
ResponseBuilder rb = Response.ok(lFiles);

A: You can not download multiple files in the same request. If you need to download multiple files you have to create an archive then download the archived file.
This is because raw bytes of the file are sent in the HTTP Response, and HTTP headers are used for how to translate the content you can only set one set of headers HTTP response.


text:
Q: Automapper with nested destination Property I am trying to map a nested child property like so.
var mapperConfig = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Collection, CollectionDTO>()
        .ForMember(dest => dest.Items.Select(x => x.AddedToCollectionDate),
                               opts => opts.MapFrom(src =>
                                   src.CollectionItems.Select(ci => ci.AddedToCollectionDate)));

});

Collection.Items is a List<Item>. Each Item has a AddedToCollectionDate property that I need to populate from the source mapping.
CollectionDTO has a navigational property to a cross-join table called CollectionItem, which has a property called AddedToCollectionDate.
Error:

Custom configuration for members is only supported for top-level individual members on a type.

How can I achieve this with AutoMapper?
Clases (omitted other properties for brevity):
public partial class Collection
{
    public virtual ICollection<CollectionItem> CollectionItems { get; set; }
}

public partial class CollectionItem
{
    public System.DateTime AddedToCollectionDate { get; set; }

    public virtual Collection Collection { get; set; }
    public virtual Item Item { get; set; }
}

public class CollectionDTO
{
    public List<ItemDTO> Items { get; set; }
    public DateTime LastAccessedDate { get; set; }
}

public class Item
{
    public DateTime LastAccessedDate { get; set; }
    public virtual ICollection<CollectionItem> CollectionItems { get; set; }
}

A: I got it to work by doing a FirstOrDefault() instead of aSelect() selection like this.
cfg.CreateMap<Item, ItemDTO>()
                    .ForMember(dest => dest.AddedToCollectionDate,
                               opts => opts.MapFrom(src =>
                                   src.CollectionItems.FirstOrDefault().AddedToCollectionDate));

A: Instead of the ForMember call, you should configure a mapping for CollectionItem as well.
cfg.CreateMap<CollectionItem, ItemDTO>();
cfg.CreateMap<Collection, CollectionDTO>();

If you also rename CollectionDTO.Items to CollectionDTO.CollectionItems AutoMapper knows enough to map Collection.CollectionItems to the right collection in CollectionDTO.


text:
Q: android drag list adapter item to n drop into bin I would like to implement a list activity where user can drag an item from a list view and then i would like to show a small recycle bin where user can drop the selected item. Recycle bin can appear from side or bottom of the screen or just pop out. This recycle bin should disappear if user drops an item.
How do i make it possible?

A: #ProTip : Starting by searching the official doc sometimes yield interesting results, like finding a documentation :
http://developer.android.com/guide/topics/ui/drag-drop.html


text:
Q: Robot FrameWork, Clink Link does not handle link with "=" and results in "Link with locator is not found" I have a problem that I failed to solve. I am trying to navigate as (I have anonymized it a bit, used Crome plugin 'Robotcorder' to capture)
Click Link   //a[@href="https://xxx.yyy.com/psp/zzzzprd/EMPLOYEE/ERP/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?scname=XX_YYYYYY_TE_CENTER&FolderPath=PORTAL_ROOT_OBJECT.CO_AAAAA_BB_SERVICE.EP_SC_UU_BBBBB_TE_CENTER&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder"]

but it always fails with "Link with locator is not found".
I tested with:

*

*Click Element

*replacing "=" with "%3D"

*default=https...

*link=https

*...

If have of course searched the web and found a lot of suggestions and tried to test them all.
If I paste the link in the browser address it navigates as intended.
The webpage is built round some kind of Oracle framework that we are using for time reporting and I just wanted to test Robot WorkFramework to enter a weeks time.

A: Fromt the Click Link documentation:

When using the default locator strategy, links are searched using id, name, href and the link text.

Because you didn't specify the locator strategy, robot will try to find a link with an id, name, or href that exactly matches the string "//a[@href=...". Since what you provided isn't an id, name, or href, it won't find your link.
If you want to look up the link using an xpath, you need to tell the keyword that you're giving it an xpath. with older versions of the selenium library you would prefix it with xpath=, with newer versions you should use xpath:.
Example:
Click Link  xpath://a[@href="https://xxx.yyy.com/psp/zzzzprd/EMPLOYEE/ERP/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?scname=XX_YYYYYY_TE_CENTER&FolderPath=PORTAL_ROOT_OBJECT.CO_AAAAA_BB_SERVICE.EP_SC_UU_BBBBB_TE_CENTER&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder"]

Since you're only using the href to identify the link, you can shorten this slighly by providing just the href:
Click Link  href:https://xxx.yyy.com/psp/zzzzprd/EMPLOYEE/ERP/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?scname=XX_YYYYYY_TE_CENTER&FolderPath=PORTAL_ROOT_OBJECT.CO_AAAAA_BB_SERVICE.EP_SC_UU_BBBBB_TE_CENTER&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder

I would encourage you to try to find a better way to identify that link rather than with that exceptionally long, hard to read URL. For example, you or one of your developers should add a unique id or name attribute to the link to make it easier to test.


text:
Q: Atempting to run Laravel Dusk tests With Lando I have a Laravel 8 application running with Lando and I'm trying to figure out why when I have the following setup of the Lando container its not running my Dusk tests. I have provided as much information about my setup as I believe will assist in the problem.
composer.json
"laravel/dusk": "^6.13",

Terminal
± lando start
Let's get this party started! Starting app teach-me...
Starting landoproxyhyperion5000gandalfedition_proxy_1 ... done
Starting teachme_database_1     ... done
Starting teachme_chromedriver_1 ... done
Scanning to determine which services are ready... Please standby...

Your app has started up correctly.
Here are some vitals:

NAME            teach-me
LOCATION        /Users/me/my-app
SERVICES        chromedriver, appserver, database
APPSERVER URLS  https://localhost:55000
                http://localhost:55001
                http://my-app.lndo.site/
                https://my-app.lndo.site/

± lando artisan dusk
PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 00:01.416, Memory: 26.00 MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to     /session with params: {"capabilities":{"firstMatch":[{"browserName":"chrome","goog:chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}]},"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}}

Failed to connect to localhost port 9515: Connection refused

/app/vendor/php-webdriver/webdriver/lib/Remote/HttpCommandExecutor.php:332
/app/vendor/php-webdriver/webdriver/lib/Remote/RemoteWebDriver.php:135
/app/tests/DuskTestCase.php:46
/app/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:218
/app/vendor/laravel/framework/src/Illuminate/Support/helpers.php:234
/app/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:219
/app/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:97
/app/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:65
/app/tests/Browser/ExampleTest.php:23

docker-compose.yml
version: '3'

services:
  chromedriver:
    image: robcherry/docker-chromedriver:latest
    volumes:
      - /dev/shm:/dev/shm
    expose:
      - "4444"
    environment:
      CHROMEDRIVER_WHITELISTED_IPS: ""
      CHROMEDRIVER_URL_BASE: "/wd/hub"
    security_opt:
      - seccomp:unconfined

lando.yml
name: my-app
recipe: laravel
compose:
  - docker-compose.yml
config:
  php: '8.0'
  webroot: /public
  database: mysql
  xdebug: true

.env.dusk.local
APP_URL=http://my-app.lndo.site


text:
Q: if $d^2=a^2+b^2+c^2$,then $A-BCD$ is Trirectangular Tetrahedron.
A  tetrahedron $A-BCD$,and let $$S_{ABC}=a,S_{ACD}=b,S_{ABD}=c,S_{BCD}=d$$
  and such
  $$d^2=a^2+b^2+c^2$$

show that:
then tetrahedron $A-BCD$ is Trirectangular Tetrahedron.

I know this reslut,if $A-BCD$ is Trirectangular Tetrahedron.then we have
$$d^2=a^2+b^2+c^2$$
and I can prove this. But the inverse problem,I can't see it,and can't prove it.I hope someone can know? Thank you

A: I'm going to change your notation slightly, for better symmetry:
$$a = |\triangle BCD| \qquad b = |\triangle CDA| \qquad c = |\triangle DAB| \qquad d = |\triangle ABC|$$
(So, "$x$" is the area of the face opposite vertex "$X$".)
Consider this tetrahedral Law of Cosines for Faces:
$$a^2 = b^2 + c^2 + d^2 - 2 c d \cos \angle AB - 2 d b \cos\angle AC - 2 b c \cos \angle AD$$
where "$\angle XY$" indicates the dihedral angle along edge $XY$.
Certainly, if the tetrahedron is tri-rectangular (what I call "right-corner") with hypotenuse-face $\triangle BCD$, then the cosines vanish and we have de Gua's Theorem,
$$a^2 = b^2 + c^2 + d^2 \qquad (\star)$$
However, the converse isn't true. Assuming $(\star)$, the Law of Cosines for Faces reduces to
$$0 = c d \cos \angle AB + d b \cos\angle AC + b c \cos \angle AD$$
This relation can hold without the cosines simultaneously vanishing. (Contrast this with Law of Cosines for Triangles, which has just a single cosine term.) In fact, if you fix hypotenuse-face $\triangle BCD$, then $(\star)$ is (usually) satisfied by a continuum of tetrahedra with vertex $A$ on some ellipsoid.


text:
Q: OCaml map a string to a list of strings I'm trying to create a dictionary in OCaml that maps a string to a list of strings. I've referenced this tutorial for a basic string to string map, but I need some help making a list.
Here is what I want to do in Python:
>>> food = {}
>>> food["fruit"] = ("blueberry", "strawberry", "kiwi")
>>> food["veggie"] = ("broccoli", "kale")
>>> for k in food:
...     for v in food[k]:
...         print k, "-->",v
...
fruit --> blueberry
fruit --> strawberry
fruit --> kiwi
veggie --> broccoli
veggie --> kale

Thanks in advance

A: You can just use lists,
let food = [
  "fruit",  ["blueberry"; "strawberry"; "kiwi"];
  "veggie", ["broccoli"; "kale"]
]

and use List.assoc to access it:
List.assoc "fruit" food

will evaluate to
- : string list = ["blueberry"; "strawberry"; "kiwi"]

If you need real maps with logarithmic search, then you can use Map module. In standard library it provides a functor Make that will create a map for a user provided data, e.g.,
module Strings = Map.Make(String)

will create a module Strings that is a map from string type to anything else. You can easily use lists as your value type:
let map = Strings.empty
Strings.add "fruit" ["blueberry"; "strawberry"; "kiwi"] map

This will, of course, create a persistent map. If you need a mutable map, like in python, then you need a Hashtbl module.
Here is an example with Hashtbl:
let food = Hashtbl.create 16
Hashtbl.add food "fruit" ["blueberry"; "strawberry"; "kiwi"]
Hashtbl.add food "veggie" ["broccoli"; "kale"]
Hashtbl.find food "veggie"

Will evaluate to
- : string list = ["broccoli"; "kale"]

A: Arrays and lists are not the same in OCaml. I'll assume you want to use lists (as in your title) and not arrays (as in the body of your question).
Here are some slightly modified lines from the tutorial:
# module myStrings = Map.Make(String);;
module MyStrings :
sig
 . . .
end
# let m0 = MyStrings.empty;;
val m0 : 'a MyStrings.t = <abstr>
# let m1 = MyStrings.add "abc" ["def"; "ghi"] m0;;
val m1 : string list MyStrings.t = <abstr>
# MyStrings.iter
    (fun s ss -> Printf.printf "%s --> %s\n" s (String.concat " " ss))
    m1;;
abc --> def ghi
- : unit = ()


text:
Q: Bash: add column and write variable, varying per line I am writing a script in bash to deal with some text files, also containing numbers. I have created an array variable in with 45 positions filled with numbers. I have this text file (delimiter is actually a '|', not a comma) with 5 fields/columns and 45 lines. I would like to add a 6th column, and write the nth value of the array on each nth line of the file.
My original text file, with:
 61537000|COO|DI|VMD|2018-01-08 00:00:00
 61537000|COO|DI|VMD|2018-01-09 00:00:00
 61537000|COO|DI|VMD|2018-01-10 00:00:00
 61537000|COO|DI|VMD|2018-01-11 00:00:00
 61537000|COO|DI|VMD|2018-01-12 00:00:00
 ...
 61537000|COO|DI|VMD|2018-02-21 00:00:00

My array variable is stored in qy. echo ${qy[*]} gives me:
133.7545755174117347 197.5730453102068415 211.0612457141076671 195.3965252988823307 155.9141492798344956 122.0765862336716795 109.3807402580878840 100.1258594727256394 118.3713165600757955 129.9118732920391577 130.2183465952591614 108.3783455600275339 87.3744866455706415 74.6811189513075407 67.2786196847537834 66.6486466128231307 75.5263825809798786 79.7579752859345201 76.7748478701627372 75.7971233334776102 75.5218971041520397 74.3644957571369167 74.7302279790034398 82.9013111977886133 107.8462461297641418 109.3922469923296476 87.2584880672884534 74.3278359110118687 66.8273524401225775 62.9054376472748469 59.2471567250619217 55.4465232890134493 54.9324477319027615 55.0268189192084034 50.3969437024658000 48.2808157236208981 49.8788627643603767 50.7025436995365588 52.5391775713757207 51.6024683921895763 66.5341261816728136 73.3342955766798011 68.3585064456764055 69.1125302235501069 75.0594939607898664

Desired output file:
 61537000|COO|DI|VMD|2018-01-08 00:00:00|133.75
 61537000|COO|DI|VMD|2018-01-09 00:00:00|197.57
 61537000|COO|DI|VMD|2018-01-10 00:00:00|211.06
 61537000|COO|DI|VMD|2018-01-11 00:00:00|195.39
 61537000|COO|DI|VMD|2018-01-12 00:00:00|155.91
 ...
 61537000|COO|DI|VMD|2018-02-21 00:00:00|122.07

I have successfully used while read line do; ... done < file with cut -d '|' -f6 to read from file, but apparently there is not an analogous while write sort of straightforward loop to write in it, is there? Any help would be very much appreciated.

A: There's good ol' paste:
printf '%.2f\n' "${qy[@]}" | paste -d'|' textfile -
 61537000|COO|DI|VMD|2018-01-08 00:00:00|133.75
 61537000|COO|DI|VMD|2018-01-09 00:00:00|197.57
 61537000|COO|DI|VMD|2018-01-10 00:00:00|211.06
 61537000|COO|DI|VMD|2018-01-11 00:00:00|195.40
 61537000|COO|DI|VMD|2018-01-12 00:00:00|155.91

(I only copied the first 5 entries, for brevity).

A: Pure bash method.  Since the number of elements in $qy is the same as the number of lines in file, a for loop should work, using read inside the loop:
for f in ${qy[*]}; do read x; printf '%s|%.2f\n' "$x" "$f"; done < file

If for some reason printf isn't behaving, it can be done with echo and parameter substitution:
for f in ${qy[*]}; do read x; echo "$x|${f%%??????????????}"; done < file

A: step1
sed -r  "s/\s+$//g" orgial_textfile| awk '{print $0"|"}' >>orginal_final_textfile

Step2
save the array variable in need_copy_textfile
sample need_copy_textfile format will be

133.7545755174117347
197.5730453102068415
211.0612457141076671
195.3965252988823307
155.9141492798344956
122.0765862336716795
109.3807402580878840
100.1258594727256394
118.3713165600757955
129.9118732920391577
130.2183465952591614
108.3783455600275339
87.3744866455706415
.
.
.

75.0594939607898664

awk '{print substr($1,1,6)}' need_copy_textfile >> need_copy_textfile_final.txt

step3
Now combine above 2 files to get required result
paste orginal_final_textfile need_copy_textfile_final.txt | sed -r "s/\t+//g"

Sample output
61537000|COO|DI|VMD|2018-01-08 00:00:00|133.75
61537000|COO|DI|VMD|2018-01-09 00:00:00|197.57
61537000|COO|DI|VMD|2018-01-10 00:00:00|211.06
61537000|COO|DI|VMD|2018-01-11 00:00:00|195.39
61537000|COO|DI|VMD|2018-01-12 00:00:00|155.91


text:
Q: Как выделить строку в QTextEdit по клику мыши? Т.е. нужно кликнуть мышью в список в QTextEdit, получить номер строки, куда был клик, и выделить эту строку.
А ещё желательно выделять строку нужного номера программно, без клика мышью.

A: Для отлавливания клика, ва понадобится установить соответствующий eventFilter, в котором просто выделить строку под курсором:
QTextCursor c = ui->textEdit->textCursor();
c.select(QTextCursor::LineUnderCursor);
ui->textEdit->setTextCursor(c);

что касается выбора определенной строки:
void MainWindow::selectLine(int line)
{
    QTextCursor c = ui->textEdit->textCursor(); //получили текстовый курсор
    c.movePosition(QTextCursor::Start); // переместили в начало документа
    c.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor,line);// сместили  на line позиций вниз
    c.select(QTextCursor::LineUnderCursor); // выделили строку под курсором
    ui->textEdit->setTextCursor(c); // установили курсор назад
}


text:
Q: jquery set previous inputs to 0 I have a checkbox at the end of 5 inputs and one dropdown. I am trying through jquery to set all the inputs and the dropdown before the checkbox to 0.
There will be many employees listed so it has to be only the ones before the checkbox.
My feeble attempt at the jquery. I have the .on as sometimes it will be called through ajax
$(document).ready(function () {

    $(document).on('click', '.fasCheck', function(){

    if ($(this).attr("checked") == "checked"){
        $(this).prev().parent().prev(".payWeek").next('input').prop('checked', true);;
    } else {

    }
    });

});

The html:

David Wilson

        Pay Week1
        <input type="number" id="MonthlyReturn0PayWeek1" value="" maxlength="12" step="any" name="data[MonthlyReturn][0][pay_week1]">

        Pay Week2
        <input type="number" id="MonthlyReturn0PayWeek2" value="" maxlength="12" step="any" name="data[MonthlyReturn][0][pay_week2]">

        Pay Week3
        <input type="number" id="MonthlyReturn0PayWeek3" value="" maxlength="12" step="any" name="data[MonthlyReturn][0][pay_week3]">

        Pay Week4
        <input type="number" id="MonthlyReturn0PayWeek4" value="" maxlength="12" step="any" name="data[MonthlyReturn][0][pay_week4]">

         Pay Week5
         <input type="number" id="MonthlyReturn0PayWeek5" value="" maxlength="12" step="any" name="data[MonthlyReturn][0][pay_week5]">

          Pay Weeks
          <select id="MonthlyReturn0PayWeeks" name="data[MonthlyReturn][0][pay_weeks]">
                <option value="0">0</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option selected="selected" value="4">4</option>
                <option value="5">5</option>
           </select>

           FAS
           <input type="checkbox" class="fasCheck" name="FAS">

A: *

*$(this).attr("checked") == "checked" won't work, you already know to use .prop(). Or just use this.cecked without any jQuery.

*.prev().parent() - the prev is absolutely unnecessary, all siblings do have the same parent node.

*.prev(".payWeek") - seems like you want to use .prevAll() instead.

*.next('input') - you don't want to find the next sibling, but a descendant. Use .children() or .find().

*.prop('checked') - while appropriate for checkboxes, you have number inputs here and need to set their value, via .val().

So change it to
$(document).ready(function() {
    $(document).on('click', '.fasCheck', function() {
        if (this.checked) {
            $(this)
              .parent()
              .prevAll(".payWeek")
              .find('input')
              .val('0');
        }
    });
});

A: From the clicked checkbox, find the closest payWeek, then select all previous payWeeks, and find all inputs within those payWeeks and set the value to zero :
$(document).ready(function () {
    $(document).on('click', '.fasCheck', function(){
        if ( this.checked ) {
            $(this).closest('.payWeek')
                   .prevAll('.payWeek')
                   .find('input')
                   .val('0');
        } else {

        }
    });
});

A: $(document).on('click', '.fasCheck', function(){

    var $this = $(this),
        $parent = $(this).parents('.returns').eq(0),
        $inputs = $parent.find('input');

    if ($this.prop("checked")){
        $inputs.val('0');
    }
});


text:
Q: FORMULA FIELD - Nested IF Statement Getting "Error: Incorrect number of parameters for function 'IF()'. Expected 3, received 5" Here is the current formula:
IF( AND
 (NOT
    (Line_Level_Detail__c ='Services'), Line_Level_Type__c= 'New Product'), UnitPrice   * Quantity , 0)

Trying to add criteria that says if the Opportunity Stage is Closed Lost then the results should be 0.
This formula sits on the opportunity product.
This is what I have right now:
IF(ISPICKVAL(Opportunity.StageName, "Closed Lost"), 0,  AND
 (NOT
    (Line_Level_Detail__c ='Services'), Line_Level_Type__c= 'New Product'), UnitPrice   * Quantity , 0)

Can't figure out where we are going wrong.

A: The three parameters in the IF formulas represent:

*

*logical condition

*value if the condition is true

*value if the condition is false

Since 0 was the third parameter in your original formula, you can just add another condition to the AND in the original version. Something like the following should return the expected result.
IF(AND(NOT(Line_Level_Detail__c ='Services'), Line_Level_Type__c= 'New Product', NOT(ISPICKVAL(Opportunity.StageName, 'Closed Lost'))), UnitPrice   * Quantity , 0)


text: Q: Change the Business Name to use the PrimaryReceiver's name in Preapproval interface for Adaptive Payments I would like to change the Business Name to use the name of the PrimaryReceiver. Is it possible via Adaptive Payments API?


text:
Q: nginx + php-fpm cycle redirection error on linode new vps I'm new to nginx, and I'm trying to make my first server run. I followed this guide as I'm trying to use it for a multisite wordpress site.
After installing everything, I get a 500 Internal server error. If I check logs, I see this:
012/09/27 08:55:54 [error] 11565#0: *8 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: xxx.xxx.xxx.xxx, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "www.mydomain.com"
2012/09/27 08:59:32 [error] 11618#0: *1 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: xxx.xxx.xxx.xxx, server: localhost, request: "GET /phpmyadmin HTTP/1.1", host: "www.mydomain.com"

My conf files are the following:
nano /etc/nginx/sites-available/mydomain.com
server {
    listen       80 default_server;
    server_name  mydomain.com *.mydomain.com;
    root /srv/www/aciup.com/public;

    access_log   /srv/www/mydomain.com/log/access.log;
    error_log    /srv/www/mydomain.com/log/error.log;

 location / {
        index index.php;
        try_files $uri $uri/ /index.php?$args;
    }

    # Add trailing slash to */wp-admin requests.
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;

    # Directives to send expires headers and turn off 404 error logging.
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires 24h;
        log_not_found off;
    }

    # this prevents hidden files (beginning with a period) from being served
              location ~ /\.          { access_log off; log_not_found off; deny all; }

    # Pass uploaded files to wp-includes/ms-files.php.
    rewrite /files/$ /index.php last;

    if ($uri !~ wp-content/plugins) {
        rewrite /files/(.+)$ /wp-includes/ms-files.php?file=$1 last;
    }

    # Rewrite multisite '.../wp-.*' and '.../*.php'.
    if (!-e $request_filename) {
        rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
        rewrite ^/[_0-9a-zA-Z-]+.*(/wp-admin/.*\.php)$ $1 last;
        rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
    }

    location ~ \.php$ {
        client_max_body_size 25M;
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        include        /etc/nginx/fastcgi_params;
    }
}

nano /etc/nginx/nginx.conf
user              www-data;
worker_processes  4;
worker_cpu_affinity 0001 0010 0100 1000;
error_log         /var/log/nginx/error.log;
pid               /var/run/nginx.pid;

events {
    worker_connections  2048;
}

http {
    include     /etc/nginx/mime.types;
    access_log  /var/log/nginx/access.log;

    sendfile            on;
    tcp_nopush          on;
    keepalive_timeout   5;
    tcp_nodelay         on;
    server_tokens       off;

    gzip          on;
    gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_disable  "MSIE [1-6]\.(?!.*SV1)";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Any help will be appreciated.

A: The first thing you're missing is a 404 error handler. WordPress Multisite pretty much requires this.
error_page 404 /index.php;


text:
Q: changing extensive tree game to normal representation I was wondering how you can get (RfM) as -0.5, -0.5
I got RrP by [(1, -1) + (1, -1)] / 2
Here is the picture of the problem:

Picture on the left: card game in extensive / tree form
picture on the right: card game in strategic form / normal representation

A: RfM: with probability 0.5 you get (2,-2) and with probability 0.5 you get (-1,1)
then, the expected outcome is (1,-1)+(-1/2,1/2)=(1/2,-1/2) as you pointed in your solution
I don't see any mistake in your solution


text:
Q: Running script in host server from my computer and shutting down my computer I'm very new to ssh and working with servers. I know how to make a connection to a server, and how to run a local script in a host server.
However I always have to have my terminal open while the script is running. The thing is that I'm about to run a script which is expected to finish in a couple of weeks. I cannot have my computer on for two weeks. How can I "send" the instruction to run my script and be able to shut down my computer while the server is running?
If this is not possible, can I copy the script to the server's hard drive and "send" the instruction to run that script, and be able to shut down my computer?
Thanks for your comments.

A: Take a look at the screen program.
You can ssh to your server, then create a new login session by typing:
screen

In that session, you can start off your script that will take a couple of weeks.
You can then detach from that session by typing:
Ctrl-a Ctrl-d

You can then log off your ssh session, and your script is still running in the detached screen session.
Later, you can ssh in to your server again and type:
screen -r

This will reattach you to the detached session from before, and you can see how your script is going. If not finished, just detach again.
Also note that if your screen session is accidentally detached (e.g. ssh stops working, or a network outage) your screen session will still be there and you can ssh again and screen -r to reattach!


text:
Q: Looping over webservice results not working I'm trying to use a webservice and loop over the result set.
For some reason it only gives me back the first result which in this case is:

Overall Rank: 537316 Level: 1419 Xp: 6407333

It seems to stop and not cycle through the rest of the results in the list of list which is from stat_list from the grab_api function.
stat_list is a list in a list with strings of numbers inside.
import urllib2
import re

def grab_api():
stat_list = []
response = urllib2.urlopen('http://services.runescape.com/m=hiscore/index_lite.ws?player=taroboxx')
html = response.read()
stat_list.append(re.split(r"[,\n]", html))
return stat_list

def check_score(hiscore_html):
stats = ["Overall", "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction", "Summoning", "Dungeoneering", "Divination"]
hiscore = 0
stat = 0
for i in hiscore_html[0]:
    if hiscore == 0:
        print stats[stat],
        print "Rank:", i,
        stat += 1
        hiscore += 1
    elif hiscore == 1:
        print "Level:", i,
        hiscore += 1
    elif hiscore == 2:
        print "Xp:", i
        hiscore += 1
    else:
        hiscore == 0

check_score(grab_api())

A: In your else block you are doing hiscore == 0 instead of hiscore = 0.

A: As an output of the first function your get a list of lists, so there is no iteration inside the list you want: you go to a list (hiscore_html), and inside you find one more list which is the only item of hiscore_html.
In order to avoid it, you can refer to the first element of hiscore_html. But I just saw your update -- it's exactly what you're doing, and the other mistake was fixed below.


text:
Q: Unable to convert from one class to another I am new to programming and trying my hands on Class to class conversion using conversion operator function.
My aim is to convert a 24 hour clock to 12 hour clock using conversion operator function (I should see both 12 and 24 hour clock).
Below is my code, while trying to see the time in 12 hour format it shows garbage value.
What changes should I a make in the code to see the correct time in 12 hours format?
#include<iostream.h>
#include<conio.h>

class Time24
{
 public:
   int hrs;
   int min;
   int sec;

   void getTime()
   {
    h:
    cout<<"Enter time in hours : " ;
    cin>>hrs;
    if(hrs > 23 || hrs < 0)
    {
     cout<<"Hours cannot be greater than 23 or less than 0 "<<endl;
     goto h;
    }

    m:
    cout<<"Enter time in minutes : ";
    cin>>min;
    if(min > 59 || min < 0)
    {
     cout<<"Minutes cannot be greater than 59 or less than 0"<<endl;
     goto m;
    }

    s:
    cout<<"Enter time in seconds : ";
    cin>>sec;
    if(sec > 59 || sec < 0)
    {
     cout<<"Seconds cannot be greater than 59 or less than 0"<<endl;
     goto s;
    }
   }

   void display()
   {
    cout<<"Time in 24 hours format = "<<hrs<<":"<<min<<":"<<sec<<endl;
   }
};

class Time12
{
  public:
   int hrs;
   int min;
   int sec;

    Time12()
    {
     hrs = 0;
     min = 0;
     sec = 0;
    }
    operator Time24()
    {
     Time24 t;
     hrs = t.hrs;
     min = t.min;
     sec = t.sec;
     cout<<"In operator function"<<endl;
     cout<<"t,hrs ="<<t.hrs<<endl;
     cout<<"hrs = "<<hrs<<endl;

     if(hrs > 12)
     {
      hrs = hrs - 12;
     }

     return t;
    }

    void display()
    {
    cout<<"Time in 12 hours format = "<<hrs<<":"<<min<<":"<<sec;
    }
};

void main()
{
 clrscr();
 Time24 t2;
 Time12 t1;
 t2.getTime();
 t2.display();
 //t1=t2;
t2=t1;
 //t2 = Time24(t1);
 t1.display();
 getch();
}

A: I suppose instead of
hrs = t.hrs;
min = t.min;
sec = t.sec;

in Time12::operator Time24() you mean
t.hrs = hrs;
t.min = min;
t.sec = sec;

This is why you are getting garbage. However, I don't think that function does what you want it to do anyway. It defines a conversion from Time12 to Time24, which isn't even possible, as Time12 doesn't know if it's AM or PM. What you want is a operator Time12() in Time24.


text:
Q: CLR stored procedure activated by a broker queue to post to a webservice I want to call a CLR inside a service broker queue activated store procedure but doing this causes the queue to be disabled - POISON_MESSAGE_HANDLING (STATUS = ON).
Basically, the CLR just calls a webservice to post the data it recieves.
Is there a permission or something I need to do first ?

A:
The activated proc '[dbo].[ProcessOrders]' running on queue 'App01.dbo.InstTargetQueue' output the following: 'Could not find stored procedure 'dbo.ProcessOrders

This error indicates that the queue is configured with a stored procedure that was dropped from the database, perhaps. Can you double check that the procedure exists? Perhaps you have a typo, eg. an extra space, in the queue configuration? Run select * from sys.service_queues and double-check that the activated procedure name is exactly what you expect. Run select * from sys.procedures and make sure the procedure exists and is named as you expect.
To answer your question about CLR: first and foremost I would urge you to move the webservice calls outside of the database. Monitor the queue with an external process service, and post the web service call from your process, not from inside the database.
If you insist on calling webservices from SQLCLR, then this is what you need to know:

*

*CLR procedures require EXTERNAL_ACCESS on the assembly to be allowed to call web services

*Activated procedures run in an 'execute as' sandboxed environment, see Why does feature … not work under activation?

*The sandboxed environment prevents EXTERNAL_ACCESS

So you need to exit the sandboxed environment of the activated procedure, and this can be done either by marking the database as TRUSTWORTHY, or by signing the procedure, see Signing an activated procedure. But right now your problem seem to be a simple name mismatch.
If you keep your web services inside SQLCLR (and I strongly discourage that) then please read about Thread.BeginThreadAffinity() and ServicePointManager.DefaultConnectionLimit (the second applies to an external process as well, not only SQLCLR).


text:
Q: Wifi disconnects abruptly and frequently Wifi disables abruptly. Tried the solution available on the internet.None worked.Need to disable and enable wifi to start the connection. Cant upgrade to Ubuntu 18.04 as download stops due to wifi issue.Need help.
output after running lspci command:
$ lspci -knn | grep -i net -A3
02:00.1 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 12)
        Subsystem: ASUSTeK Computer Inc. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [1043:200f]
        Kernel driver in use: r8169
        Kernel modules: r8169
03:00.0 Network controller [0280]: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe [1814:3290]
        Subsystem: Foxconn International, Inc. RT3290 Wireless 802.11n 1T/1R PCIe [105b:e055]
        Kernel driver in use: rt2800pci
        Kernel modules: rt2800pci

A: Installation of Ralink RT3290

*

*fork this repo

*cd into it

*compile the driver

*install the driver

comand for that (it will ask your user password to apply changes to system):
git clone https://github.com/pkeeper/rt3290sta.git
cd rt3290sta
make
sudo make install
sudo modprobe -r rt2800pci
sudo modprobe rt3290sta

Now you need to make it load on startup. Blacklist the rt2800pci driver in /etc/modprobe.d/blacklist.conf and add rt3290sta to /etc/modules.


text:
Q: Problem displaying uploaded image from firebase when refreshing page Hello everyone and Happy New Year! Maybe someone knows why this can happen? There is a link to the image in the database, everything is also loaded in storage. And after adding the image, everything is also fine until the page is refreshed . Help someone, please. I didn't find the answer to the question in Google.
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
import cart from './cart'
import loading from './loading'
import * as fb from 'firebase/app'

Vue.use(Vuex)
class Product {
  constructor (title, price, description, ownerId, imageSrc = '', id = null) {
    this.title = title
    this.price = price
    this.description = description
    this.ownerId = ownerId
    this.imageSrc = imageSrc
    this.id = id
  }
}

export default function (/* { ssrContext } */) {
  const Store = new Vuex.Store({
    state: {
      amount: 1,
      products: [
      ]
    },
    getters: {
      addById (state) {
        return addId => {
          return state.products.find(product => product.id === addId)
        }
      },
      products (state) {
        return state.products
      }
    },
    actions: {
      async CREATE_PRODUCT ({ commit, getters }, payload) {
        commit('SET_LOADING', true)
        const image = payload.image

        try {
          const newProduct = new Product(payload.title, payload.price, payload.description, getters.user.id, '')
          const product = await fb.database().ref('products').push(newProduct)
          const imageExt = image.name.slice(image.name.lastIndexOf('.'))
          const fileData = await fb.storage().ref(`products/${product.key}.${imageExt}`).put(image)
          // const imageSrc = await fb.storage().ref().StorageReference(fileData.ref.fullPath).getDownloadUrl()
          const imageSrc = await fileData.ref.getStorage().getDownloadURL()
          await fb.database().ref('products').child(product.key).update({ imageSrc })
          commit('SET_LOADING', false)
          commit('CREATE_PRODUCT', {
            ...newProduct,
            id: product.key,
            imageSrc
          })
        } catch (error) {
          commit('SET_LOADING', false)
          throw error
        }
      },
      async fetchProducts ({ commit }) {
        commit('SET_LOADING', true)
        const resultProducts = []
        try {
          const fbVal = await fb.database().ref('products').once('value')
          const products = fbVal.val()
          Object.keys(products).forEach(key => {
            const product = products[key]
            resultProducts.push(
              new Product(product.title, product.price, product.description, product.imageSrc, product.ownerId, key)
            )
          })
          commit('LOAD_PRODUCTS', resultProducts)
          commit('SET_LOADING', false)
        } catch (error) {
          commit('SET_LOADING', false)
          throw error
        }
      }
    },
    mutations: {
      CREATE_PRODUCT (state, payload) {
        state.products.push(payload)
      },
      LOAD_PRODUCTS (state, payload) {
        state.products = payload
      }
    },
    modules: {
      user,
      loading,
      cart
    },

    strict: process.env.DEV
  })

  return Store
}

A: In your fetchProducts() function, when you initialize each product to add to the store, you have got the arguments out-of-order where imageSrc and ownerId are around the wrong way.
new Product(product.title, product.price, product.description, product.imageSrc, product.ownerId, key)

needs to change to
new Product(product.title, product.price, product.description, product.ownerId, product.imageSrc, key)

Other improvements
In CREATE_PRODUCT, consider uploading the product data and image at the same time rather than one after the other.
async CREATE_PRODUCT ({ commit, getters }, payload) {
  commit('SET_LOADING', true)
  const image = payload.image

  try {
    const newProduct = new Product(payload.title, payload.price, payload.description, getters.user.id, '')
    const imageExt = image.name.slice(image.name.lastIndexOf('.'))
    const productRef = fb.database().ref('products').push(); // generates push ID without uploading data

    const productDbPromise = productRef.set(newProduct)
    const productImagePromise = fb.storage().ref(`products/${productRef.key}.${imageExt}`).put(image)
      .then(fileData => fileData.ref.getStorage().getDownloadURL())

    const [fbSnapshot, imageSrc] = await Promise.all([productDbPromise, productImagePromise])
    await fbSnapshot.ref.update({ imageSrc })

    commit('SET_LOADING', false)
    commit('CREATE_PRODUCT', {
      ...newProduct,
      id: productRef.key,
      imageSrc
    })
  } catch (error) {
    commit('SET_LOADING', false)
    throw error
  }
}

In fetchProducts, iterate over the products tree just once (rather than using val() on the entire products tree, iterating for a list of all the keys, then iterating again for each value). This is less RAM intensive and will be snappier. In addition, you should consider paginating the products rather than return everything at once.
async fetchProducts ({ commit }) {
  commit('SET_LOADING', true)
  try {
    const resultProducts = []
    const allProductsSnapshot = await fb.database().ref('products').once('value')
    allProductsSnapshot.forEach((productSnapshot) => {
      const product = productSnapshot.val();
      resultProducts.push(
        new Product(product.title, product.price, product.description, product.ownerId, product.imageSrc, productSnapshot.key)
      )
    });

    commit('LOAD_PRODUCTS', resultProducts)
    commit('SET_LOADING', false)
  } catch (error) {
    commit('SET_LOADING', false)
    throw error
  }
}


text:
Q: Show the location of the executable in GDB I suspect my gdb is accessing the wrong program location when I try to run it with "gdb [executable-name]". Is there anything I can do to have gdb output the location of the executable that's being debugged?

A:
I suspect my gdb is accessing the wrong program location when I try to run it with "gdb [executable-name]".

GDB will look for ./executable-name, and then search $PATH.
GDB info file will tell you what binary it's currently using.
P.S. If in doubt, simply pass the absolute path to your binary explicitly: gdb /path/to/executable-name.


text:
Q: Using exclamation marks in javascript Just seen a piece of javascript code where they placed two exclamation marks in front of a variable and I'm not sure what it does. I know what one does in front of a variable, just not what the second does. Any ideas would be much appreciated.

A: From: http://brianflove.com/2014/09/02/whats-the-double-exclamation-mark-for-in-javascript/
function() {
    var nothing = "";
    if (nothing) {
        window.alert('Nothing');
    } else {
        window.alert('Huh?');
    }
}
When the function above is executed we will get the alert "Huh?" because the value of the variable hello is being evaluated to be false. This is what is commonly referred to as truthy versus falsey.

The following values are considered by JavaScript to be falseys:

Empty string: ""
0
null
undefined
NaN
The following values are considered by JavaScript to be truthys:

Object: {}
Array: []
Not empty string: "anything"
Number other than zero: 3.14
Date: new Date();
The JavaScript engine that is executing your code will attempt to convert (or coerce) a value to a boolean when necessary, such as when evaluated in an if-statement.

So, why double exclamation marks?

In some cases you may want to cast a variable to be explicitly boolean. Why? Well, the number one reason is that most of time developers do not use type safe comparison operators.

The type safe comparison operators are:

Strictly equal: ===
Strictly unequal: !==
When using the type safe comparison operators you are both checking that the values are equal (or unequal) and that their type is the same. Without the type safe comparison operators, you are allowing the JavaScript engine the freedom to coerce your variables to true or false based on the truthy/falsey logic.

To cast your JavaScript variables to boolean, simply use two exclamation signs:

function() {
    var name = "Brian";

    //alert 'string'
    window.alert(typeof name);

    //cast to boolean
    var bool = !!name;

    //alert 'boolean'
    window.alert(typeof bool);
}
In the example code above we are casting the string "Brian" to a boolean value. Therefore the second alert will indicate that the variable is now a boolean value.


text:
Q: Error in mechanize python: no form matching nr 0 I am trying to webcrawl a website, however, I am getting the following error:
mechanize._mechanize.FormNotFoundError: no form matching nr 0.

The script is as follows:
import mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.open("http://dbaasp.org/prediction")
br.select_form(nr = 0)

## See what is available on this web page:
for f in br.forms():
    print f

How can this be ameliorated? Thank you.

A: If you want to handle this error in your Python script, just put try/except around your loop.
try:
    for f in br.forms():
        print(f)
except mechanize._mechanize.FormNotFoundError as e:
    print("Sorry no form found on this page", e)

A: The page you are accessing doesn't have any  html  element on it but use the  tag directly. You need to nest it inside

 <form>
  First name:

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

  Last name:

  <input type="text" name="lastname">
</form>


text:
Q: Swift iOS: dyld: dyld_sim cannot be loaded in a restricted process I'm making an iOS app for jailbroken devices running iOS 12 or newer.
I need my app to run a command line command, so to achieve that I use a custom Objective-C header file which creates the object NSTask and everything it needs, and then, using Bridging Headers I expose it to Swift.
So, to run a task I use the following function:
func task(launchPath: String, arguments: String...) -> NSString {
    let task = NSTask.init()
    task?.setLaunchPath(launchPath)
    task?.arguments = arguments

    // Create a Pipe and make the task
    // put all the output there
    let pipe = Pipe()
    task?.standardOutput = pipe

    // Launch the task
    task?.launch()
    task?.waitUntilExit()

    // Get the data
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

    return output!
}

And call it like this:
installPackage = task(launchPath: "/usr/bin/dpkg", arguments: "-i", packageID, "control")

I noted that this wasn't doing anything, so I wanted to check what was the command really doing.
To do this, I printed installPackage.
This should have printed the dpkg command output, but instead, it printed the following:
print(installPackage)

~> dyld: dyld_sim cannot be loaded in a restricted process

I've read that to fix this you need to turn off Thread Sanitizer or change the Build Configuration to Release, but it keeps showing the same message.
What can I do to fix this?


text:
Q: Ajax replacing content and using fade I'm trying to replace the div with "demo" as the id, to the content of "newpage.html". This code works, although I'm just wondering how I'd be able to put a fade effect into it.
<button onclick="loadDoc()">Click here</button>

function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          document.getElementById("demo").innerHTML = xhttp.responseText;
        }
      };
      xhttp.open("GET", "newpage.html", true);
      xhttp.send();
    }

A: Remove
document.getElementById("demo").innerHTML = xhttp.responseText;

Add this code instead
also change 'content' to 'xhttp.responseText'
$('#demo').fadeOut('slow', function() {
    $('#demo').html(content);
    $('#demo').fadeIn('slow');
});

Finally you have to add jquery library to perform 'FadeIn'
Jquery Library link Jquery
You have to add below code to your html header section.
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>


text:
Q: How do I create a temporary table out of this SQL merge statement? I have an SQL query in Access that is supposed to find duplicates and update a field based on that. It is giving me the "this query is not updateable" error. I read online that I need to create a subquery that creates a table? I'm not sure how to go about this at all honestly.
This is my query:
UPDATE work T INNER JOIN
      (SELECT DIVISION, FIPS_COUNTY_CODE, LAST, SUFFIX, FIRST, TITLE, BIRTHDATE
          FROM work
          GROUP BY DIVISION, FIPS_COUNTY_CODE, LAST, SUFFIX, FIRST, TITLE, BIRTHDATE
          HAVING COUNT(*) > 1
          ) AS S
      ON  T.DIVISION = S.DIVISION
      AND T.FIPS_COUNTY_CODE = S.FIPS_COUNTY_CODE
      AND T.LAST = S.LAST
      AND T.SUFFIX = S.SUFFIX
      AND T.FIRST = S.FIRST
      AND T.TITLE = S.TITLE
      AND T.BIRTHDATE = S.BIRTHDATE
SET T.BAD_CODES = T.BAD_CODES  & 'D'

A: Reasons why a Query or Recordset is not updateable
There are many reasons why your data may not be updateable. Some are pretty obvious:
•   The query is a Totals query (uses GROUP BY) or Crosstab query (uses TRANSFORM), so the records aren't individual records
•   The field is a calculated field, so it can't be edited
•   You don't have permissions/rights to edit the table or database
•   The query uses VBA functions or user defined functions and the database isn't enabled (trusted) to allow code to run
Some reasons are less obvious but can't be avoided:
•   The table being modified is a linked table without a primary key.
o   For certain backend databases (e.g. Microsoft SQL Server), Access/Jet requires the table to be keyed to make any changes. This makes sense since Access wants to issue a SQL query for modifications but can't uniquely identify the record.
Less obvious are these situations:
•   Queries with some summary fields linked to individual records and the individual records still can't be edited
•   Queries with multi-table joins that are not on key fields
•   Union queries
Copied from http://www.fmsinc.com/Microsoftaccess/query/non-updateable/index.html


text:
Q: How to randomize the position of buttons when i open the page? good afternoon!
I'm creating a little game for my first project on JavaScript, that will be a 10-button site where only one gives the prize. But I wanna randomize the order of the buttons, so, everytime i open the page, the right choice could be anywhere. How could i do this?
Here is my JavaScript and HTML code.

const buttons = document.querySelector('input.premio');

buttons.addEventListener('click', createParagraph);

function createParagraph() {
  let para = document.createElement('h3');
  para.textContent = 'VOCÊ ACERTOU!';
  document.body.appendChild(para);
  let newbtn = document.createElement('button');
  newbtn.textContent = 'Fechar guia';
  document.body.append(newbtn);
  newbtn.addEventListener('click', Fechar);
}

function Fechar() {
  window.close();
}

const fake1 = document.querySelector('input.btn1');

fake1.addEventListener('click', closewindow1);

function closewindow1() {
  window.close();
}

const fake2 = document.querySelector('input.btn2');

fake2.addEventListener('click', closewindow2);

function closewindow2() {
  window.close();
}

const fake3 = document.querySelector('input.btn3');

fake3.addEventListener('click', closewindow3);

function closewindow3() {
  window.close();
}

const fake5 = document.querySelector('input.btn5');

fake5.addEventListener('click', closewindow5);

function closewindow5() {
  window.close();
}

const fake6 = document.querySelector('input.btn6');

fake6.addEventListener('click', closewindow6);

function closewindow6() {
  window.close();
}

const fake7 = document.querySelector('input.btn7');

fake7.addEventListener('click', closewindow7);

function closewindow7() {
  window.close();
}

const fake8 = document.querySelector('input.btn8');

fake8.addEventListener('click', closewindow8);

function closewindow8() {
  window.close();
}

const fake9 = document.querySelector('input.btn9');

fake9.addEventListener('click', closewindow9);

function closewindow9() {
  window.close();
}

const fake10 = document.querySelector('input.btn10');

fake10.addEventListener('click', closewindow10);

function closewindow10() {
  window.close();
}

Jogo dos botões

Será que você é capaz de encontrar o botão premiado?

      <input type="button" value="Será que é aqui?" class='btn1'>

      <input type="button" value="Será que é aqui?" class='btn2'>

      <input type="button" value="Será que é aqui?" class='btn3'>

      <input type="button" value="Será que é aqui?" class='premio'>

      <input type="button" value="Será que é aqui?" class='btn5'>

      <input type="button" value="Será que é aqui?" class='btn6'>

      <input type="button" value="Será que é aqui?" class='btn7'>

      <input type="button" value="Será que é aqui?" class='btn8'>

      <input type="button" value="Será que é aqui?" class='btn9'>

      <input type="button" value="Será que é aqui?" class='btn10'>

A: Okay! I think this is what are you looking for.

function prize() {
  alert('prizee');
}

function closewindow() {
  window.close();
}

var random = Math.floor(Math.random() * 9) + 1; //we select a random number between 1 (inclusive) and 10 (inclusive)

// now we get the random number and we will set a event with prize function or what you want to do
// the rest of buttons will have set event with close window function.
// important is all buttons should have the class: btn1, btn2, btn3 ..., btn10
for(var i=1;i<=10;i++) {
  var button = document.querySelector('input.btn' + i);
    if(random == i) {
    button.addEventListener('click', prize);
    }
    else {
        button.addEventListener('click', closewindow);
    }
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jogo dos Botões</title>
    <link rel="stylesheet" href="style.css">

Jogo dos botões

Será que você é capaz de encontrar o botão premiado?

                <input type="button" value="Será que é aqui?" class='btn1'>

                <input type="button" value="Será que é aqui?" class='btn2'>

                <input type="button" value="Será que é aqui?" class='btn3'>

                <input type="button" value="Será que é aqui?" class='btn4'>

                <input type="button" value="Será que é aqui?" class='btn5'>

                <input type="button" value="Será que é aqui?" class='btn6'>

                <input type="button" value="Será que é aqui?" class='btn7'>

                <input type="button" value="Será que é aqui?" class='btn8'>

                <input type="button" value="Será que é aqui?" class='btn9'>

                <input type="button" value="Será que é aqui?" class='btn10'>

A: It is better to choose a button at random

var random = Math.floor(Math.random() * 10) + 1;
const button = document.querySelector('input.btn' + random);
button.addEventListener('click', createParagraph);
function createParagraph() {
    let para = document.createElement('h3');
    para.textContent = 'VOCÊ ACERTOU!';
    document.body.appendChild(para);
    let newbtn = document.createElement('button');
    newbtn.textContent = 'Fechar guia';
    document.body.append(newbtn);
    newbtn.addEventListener('click', Fechar);
}
function Fechar() {
    window.close();
}

Jogo dos botões

Será que você é capaz de encontrar o botão premiado?

      <input type="button" value="Será que é aqui?" class='btn1'>

      <input type="button" value="Será que é aqui?" class='btn2'>

      <input type="button" value="Será que é aqui?" class='btn3'>

      <input type="button" value="Será que é aqui?" class='premio'>

      <input type="button" value="Será que é aqui?" class='btn5'>

      <input type="button" value="Será que é aqui?" class='btn6'>

      <input type="button" value="Será que é aqui?" class='btn7'>

      <input type="button" value="Será que é aqui?" class='btn8'>

      <input type="button" value="Será que é aqui?" class='btn9'>

      <input type="button" value="Será que é aqui?" class='btn10'>


text:
Q: How to load another process' window as a child window? I have an executable called A.exe (say it is cmd.exe). I want to launch it (and also I want multiple instances of it) inside another window (that is I have to create) like,

How can I create such a window (program) using win32 or MFC ? Or this isn't possible ? Thank you.....
regards,

A: You could do it by hooking window creation and re-directing all creations to be children of the parent process.  AFAIK (And I'll probably get told otherwise) window handles are global so you can descend from ANY window, including windows in other processes.


text:
Q: Measuring how "connected" nodes are in a network I am an undergraduate studying economics and mathematics. I've never studied graph theory formally (only briefly in my spare time) and as such I don't have formal terms for what I'm clumsily trying to describe below. That's where I need help.
Suppose we have a graph $G$ with a set of verticies $R=\{ R_1,R_2,...,R_{n} \}$, and a set of weighted edges $E=\{ E_1,E_2,...,E_m \}$, where edge $E_i$ has weight $e_i$. Now, suppose further that each vertex $R_j$ has an associated value $r_j$.
I would like to assign a number $M_i$ to each vertex $R_i$ that captures its "access" to every other vertex's value $r_j$. The farther away vertex $R_{i}$ is from vertex $R_j$, the less impact $r_j$ has on $M_i$.  I've made a simple example to try and show what I mean by that. The vertex $R_j$ and its associated value $r_j$ are represented by $R_j(r_j)$.

Vertex $R_3$ would have the value $M_3=\frac{1}{5} \cdot 100 + \frac{1}{2} \cdot 20$, vertex $R_2$ would have the value $M_2=\frac{1}{2} \cdot 50 + \frac{1}{2+5} \cdot 100$, and vertex $R_1$ would have the value $M_1 = \frac{1}{5} \cdot 50 + \frac{1}{5+2} \cdot 20$. What I'm trying to capture of course is a cost for distance.
Things obviously become more complicated the more verticies there are. I would want to find the shortest path from $R_{\alpha}$ to $R_{\beta}$ before including $r_{\beta}$ in the measure $M_{\alpha}$. The process for determining $M_i$ would be

*

*Find the shortest path from $R_i$ to $R_j$ for all $i \neq j$.

*Let $d_{ij}$ be the sum of the weights of the edges that make up the shortest path between $R_i$ and $R_j$.

*Then $M_i = \sum_{j=1\neq i}^{n} \frac{1}{d_{ij}} \cdot r_j$

What is this sort of process called? I imagine that it provides a measure of how "connected" a given node is in a network that is comprised of nodes that are not all valued equally nor of equal distance apart.
My context (roughly): Attempting to model the change in market access of regional economies in 19th century United States as they became more interconnected by railways. A regional economy would gain greater access to other regional economies as more railways connected them, but distance would increase costs.

A: You are trying to measure something like the conductance (or, inversely, the resistance) between the two node). The canonical (elementary) reference on this is Doyle and Snell's random walks and electrical network, though Bollobas' "Modern graph theory" has a good discussion as well.


text:
Q: Communicate between UpdatePanels ASP.Net I have placed a treeView in One Update Panel and Each View in one update Panel
  something like this

   <UpdatePanel id="UP1">
     <ContentTemplate>
       <TreeView/>
     </ContentTemplate>
  </UpdatePanel>

   <MultiView>
    <UpdatePanel id="UP2">
      <View1/>
     </UpdatePanel>

Now I want to know how I can make sure When I click any node of TreeView respective Views should get displayed

A: Another way of approaching it would be to call UP2.Update() from the codebehind if you have code for the click event of the Treeview. Remember, UP2 needs to have its RenderMode set to Conditional for this to work. Hope it helps

A: Add an AsyncPostBackTrigger to the second updatePanel, so it gets updated when the TreeView Click event is fired.
<Asp:UpdatePanel id="UP2">
   <View1/>
   <Triggers>
      <asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="Click" />
   </Triggers>
</Asp:UpdatePanel>

OK, Here Is a working Example.
The Markup:
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

                <asp:UpdatePanel ID="upTreeView" runat="server">
                    <ContentTemplate>
                        <asp:TreeView ID="TreeView1" runat="server"
                            onselectednodechanged="TreeView1_SelectedNodeChanged">
                            <Nodes>
                                <asp:TreeNode Text="GrandFather" Value="GrandFather">
                                    <asp:TreeNode Text="Father" Value="Father">
                                        <asp:TreeNode Text="Son" Value="Son"></asp:TreeNode>
                                    </asp:TreeNode>
                                </asp:TreeNode>
                            </Nodes>
                        </asp:TreeView>
                    </ContentTemplate>
                </asp:UpdatePanel>

                <asp:UpdatePanel ID="upView" runat="server">
                    <ContentTemplate>
                        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="TreeView1"
                            EventName="SelectedNodeChanged" />
                    </Triggers>
                </asp:UpdatePanel>

The code behind:
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        Label1.Text = TreeView1.SelectedValue;
    }


text:
Q: retain contentView and release NSWindow _mainView = [[_window contentView] retain];
...
[_window release];
_window = nil;
return _mainView;

I meet code snippet above, I want to know what effects it really makes.
Thx.

A: Now you are the owner of highest accessible NSView object in the window's view hierarchy.
NSView  *mainView = [[window1 contentView] retain];
[window1 release];
window1 = nil;
[window setContentView:mainView];


text:
Q: Using ReportViewer server control with a parameterized server report in ASP.NET MVC project I am trying out using ReportViewer in an ASP.NET MVC project, and it worked well. However, when I introduced a parameter in the report, the ReportViewer failed to display the report. In other words, In ReportViewer you specify the parameter value and hit 'View Report', but nothing is displayed. I tried out retrieving the same report with same parameter value from an ASP.NET WebForms project with ReportViewer, and it worked perfectly fine.
My report is a server (rdl) report hosted in SQL Server 2008 R2.
My MVC project is the same as the best answer of this question, except that I am using a server report with a parameter.
The error is a JavaScript error, here is the full exception stack:

Uncaught exception:
  Sys.WebForms.PageRequestManagerParserErrorException:
  Sys.WebForms.PageRequestManagerParserErrorException: The message
  received from the server could not be parsed. Error thrown at line
  869, column 12 in Sys$WebForms$PageRequestManager$_endPostBack(error,
  executor, data) in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      throw error; called from line 1410, column 12 in Sys$WebForms$PageRequestManager$_parseDelta(executor) in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      this._endPostBack(this._createPageRequestManagerParserError(String.format(Sys.WebForms.Res.PRM_ParserErrorDetails,
  parserErrorDetails)), executor, ); called from line 1289, column 8 in
  Sys$WebForms$PageRequestManager$_onFormSubmitCompleted(sender,
  eventArgs) in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      var data = this._parseDelta(sender); called via Function.prototype.apply() from line 47, column 8 in () in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      return method.apply(instance, arguments); called from line 3484, column 16 in (source, args) in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      evt[i](source, args); called from line 6364, column 12 in Sys$Net$WebRequest$completed(eventArgs) in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      handler(this._executor, eventArgs); called from line 5984, column 16 in () in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      _this._webRequest.completed(Sys.EventArgs.Empty);
Error created at line 237, column 4 in Error$create(message,
  errorInfo) in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      var err = new Error(message); called from line 649, column 8 in Sys$WebForms$PageRequestManager$_createPageRequestManagerParserError(parserErrorMessage)
  in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      var e = Error.create(displayMessage, {name: 'Sys.WebForms.PageRequestManagerParserErrorException'}); called from
  line 1410, column 12 in
  Sys$WebForms$PageRequestManager$_parseDelta(executor) in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      this._endPostBack(this._createPageRequestManagerParserError(String.format(Sys.WebForms.Res.PRM_ParserErrorDetails,
  parserErrorDetails)), executor, null); called from line 1289, column 8
  in Sys$WebForms$PageRequestManager$_onFormSubmitCompleted(sender,
  eventArgs) in
  localhost:63763/ScriptResource.axd?d=9h24dbJaaly3rGMpfScOygOpMl0i9ZEfurAVmwlb3Yl0rMGkCKy1xLKet_d0sBUJJ4e0MXKZS5XmIx-OivjpZk0ANckormmfPEBQ-Afm2nzOCuVDyyfYtP5j0AZgct8H67Sb-su3x9adK7hL6Sr6mSRruPOfgpwkAx7FkQnNwxll0rK_eH5XspKF7I4bOja30&t=ffffffff940d030f:
      var data = this._parseDelta(sender); called via Function.prototype.apply() from line 47, column 8 in () in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      return method.apply(instance, arguments); called from line 3484, column 16 in (source, args) in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      evt[i](source, args); called from line 6364, column 12 in Sys$Net$WebRequest$completed(eventArgs) in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      handler(this._executor, eventArgs); called from line 5984, column 16 in () in
  localhost:63763/ScriptResource.axd?d=5kl0znaGl8mJnEQzUd91vqZhniJAoaXveYJu32ah4gLsmHOPWa96ICxMfSrJe-fpz4tHJdIFn_hkaL1FO-AADXzl-rRWgsT1CLV7B_tLY183SFpWsMANof_Lmsl3J9tuuHqYkhyJ_KZWOgebGYCVK5wpsX3XToZdY9wOAYQkNoVcAAlWiP-4bSDdiID80dex0&t=ffffffff940d030f:
      _this._webRequest.completed(Sys.EventArgs.Empty);

I believe something is missing in my settings. Again, my web.config is the same as this.

A: Reading that other question you linked, I am presuming the other difference is you have not included the following. Personally I have used a similar approach and couldn't get AsyncRendering working.
TLDR: Set AsyncRendering to false like:
AsyncRendering="false"


text:
Q: Grouping the data into categories based on a column I have a tab delimited file which have 2 columns as:
new.txt
    1.01   yes
    2.00   no
    0.93   no
    1.2223 yes
    1.7211 no

I want to modify the contents of it as if there are two categories as:
new_categorized.txt
yes    no
1.01   2.00
1.2223 0.93
       1.7211

I have found a similar question with an answer in R (here) ,however I need to do it with bash or awk..
I would appreciate your help.

A: $ cat tst.awk
BEGIN { FS=OFS="\t" }
!($2 in label2colNr) {
    label2colNr[$2] = ++numCols
    colNr2label[numCols] = $2
}
{
    colNr = label2colNr[$2]
    val[++numRows[colNr],colNr] = $1
    maxRows = (numRows[colNr] > maxRows ? numRows[colNr] : maxRows)
}
END {
    for (colNr=1; colNr <= numCols; colNr++) {
        printf "%s%s", colNr2label[colNr], (colNr<numCols ? OFS : ORS)
    }

    for (rowNr=1; rowNr <= maxRows; rowNr++) {
        for (colNr=1; colNr <= numCols; colNr++) {
            printf "%s%s", val[rowNr,colNr], (colNr<numCols ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk file
yes     no
1.01    2.00
1.2223  0.93
        1.7211

The above will work with any awk in any shell on any UNIX system no matter how many categories you have in the 2nd field and no matter what their values are.

A: With bash, GNU grep and paste:
echo -e "yes\tno"
paste <(grep -Po '^\t\K.*(?=\tyes)' new.txt) <(grep -Po '^\t\K.*(?=\tno)' new.txt)

Output:

yes     no
1.01    2.00
1.2223  0.93
        1.7211

A: GNU awk solution:
awk '{ a[$2][($2=="yes"? ++y : ++n)]=$1 }
     END{
         max=(y > n? y:n);
         print "yes","no";
         for(i=1; i<=max; i++) print a["yes"][i], a["no"][i]
     }' OFS='\t' file | column -tn

The output:
yes     no
1.01    2.00
1.2223  0.93
        1.7211


text:
Q: Apply design as user is swiping and removing design on aborted swipe I have: A RecyclerView where I can swipe cards to the right.
I want: Add a border to the selected card while the user is holding down her finger to swipe. However, as soon as the user lets go of their finger and aborts the swipe, I want the border to go away.
I've managed so far: I managed to implement an onItemTouchHelper that allows me to change the design during touch. It changes the color around the card to Blue during swipe. But the border just stays even when swipe is aborted.
Issue I have: The border does not go away when the user let's go of the card (aborts swipe)
Here's my code:
@Override
        public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

            View itemView = viewHolder.itemView;

            itemView.setRotation(
                    swipeLayoutManager.getAngle() * (dX / recyclerView.getMeasuredWidth()));

            itemView.setBackgroundColor(Color.BLUE);

            }

NOTE 1: The itemView.setBackgroundColor does create a Blue border around the card. But it doesn't go away when the user aborts the swipe and the card falls back into place.
NOTE 2: The itemView.setRotation method I implemented here works only applies the change in angle during the swipe but returns the angle to normal as soon as the swipe is aborted. I fail to implement the same thing with the border. When I try, it applies a color only during the swipe but the colors change all the time creating some crazy blinking effect.

A: Solved issue by creating a Boolean variable viewBeingCleared and setting it to false in the onChildDraw method. Then implementing the clearView method and setting the boolean back to true.
Go to this post to the solution in full: Why ItemTouchHelper.Callback's onChildDraw will be called after clearView


text:
Q: Piecewise quadratic interpolation in a symmetric manner I am trying to derive a reasonable symmetric interpolant for quadratic $C^0$ interpolation. For odd degrees I have no trouble since things are symmetric. For example for a piecewise cubic interpolant I could define it in each interval $[x_{i-1},x_i]$ to be the cubic polynomial passing through $(x_{i-2},y_{i-2}),\, (x_{i-1},y_{i-1}), \,(x_{i},y_i),\, (x_{i+1},y_{i+1})$. For odd degrees this results in $C^{k-2}$ continuity, where $k$ is the degree of the polynomial. I am aware that I can construct a $C^{k-1}$ interpolant if I additionally solve a linear system of equations, but due to performance considerations I have decided to avoid this.
The issue is that the even degree case is not symmetric. For example I am not sure what constraints would make sense for piecewise quadratic interpolation. If for an interval $[x_{i-1}, x_i]$ I were to take the quadratic polynomial passing through $(x_{i-1}, y_{i-1}),\, (x_i, y_i), \, (x_{i+1},y_{i+1})$ then this emphasizes $(x_{i+1},y_{i+1})$ while it ignores $(x_{i-2}, y_{i-2})$. On the other hand if I were to take the quadratic polynomial passing through $(x_{i-2}, y_{i-2}), \,(x_{i-1}, y_{i-1}),\, (x_i, y_i)$ then this emphasizes $(x_{i-2}, y_{i-2})$ and ignores $(x_{i+1}, y_{i+1})$. Is there some standard approach for constructing a symmetric constraint that doesn't involve solving a system of linear equations for the global piecewise interpolant?
I want the piecewise interpolant in the interval $[x_{i-1}, x_i]$ to pass through $(x_{i-1},y_{i-1})$ and $(x_i, y_i)$, which leaves me with 1 parameter. Ideally I want to determine said parameter symmetrically from both $(x_{i-2},y_{i-2})$ and $(x_{i+1}, y_{i+1})$.

A: The following is not standard, as far as I know, but it might work.
We're interested in how to construct a quadratic interpolant $Q(x)$ on $[x_{i-1}, x_i]$. Let $z=\tfrac12(x_{i-1} + x_i)$. If we could decide a suitable value for $Q(z)$, we'd be done.
So, let $A(x)$ be the quadratic interpolant through $x_{i-2}, x_{i-1}, x_i$, let $B(x)$ be the interpolant through $x_{i-1}, x_i, x_{i+1}$, and let $Q(z) = \tfrac12 (A(z) + B(z))$.
That's symmetric, at least.

A: I also tried deriving an interpolating synthesis function by analogy to how it is done in Keys' paper Cubic convolution interpolation for digital image processing. Granted there are multiple choices so I am not claiming that what I derived is the best in any sense of the word.
For a synthesis function (on a regular grid) one typically desires symmetry around $0$, interpolation at the different points, and smoothness.
Taking into account symmetry, it is enough to only consider the intervals $[0,1]$ and $[1,2]$ and fit a quadratic functions within each: $u_1(x) = a_1x^2 + b_1x + c_1$ and $u_2(x) = a_2x^2 + b_2x + c_2$. Then the symmetric versions would have minuses in front of the odd degrees. The interpolating conditions read:
$$u_1(0) = 1, \, u_1(1) = 0, \, u_2(1) = 0, \, u_2(2) = 0$$
$$c_1 = 1, \, a_1+b_1 = -1, \, a_2+b_2+c_2 = 0, 4a_2 + 2b_2 + c_2 = 0$$
I can additionally require that $u_1'(0) = 0$ resulting in $b_1 = 0$ which yields:
$$u_1(x) = -x^2+1.$$
Furthermore I can require that $u_1'(1) = -2 = u_2'(1) = 2a_2 + b_2$. Solving for $a_2, b_2, c_2$ yields:
$$u_2(x) = 2x^2-6x+4.$$
Ultimately the synthesis function is:
$$\phi_2(x) = \begin{cases} -x^2+1 & |x| \leq 1 \\
                            2x^2-6|x|+4 & 1 \leq |x| \leq 2 \\
                            0 & |x| > 2\end{cases}$$
It has the following shape:

The $\frac{1}{2}$ version that bubba suggested results in the synthesis function:
$$\phi_2(x) = \begin{cases} -\frac{1}{4}x^2-\frac{3}{4}|x|+1 & |x| \leq 1 \\
                            \frac{1}{4}x^2-\frac{3}{4}|x|+\frac{1}{2} & 1 \leq |x| \leq 2 \\
                            0 & |x| > 2\end{cases}$$
This seems to match quite well what one should expect from Lagrange interpolating functions (I discuss some details here, also using the idea of bubba Constructing $C^{k−2}$ and $C^{k−1}$ splines on a regular grid through convolution). The shape of the synthesis function is:


text:
Q: Question on domain and range of nonlinear, multivalued operator I'm reading a paper by Crandall Liggett ("Generation of semi-groups...") and I have a question about one of the lemmas.
I'll included some "background information" as I'm not sure if it's relevant for my question or not.
They say:

A subset $B \subset X  \times X$ ($X$ is a Banach space) is called accretive if $(I+\lambda B)^{-1}$ is a function for $\lambda>0$ and:
  $\lVert (I+\lambda B)^{-1}x- (I+\lambda B)^{-1}y \rVert \leq \lVert x-y \rVert$
  for $x,y\in D((I+\lambda B)^{-1})$.

and further:

a set $A \subset X \times X $ and a real number $\omega$ such that $A+\omega I$ is an accretive operator are fixed. If $\lambda$ is real let $J_\lambda$ denote the set$ (I+\lambda A)^{-1}$  and $D_\lambda=D(J_\lambda)$ be its domain.

My question is about the following step in the proof of Lemma 1.2.ii):

Take $[x_1,y_1]\in A$ and $[x,y]\in A$ such that $x_1+\lambda y_1 =x$

For this to be possible one needs to have $x \in D(A)\cap R (I+\lambda A)$, but how does one know that this set is non-empty? Does it follow from one of the assumptions above or something more basic?


text:
Q: How do I set a default FileHandle attribute with moose You may infer from the question that this is my first Moose class.
How do I set an attribute FileHandle to *STDOUT?
This doesn't work.
has 'output' => (
    is => 'rw',
    isa => 'FileHandle',
    default => sub { openhandle(*STDOUT) }
);

The output when run is:

Attribute (output) does not pass the type constraint because: Validation failed for 'FileHandle' with value *main::STDOUT

The documentation claims:

FileHandle accepts either an IO::Handle object or a builtin perl
  filehandle (see "openhandle" in Scalar::Util).

What am I missing?
Thanks.
-E

A: I don't know what else you may need there, but this works for starters
The WithFH.pm
package WithFH;

use feature 'say';
use Moose;

has 'fh' => (is => 'ro', isa => 'FileHandle', default => sub { \*STDOUT } );

sub say {
    my $self = shift;
    say { $self->{fh} } "@_";
}

__PACKAGE__->meta->make_immutable;
1;

and the main
use warnings;
use strict;
use feature 'say';

use WithFH;

my $wfh = WithFH->new;

$wfh->say("hi");

That prints hi to STDOUT.


text:
Q: Remove brackets if the content inside is a number Is there any way to remove the brackets () if the content inside .isnumeric()
I do know a little bit of RegEx but I'm unable to find a way to do it using RegEx.
Example:
input = '((1)+(1))+2+(1+2)+((2))'
output = somefunction(input)

Here the output should look like
(1+1)+2+(1+2)+2

A: import re

x = '((1)+(1))+2+(1+2)+((2))'
re.sub(r'(\()([\d*\.]+)(\))', r"\2", x)

"""
or
re.sub(r'\(([\d*\.]+)\)', r"\1", x) #  @deceze
"""

But this will give you
(1+1)+2+(1+2)+(2)
Can maybe use re.subn to do this until number of replacements are 0


text:
Q: display system ringtones list in wp7 in a third party application I am developing a wp7 application that requires me to tap on a textblock and on that tap the list of system ringtones should get displayed from which the user can select a ringtone. But unfortunately I am not able to find a way to do this. Can anyone help me in this?

A: No, this is not possible at this point of time, as the Microsoft.Phone.RingToneLibrary supports only the adding of the RingTones.
May be in future if Microsoft provides any API, then its possible to access system ringtones.


text:
Q: How to track mobile location using traccar open source? I am trying to track my iPhone using traccar.
I installed traccar server in windows 7 and ios client application in iphone 4s.
I added my iPhone successfully in traccar web application and it is updating location per minute.
But in traccar we application when I load my phone it always display error "No results found for selected period"
Below is a log file of traccar server...

2015-01-27 11:59:44
  INFO: Starting server... 2015-01-27 11:59:44 INFO: Operating
  System name: Windows 7 version: 6.1 architecture: x86 2015-01-27
  11:59:44 INFO: Java Runtime name: Java HotSpot(TM) Client VM vendor:
  Oracle Corporation version: 25.31-b07 2015-01-27 11:59:44 INFO:
  Memory Limit heap: 247mb non-heap: 0mb 2015-01-27 11:59:44 INFO:
  Version: 2.11-SNAPSHOT 2015-01-27 12:02:39 DEBUG: [5005 <-
  192.168.1.59] - HEX: 24504749442c3838353839352a30300d0a 2015-01-27 12:02:39 WARN: Unknown device - 885895 2015-01-27 12:02:42 DEBUG:
  [5005 <- 192.168.1.59] - HEX:
  244750524d432c3036333231342e3030302c412c323833362e383730352c4e2c30373732312e373135302c452c302e30302c3131362e30322c3237303131352c2c2a30300d0a
  2015-01-27 12:03:46 DEBUG: [5005 <- 192.168.1.59] - HEX:
  244750524d432c3036333331352e3030302c412c323833362e383731362c4e2c30373732312e373134322c452c302e30302c302e30302c3237303131352c2c2a30300d0a

Please provide appropriate solution.

A: You need to register your device through web interface with 885895 as a unique identifier.

A: I had the same problem because I was trying this application in my office. You know that GPS doesn't work indoors so you will have to go outside with your Iphone. Try it if work.
Best of luck!


text:
Q: Entity Framework Core: generated query selects a column which does not exists anymore I have an entity model generated by dotnet ef dbcontext scaffold.
It generated (among others) a class for this table:
CREATE TABLE MyTable
(
    Id INT IDENTITY(1,1) NOT NULL,
    ProductId INT NOT NULL,
    CountryId NVARCHAR(3) NOT NULL
);

Class:
public class MyTable
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public string CountryId { get; set; }
}

DbContext:
// extraction ...
public virtual DbSet<MyTable> MyTables { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyTable>(entity =>
    {
        entity.ToTable("MyTable");
        entity.Property(e => e.CountryId).HasMaxLength(3);
    }
}
// ...

After some time I made a change to this table:
CREATE TABLE MyTable
(
    Id INT IDENTITY(1,1) NOT NULL,
    ProductId INT NOT NULL,
    TheCountryId INT NOT NULL -- Rename and change the Data type
);

And of course to the class and DbContext as well.
Class:
public class MyTable
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int TheCountryId { get; set; }  // Rename and change the Data type
}

DbContext:
// extraction ...
public virtual DbSet<MyTable> MyTables { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyTable>(entity =>
    {
        entity.ToTable("MyTable");
        // Remove restriction
    }
}
// ...

When I run _db.MyTables.ToArray() or similar code, Entity Framework generates queries which still select CountryId (and not TheCountryId)
SELECT
    [m.MyTable].[Id], [m.MyTable].[ProductId], [m.MyTable].[CountryId], [m.MyTable].[TheCountryId]
FROM
    [MyTable] AS [m.MyTable]

Why does this happen? I removed all that indicates that the class had a property CountryId. I also deleted the bin an obj folders to make sure the program is a clear compilation. Nothing works. Is Entity Framework Core caching queries or is SQL Server doing this?


text:
Q: Encounter the RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation I'm getting the following error when calling .backward():
Encounter the RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
Here's the code:
for i, j, k in zip(X, Y, Z):
    A[:, i, j] = A[:, i, j] + k

I've tried .clone(), torch.add(), and so on.
Please help!

A: After the comments I'm a bit confused about what you want to accomplish. The code you gave gives me an error using the dimensions you provided in the comments
Traceback (most recent call last):
    A[:, i, j] = A[:, i, j] + k
RuntimeError: The size of tensor a (32) must match the size of tensor b (200) at non-singleton dimension 0

But here's what I think you want to do, please correct me in the comments if this is wrong...
Given tensors X, Y, and Z, each entry of X, Y, and Z correspond to a coordinate (x,y) and a value z. What you want is to add z to A at coordinate (x,y). For most cases the batch dimension is kept independent, although its not clear that's the case in the code you posted. For now that's what I'll assume you want to do.
For example lets say A contains all zeros and has shape 3x4x5 and X,Y are shape 3x3 and Z is shape 3x3x1. For this example let's assume A contains all zeros to start, and X, Y, and Z have the following values
X = tensor([[1, 2, 3],
            [1, 2, 3],
            [2, 2, 2]])
Y = tensor([[1, 2, 3],
            [1, 2, 3],
            [1, 1, 1]])
Z = tensor([[[0.1], [0.2], [0.3]],
            [[0.4], [0.5], [0.6]],
            [[0.7], [0.8], [0.9]]])

Then we would expect A to have the following values after the operation
A = tensor([[[0,   0,   0,   0,   0],
             [0,   0.1, 0,   0,   0],
             [0,   0,   0.2, 0,   0],
             [0,   0,   0,   0.3, 0]],

            [[0,   0,   0,   0,   0],
             [0,   0.4, 0,   0,   0],
             [0,   0,   0.5, 0,   0],
             [0,   0,   0,   0.6, 0]],

            [[0,   0,   0,   0,   0],
             [0,   0,   0,   0,   0],
             [0,   2.4, 0,   0,   0],
             [0,   0,   0,   0,   0]]])

In order to accomplish this we can make use to the index_add function which allows us to add to a list of indices. Since this only supports 1-dimensional operations we first need to convert X,Y to a linear index for flattened tensor A. Afterwards we can un-flatten to the original shape.
layer_size = A.shape[1] * A.shape[2]
index_offset = torch.arange(0, A.shape[0] * layer_size, layer_size).unsqueeze(1)
indices = (X * A.shape[2] + Y) + index_offset
A = A.view(-1).index_add(0, indices.view(-1), Z.view(-1)).view(A.shape)