text:
Q: Magento 2 - What is the proper way to edit core file? For my Paypal Payment issue,
I just want to update the following function,
app/code/Magento/Paypal/Model/Api/Nvp.php
protected function _applyStreetAndRegionWorkarounds(DataObject $address)
{
// merge street addresses into 1
if ($address->getData('street2') !== null) {
$address->setStreet(implode("\n", [$address->getData('street'), $address->getData('street2')]));
$address->unsetData('street2');
}
// attempt to fetch region_id from directory
if ($address->getCountryId() && $address->getRegion()) {
$regions = $this->_countryFactory->create()
->loadByCode($address->getCountryId())
->getRegionCollection()
->addRegionCodeOrNameFilter($address->getRegion())
->setPageSize(1);
if ($regions->count()) {
$regionItems = $regions->getItems();
$region = array_shift($regionItems);
$address->setRegionId($region->getId());
$address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id']));
}
}
}

Instead of
  protected function _applyStreetAndRegionWorkarounds(DataObject $address)
    {
        // merge street addresses into 1
        if ($address->getData('street2') !== null) {
            $address->setStreet(implode("\n", [$address->getData('street'), $address->getData('street2')]));
            $address->unsetData('street2');
        }
        // attempt to fetch region_id from directory
        if ($address->getCountryId() && $address->getRegion()) {
            $regions = $this->_countryFactory->create()->loadByCode(
                $address->getCountryId()
            )->getRegionCollection()->addRegionCodeOrNameFilter(
                $address->getRegion()
            )->setPageSize(
                1
            );
            $regionItems = $regions->getItems();
            $region = array_shift($regionItems);
            $address->setRegionId($region->getId());
            $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id']));
        }
    }

Source: https://github.com/magento/magento2/issues/26698
What is the best way to edit core files? Module or Preference or anything else?
My Error:
Fatal error: Uncaught Error: Call to a member function getId() on null in /var/www/html/test/app/code/Magento/Paypal/Model/Api/Nvp.php:1524 Stack trace:
#0 /var/www/html/test/app/code/Magento/Paypal/Model/Api/Nvp.php(1493): Magento\Paypal\Model\Api\Nvp->_applyStreetAndRegionWorkarounds(Object(Magento\Framework\DataObject))
#1 /var/www/html/test/app/code/Magento/Paypal/Model/Api/Nvp.php(849): Magento\Paypal\Model\Api\Nvp->_exportAddresses(Array)
#2 /var/www/html/test/app/code/Magento/Paypal/Model/Express/Checkout.php(621): Magento\Paypal\Model\Api\Nvp->callGetExpressCheckoutDetails()
#3/var/www/html/test/app/code/Magento/Paypal/Controller/Express/AbstractExpress/ReturnAction.php(32): Magento\Paypal\Model\Express\Checkout->returnFromPaypal('*********')
#4/var/www/html/test/generated/code/Magento/Paypal/Controller/Express/ReturnAction/Interceptor.php(24): Magento\Paypal\Controller\Express\AbstractExpress\ReturnAction->execute()
#5 /var/www/html/test/lib/internal/Magento/Framework/App/Action/Ac in /var/www/html/test/app/code/Magento/Paypal/Model/Api/Nvp.php on line 15

Note: Is the following patch suitable for my error,
https://magento.com/tech-resources/download#tab-36   (PayPal Express Checkout issue with region patch for Magento 2.3.4)

A: In your di.xml create a preference to your own implementation
app/code/StackExchange/PayPalPreference/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"
>
 <preference
     for="Magento\Paypal\Model\Api\Nvp"
     type="StackExchange\PayPalPreference\Model\Api\Nvp"
 />
</config>

In your own implementation, extend the class you want to change and override only the method in question. You will have to create a constructor matching the parent constructor, it will look something like this:
app/code/StackExchange/PayPalPreference/Model/Api/Nvp.php
<?php
declare(strict_types=1);

namespace StackExchange\PayPalPreference\Model\Api;

use Magento\Payment\Model\Method\Logger;

class Nvp extends \Magento\Paypal\Model\Api\Nvp
{
    public function __construct(
        \Magento\Customer\Helper\Address $customerAddress,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Payment\Model\Method\Logger $customLogger,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        \Magento\Directory\Model\RegionFactory $regionFactory,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Paypal\Model\Api\ProcessableExceptionFactory $processableExceptionFactory,
        \Magento\Framework\Exception\LocalizedExceptionFactory $frameworkExceptionFactory,
        \Magento\Framework\HTTP\Adapter\CurlFactory $curlFactory,
        array $data = []
    ) {
        parent::__construct($customerAddress, $logger, $customLogger, $localeResolver, $regionFactory, $countryFactory, $processableExceptionFactory, $frameworkExceptionFactory, $curlFactory, $data);
    }

    protected function _applyStreetAndRegionWorkarounds(DataObject $address)
    {
        if ($address->getData('street2') !== null) {
            $address->setStreet(implode("\n", [$address->getData('street'), $address->getData('street2')]));
            $address->unsetData('street2');
        }
        if ($address->getCountryId() && $address->getRegion()) {
            $regions = $this->_countryFactory->create()
                ->loadByCode($address->getCountryId())
                ->getRegionCollection()
                ->addRegionCodeOrNameFilter($address->getRegion())
                ->setPageSize(1);
            if ($regions->count()) {
                $regionItems = $regions->getItems();
                $region = array_shift($regionItems);
                $address->setRegionId($region->getId());
                $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id']));
            }
        }
    }
}

You can change the app/code/StackExchange/PayPalPreference/Model/Api/Nvp.php like this and use storeManager to fetch website id to decide whether to run the code or not for particular websites:
<?php
declare(strict_types=1);

namespace StackExchange\PayPalPreference\Model\Api;

use Magento\Store\Model\StoreManagerInterface;

class Nvp extends \Magento\Paypal\Model\Api\Nvp
{
    /**
     * @var StoreManagerInterface
     */
    private StoreManagerInterface $storeManager;

    public function __construct(
        \Magento\Customer\Helper\Address $customerAddress,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Payment\Model\Method\Logger $customLogger,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        \Magento\Directory\Model\RegionFactory $regionFactory,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Paypal\Model\Api\ProcessableExceptionFactory $processableExceptionFactory,
        \Magento\Framework\Exception\LocalizedExceptionFactory $frameworkExceptionFactory,
        \Magento\Framework\HTTP\Adapter\CurlFactory $curlFactory,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        parent::__construct($customerAddress, $logger, $customLogger, $localeResolver, $regionFactory, $countryFactory, $processableExceptionFactory, $frameworkExceptionFactory, $curlFactory, $data);

        $this->storeManager = $storeManager;
    }

    protected function _applyStreetAndRegionWorkarounds(DataObject $address)
    {
        // e.g. if you do not want to run the code on website id = 2
        if ($this->storeManager->getWebsite()->getId() == 2) {
            parent::_applyStreetAndRegionWorkarounds($address);
            return;
        }

        if ($address->getData('street2') !== null) {
            $address->setStreet(implode("\n", [$address->getData('street'), $address->getData('street2')]));
            $address->unsetData('street2');
        }
        if ($address->getCountryId() && $address->getRegion()) {
            $regions = $this->_countryFactory->create()
                ->loadByCode($address->getCountryId())
                ->getRegionCollection()
                ->addRegionCodeOrNameFilter($address->getRegion())
                ->setPageSize(1);
            if ($regions->count()) {
                $regionItems = $regions->getItems();
                $region = array_shift($regionItems);
                $address->setRegionId($region->getId());
                $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id']));
            }
        }
    }
}


text:
Q: Echoing html link mailto I'm using Ckeditor on a field of a CakePHP form.
No problems saving the information on the database the problem is when I echo the content of that field. If the field as a link of the type mailto I get a denied: in the beginning of the href attribute.
For example:
name@domain.com

To echo the field value I'm using:
echo $data['Ent']['text'];

A: you can use :
<?php echo $this->Html->link($v['mail'],'mailto:'.$v['mail'],array('target' => '_blank'));?>

A: Dont know why Ckediter is doing that but you can remove it using jquery
name@domain.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 2.3 get custom category attribute in .phtml file I have created a custom category attribute title_description and is showing on the admin side and I can save data. But when I try to show the value on the frontend using getTitleDescription() it is not showing anything. It is working for default category attributes like getName() and getId(). In my block I have created the function
public function getCurrentCategory()
    {
        $currentCategory = $this->registry->registry('current_category');
        return $currentCategory;
    }

And in .phtml file I am calling
$block->getCurrentCategory()->getTitleDescription()

It works on other pages where I am using a collection of categories and looping through it. But not working when calling an individual category

A: You can add your custom attribute to Magento's list of attributes that it'll load by default when loading categories.
Create a file called catalog_attributes.xml in the etc folder of your module.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="catalog_category">
        <attribute name="title_description"/>
    </group>
</config>

Note that the group is called catalog_category, which is the group for auto-loaded attributes. This file is capable of doing other things as well, which you can learn about here.

A: You can also try adding
public function getTitleDesc()
{
    return $this->getCustomAttribute('title_description');
}

In your block and then call the function.
Note you should flush the cache before calling it.


text:
Q: how to change the selected value of a disabled dropdownlist in jquery I want to change the selected value to a disabled dropdownlist to someother value on a button click. Managed to change the value but the issue is when i submit the form previously selected value is submitted.
$("#RatesImplementation").click(function () {
    $('#DrpDwnRequestStatus').val('Rates Implementation').trigger('change');
    $('#DrpDwnNextStage').val('Implementation Approval').trigger('change');

});

this wont set selected attribute for the option.
Any help would be appreciated.Thanks!

I was hidden variable for submitting the disabled field value.
$("#RatesImplementation").click(function () {
    $('#DrpDwnRequestStatus').val('Rates Implementation').trigger('change');
    $('#DrpDwnNextStage').val('Implementation Approval ').trigger('change');
    $('#hdnRequestStatus').val('Rates Implementation');
    $('#hdnNextStage').val('Implementation Approval ')
});


text:
Q: Android send array from classA to classB in class A I have a array
final Integer[] images = {R.drawable.aa, R.drawable.aa2, R.drawable.aa3, R.drawable.aa4, R.drawable.aa5};

I need to send this array to class B and make something like this:
Button button = (Button)findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View viev) {
                // TODO Auto-generated method stub

                image.setImageResource(images[0]);
                        }
                });
            Button button2 = (Button)findViewById(R.id.button2);
            button2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View viev) {
                    // TODO Auto-generated method stub

                image.setImageResource(images[1]);
                        }
        });

A: Since Resources are accessible for all the application you dont need to pass the array. Just intialize it in the Class B, IF you don't affect it in Class A.

A: If I understand you  correctly ,you want to pass integer array from one activity to another.
in that can you can try follow code;
Intend i = new Intent(A.this,B.class);
i.putIntegerArrayListExtra(String name, ArrayList<Integer> value);
startActivity(i);


text:
Q: Select values in a table conditional to an external table I'd like to select the first N values of each variables (columns) in a data set, where N varies by column and row and are given in an other table. An example below with the iris data:
data(iris)
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

## Create a fake external table
ext.tab <- data.table(species=c("setosa","versicolor", "virginica" ),N1=c(1:3),N2=c(3:5),N3=c(5:7),N4=c(7:9))
head(ext.tab)

      species N1 N2 N3 N4
1:     setosa  1  3  5  7
2: versicolor  2  4  6  8
3:  virginica  3  5  7  9

Now for Iris setosa, I'd like to get the first maximum value (N1 in ext.tab) of column 1 ('sepal.length' in iris data), then the three max values (N2 in ext.tab) for column 2 (sepal.width), then the five max values (N3) for column 3 (petal.length) and so forth. Then moving to the Iris versicolor and do the same.
The result can be either a table or a list for each species with the values themselves or row indices for each variable (column). Any idea of a fast way to implement that?

A: Here is a tidyverse approach using a custom function. The function takes the variable and group names as character scalar and number of maximum values as numeric. Inside the function is a dplyr pipeline using .data pronoun. Then, I reshaped ext.tab to long form and applied get_maximum() row-wise.
library(tidyverse)

get_maximum <- \(.x, .group, .n_max, .dat) {
  .dat %>%
    filter(Species == .group) %>%
    arrange(desc(.data[[.x]])) %>%
    slice(seq_len(.n_max)) %>%
    pull(.data[[.x]])
}

dat <- as_tibble(ext.tab) %>%
  pivot_longer(-species) %>%
  mutate(name = recode(
    name,
    N1 = "Sepal.Length",
    N2 = "Sepal.Width",
    N3 = "Petal.Length",
    N4 = "Petal.Width"
  )) %>%
  rowwise() %>%
  mutate(max_num = list(
    get_maximum(name, species, value, iris)
  )) %>%
  ungroup()

If you need the unique maximum values, you can add distinct() inside the custom function.
get_maximum_unique <- \(.x, .group, .n_max, .dat) {
  .dat %>%
    filter(Species == .group) %>%
    distinct(.data[[.x]]) %>%
    arrange(desc(.data[[.x]])) %>%
    slice(seq_len(.n_max)) %>%
    pull(.data[[.x]])
}

A: Here is an option using data.table. I have taken the liberty of renaming the column names.
cols <- setdiff(names(ext.tab), "Species")
iris[ext.tab, on=.(Species), by=.EACHI,
    .(.(mapply(function(x, n) -head(sort(-x, partial=n), n),
        x=mget(cols), n=mget(paste0("i.", cols)), SIMPLIFY=FALSE)))]$V1

data:
library(data.table)
iris <- as.data.table(iris)
ext.tab <- data.table(Species=c("setosa", "versicolor", "virginica"),
    Sepal.Length=c(1:3),
    Sepal.Width=c(3:5),
    Petal.Length=c(5:7),
    Petal.Width=c(7:9))

output:
[[1]]
[[1]]$Sepal.Length
[1] 5.8

[[1]]$Sepal.Width
[1] 4.4 4.2 4.1

[[1]]$Petal.Length
[1] 1.9 1.9 1.7 1.7 1.7

[[1]]$Petal.Width
[1] 0.4 0.4 0.6 0.4 0.5 0.4 0.4

[[2]]
[[2]]$Sepal.Length
[1] 7.0 6.9

[[2]]$Sepal.Width
[1] 3.4 3.3 3.2 3.2

[[2]]$Petal.Length
[1] 5.1 4.8 4.9 5.0 4.9 4.8

[[2]]$Petal.Width
[1] 1.7 1.6 1.6 1.8 1.5 1.5 1.6 1.5

[[3]]
[[3]]$Sepal.Length
[1] 7.7 7.9 7.7

[[3]]$Sepal.Width
[1] 3.8 3.8 3.6 3.4 3.4

[[3]]$Petal.Length
[1] 6.4 6.3 6.7 6.9 6.7 6.6 6.1

[[3]]$Petal.Width
[1] 2.5 2.5 2.4 2.5 2.4 2.4 2.3 2.3 2.3

Short explanation:

*

*Perform a left join iris[ext.tab, on=.(Species),

*by=.EACHI means for each row of ext.tab

*x=mget(cols) gets the columns in iris

*mget(paste0("i.", cols)) gets the number of values required for each column

*-head(sort(-x, partial=n), n) performs a partial sort and extract the first n values

*SIMPLIFY=FALSE and .(.( )) are simply required to return the results as a list


text:
Q: New Community Managers have no "staff" indicator in their profile Since July 2019, Employee profiles are now marked with a "Staff" indicator.
This worked well and people working for Stack Exchange back then indeed got the indicator, however looks like it stopped working at some point.
Both Ayo (started working at Stack Exchange a week ago) and Rosie (started working yesterday) have no staff indicator in their profiles. In case of Rosie it still might be some cache, but I doubt a whole week can be due to cache.
Can this please be fixed, or in case it's on purpose (I don't aspire to know why) can the decision please be reconsidered and staff indicator be given even to new employees? Having some with and some without is worse and more confusing than not having it at all, in my opinion.

A: The two new CM's now both have `staff` tags on their profile pages and have been modded across the network.

regret the delay
user account type now set
for our new CMs


text:
Q: Extract data from cell in excel I need to extract data from excel cell. The data is locked between two brackets.
For example: if I have DYT[[AU7]]YHU in a cell, I need to extract AU7.
Edit:
I'm having this formula: MID(A2,FIND("[",A2)+1,FIND("]",A2)-FIND("[",A2)-1)
but I'm getting [AU7 instead AU7
Can someone told me where's my mistake?
Thank you in advance

A: Ok.. I found an answer:
MID(A2,FIND("[",A2)+2,FIND("]",A2)-FIND("[",A2)-2)
Thanks for those who tried to help!


text:
Q: error during build using sandcastle help builder with visual studio 2010 .NET 4.0 project I was using sandcastle to generate help for my project in visual studio 2008. When i change my project to visual studio 2010 and change the project .NET version to .NET 4.0 i got this problem with Sandcastel. I can't understand why sandcastel is using C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe
and not
C:\Windows\Microsoft.NET\Framework64\v4.0\MSBuild.exe
thinking that i specified as framework version the v4.0.30319
Can anyone tell me how to resolve this issue?? Where to change the path of the msbuild.exe or some other solution ???
Generating reflection information...
[C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe]
GenerateRefInfo:
  MrefBuilder (v2.4.10520.1)
  Copyright c Microsoft 2006
  Info: Loaded 1 assemblies for reflection and 0 dependency assemblies.
MREFBUILDER : error : Unresolved assembly reference: System.Windows.Forms (System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089) required by WLAEDInt

Last step completed in 00:00:01.2731

-------------------------------

SHFB: Error BE0043: Unexpected error detected in last build step.  See output above for details.

A: The current version of Sandcastle does not support .NET 4 without some config hackery. There is a new version that should be available quite soon, expected to support .NET 4 out of the box.
Edit: the latest Sandcastle is available now; perhaps that will solve your issue, since it includes .NET 4 support.

A: I had the same problem today, and this post helped me resolve it: http://shfb.codeplex.com/Thread/View.aspx?ThreadId=214594
Solution summary:
Step 1:
Ensure you've got the latest Sandcastle patches, especially for VS2010, available at: sandcastlestyles.codeplex.com. As of today, it is 'Sandcastle May 2008 Patch Rev 3 '.
Step 2:
Add another supportedRuntime element to the 'MRefBuilder.exe.config' file that utilizes the RTM version of .NET 4.0:
<supportedRuntime version="v4.0.30319"/>

I still had the error after step 1, then step 2 finally fixed it.

A: I ran into this same problem with the latest version of the Sandcastle Help File Builder v1.9.1.0 with regards to the Microsoft.VisualStudio.TestTools.UITesting library.
I resolved it by copying the referenced UITest assemblies (buried in the Visual Studio directory) to the directory containing the documentation source.  Then bingo the build worked for the Sandcastle Help File Builder.

A: In my case it was caused by a bad xml comment code item.
   '''
   '''

Error from LastBuild.log:
BuildAssembler : error : CodeBlockComponent: [T:FrozenElephant.Symbiotic.DatabaseTypesFactory] Unable to load source file 'G:\Dev\FrozenElephant\SymbioticORM\SymbioticUniversalTests\UniversalTestProject_CS\ExampleUnitTests\AbstractFactoryTests.cs'.  Error: Could not find file 'G:\Dev\FrozenElephant\SymbioticORM\SymbioticUniversalTests\UniversalTestProject_CS\ExampleUnitTests\AbstractFactoryTests.cs'. [G:\Dev\FrozenElephant\SymbioticORM\Symbiotic.Docs\Help\Working\BuildTopics.proj]


text:
Q: OCR Support with Tesseract via SOLR Good day,
I'm trying to configure SOLR to use Tesseract OCR engine for text extraction from images, but did not have success yet.
SOLR extracting fine text from structured text documents (.xls, .pdf, doc, etc), but it does not want to call Tesseract module for text recognition.
I'm using

*

*SOLR v.7.4.0

*Tesseract version 4.1.1

*TIKA 1.18 version (build-in in SOLR, no standalone version)

Tesseract is installed in to the following directory:
/usr/share/tesseract/4/tessdata/
echo $TESSDATA_PREFIX - > /usr/share/tesseract/4/tessdata/
tesseract -v
tesseract 4.1.1-rc2-20-g01fb
leptonica-1.76.0
  libjpeg 6b (libjpeg-turbo 1.2.90) : libpng 1.5.13 : libtiff 4.0.3 : zlib 1.2.7 : libwebp 0.3.0

Command tesseract test.jpg  test.txt  produces accurate txt file with OCRed content from test.jpg.
solrconfig.xml, TesseractOCRConfig.properties, ParseContent.xml files were modified to point to Tesseract installation.
Has anybody done such configuration ?

A: Good day,
We solved the situation. Here is what was used and changed:
In our installation we used Tesseract  version 3.05, Tika version 1.17, SOLR version 7.4.  We actually, had TIKA version 1.17, not 18.
1. Changed from HOCR to TXT  >>>      in file parseContext.xml
2. Had to start SOLR as a root user.
Version 4.1.1 is not compatible with TIKA 1.17 , so we will upgrade SOLR to version 7.7, TIKA version 1.19 and will try to install Tesseract 4.1.1enter image description here


text:
Q: Front-end Image Upload with Preview - Is this Possible in WP? I created a front-end form and have several image upload fields.  I was able to create a post and have the images attached.  But what I would like to do is have the user see a preview of the image they are about to upload before submitting the Post.
I've read quite a few alternatives, Uploadify, Valums.com http://valums.com/ajax-upload, SWFupload and a few others I can't remember.  But the problem with all of them is that once i implement them in the form, the images are no longer attached to the post, but only uploaded to the server.
Any suggestion or code sample I can use to do this?  I have scoured the net for an answer - perhaps it's just not possible in WP to preview an image and also attach it to a post in one form?

A: Just add this scripts in header

Add for Internet explorer:

Add style to the header.

Note this should be added in header of that page or ur theme
and this will be upload bar
with preview
u can also cancel the preview with this
<input type='file' onchange="readURL(this);" />

 img id="img_prev" src="#" alt="your image" />
 span id="x">[X]


text:
Q: Animated Transitions with andreypopp/react-router-component I'm trying to get this react-router-component to animate the transitions from one route to the next. I'd ideally like each "Location" component to be able to implement componentWillEnter, componentWillLeave, etc... function similar to the way you can with React's Transition Groups. Either by using TransitionGroups or just mimicking the behavior.
Has anyone played with this router like this before, or know of a similar router for React that can do this?
Thanks.


text:
Q: SwiftUI Menu with label an image and a text
As you can see in the image I would like to put the photo inside that drop down menu where it says Paul.
I tried to insert it but I get a strange effect, it happens that the image takes up all the space, you can't see the text anymore.
Can you give me a hand?

import Foundation
import SwiftUI

struct RemoteImage: View {
    private enum LoadState {
        case loading, success, failure
    }

    private class Loader: ObservableObject {
        var data = Data()
        var state = LoadState.loading

        init(url: String) {
            guard let parsedURL = URL(string: url) else {
                fatalError("Invalid URL: \(url)")
            }

            URLSession.shared.dataTask(with: parsedURL) { data, response, error in
                if let data = data, data.count > 0 {
                    self.data = data
                    self.state = .success
                } else {
                    self.state = .failure
                }

                DispatchQueue.main.async {
                    self.objectWillChange.send()
                }
            }.resume()
        }
    }

    @StateObject private var loader: Loader
    var loading: Image
    var failure: Image

    var body: some View {
        selectImage()
            .resizable()
    }

    init(url: String, loading: Image = Image(systemName: "photo"), failure: Image = Image(systemName: "multiply.circle")) {
        _loader = StateObject(wrappedValue: Loader(url: url))
        self.loading = loading
        self.failure = failure
    }

    private func selectImage() -> Image {
        switch loader.state {
        case .loading:
            return loading
        case .failure:
            return failure
        default:
            if let image = NSImage(data: loader.data) {
                return Image(nsImage: image)
            } else {
                return failure
            }
        }
    }
}

struct Test: View {

    var body: some View {
        VStack(alignment: .trailing){
            Menu {
                Button(action: {
                    NSApplication.shared.terminate(self)
                }) {
                    Text("Esci")
                }
            } label: {
                RemoteImage(url: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Leonardo_Dicaprio_Cannes_2019_2.jpg/440px-Leonardo_Dicaprio_Cannes_2019_2.jpg")
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 20, height: 20)
                    .cornerRadius(10)
                Text("Paul")
            }
            .menuStyle(BorderlessButtonMenuStyle())
            .frame(width: 80, height: 16)
            .padding(3)
            .cornerRadius(4)
            .help("Impostazioni")
        }
        .frame(width: 360, height: 360)
    }
}


text:
Q: Answer Set Programming Beginner I am a beginner in Answer Set Programming and completely new to clingo. I tried the facts and constraints below on nurses shift on clingo, but I am not getting any model and clingo not flagging any error. I keep getting UNSAT. What am I not doing right?
nurselimits(x, min, max).
worklimits(min, max).
daylimits(x, t, min, max).
x(morning; afternoon; night; off; leave).
x(1..5).

day(1..28).
days(28).
nurse(1..40).
shift(1, morning, 8).
shift(2, afternoon, 14).
shift(3, night, 20).
shift(4, off, 0).
shift(5, leave, 10).
nurselimits(1,6,9).
nurselimits(2,6,9).
nurselimits(3,4,7).
daylimits(1,8,6,9).
daylimits(2,8,6,9).
daylimits(3,8,5,10).
worklimits(132,228).

 {assign(N, X, D) : shift(X, Name, H), X != 4, X != 5} = 1:- nurse(N), day(D).

:- day(D), #count{N : assign(N, X, D)} > max, nurselimits(x, min, max).
:- day(D), #count{N : assign(N, X, D)} < min, nurselimits(x, min, max).

:- nurse(N), #sum{H, D : assign(N, X, D), shift(X, Name, H)} > max, worklimits(min, max).
:- nurse(N), #sum{H, D : assign(N, X, D), shift(X, Name, H)} < min, worklimits(min, max).

:- nurse(N), assign(N, X1, D), assign(N, X2, D+1), X2 < X1 , X1 <= 3.

:- nurse(N), day(D), days(DAYS), D <= DAYS-21,
   #count{D1 : assign(N, 4, D1), D1 >= D, D1 <= D+21} = 1.

:- nurse(N), #count{D: assign(N, X, D)} > max, daylimits(x, t, min, max).

:- nurse(N), #count{D: assign(N, X, D)} < min, daylimits(x, t, min, max).

A: In this code
nurselimits(x, min, max).
worklimits(min, max).
daylimits(x, t, min, max).
x(morning; afternoon; night; off; leave).
x(1..5).

There are several problems. The symbols x, min, max, t. Are all non-numerical symbolic constants, much like morning, afternoon,etc. That is probably unintended, unless you are substituting them using the -c command line option. Certainly, the x in nurselimits has nothing to do with the x(1..5) in your code, which also seems unintended. Also, the constant min is the same symbolic value in  nurselimits, worklimits and daylimits. Perhaps you wanted it to be variable instead?

A: You should remove first three lines and add #show (e.g. #show assign/3.) of any predicate you want to see in the answer sets.


text:
Q: PowerBi - Set Axis Maximum as a measure I want to be able to set the maximum on my Y axis for a visual based on a calculated measure.
For example, if i have a measure which is max number of steps covered for a group, and i want this to be the maximum on y scale so it remains dynamic to changes.
Is this possible?

A: With the power bi visuals it is not possible to directly use a measure on the axis.
There are a number of workarounds using a calculated column and IF statements to create a column that can be use. SO answer and Power BI Community
One other alternative would be to use a R visual, they are able to take a measure and apply it to an axis


text:
Q: Node js url is working only on private window in React application I have an application built with reactjs with node js backend by using Create React App library.
in Nodejs-server.js I have the following code structure.

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import cors from 'cors';
import visitors from './routes/visitors';
import { cronNotification } from './cron/cron.js';

let app = express();

app.use(bodyParser.json({ limit: '15mb' }))
app.use(cors())

app.use('/api/visitors', visitors)
app.use('/docs/visitorTickets', express.static(path.join(__dirname, '../docs/visitorTickets')));
app.use('/images', express.static(path.join(__dirname, '../assets/images')));

app.use(express.static(path.join(__dirname, '../../build')));
app.get('/*', function (req, res, next) {
 res.sendFile(path.join(__dirname, '../../build', 'index.html'));
});

app.use((req, res) => {
 res.status(404).json({
  errors: {
   global: "Page Not Found."
  }
 })
});

let port  = 8080
app.listen(port, () => console.log('Running on port:'+port));
cronNotification();

In Visitor file I have following code

import express from 'express';
import QRCode from 'qrcode';
import pdf from 'html-pdf';

let router = express.Router();

router.get('/test', (req, res) => {
 res.json({ success: "test success page." })
});

router.get('/pdf', (req, res) => {
 let html = '
test value
';
 pdf.create(html).toStream((err, pdfStream) => {
    if (err) {
      return res.sendStatus(500)
    } else {
      res.statusCode = 200
      pdfStream.on('end', () => {
        return res.end()
      })
      pdfStream.pipe(res)
    }
  });
});

export default router;

This code working perfect with front end react app by using http://localhost:3000/test.
It gets the result via API from axios library from react action page.
In developr tool network -> result shows: success: "test success page."
Now the issues is:
When I access
http://localhost:8080/api/visitors/pdf OR
http://localhost:8080/api/visitors/test
Directly in browser, It shows blank page (directly frot end source is appearing from console)
While access it from private window, It shows the result.
It tried it with diffrent browsers and diffrent computers but issue remain the same.
I am suspecting something wrong in this code

app.use(express.static(path.join(__dirname, '../../build')));
app.get('/*', function (req, res, next) {
 res.sendFile(path.join(__dirname, '../../build', 'index.html'));
});

It is neglecting app.use path (app.use('/api/visitors', visitors))

Kindly help me out why this is working only in private browser?

A: After a long battle, I have fixed that issue by unregister react's registerServiceWorker

import { unregister } from './registerServiceWorker';
unregister();

A: So, why you need to res.sendFile to send an html page ? Let try to use ejs or jade view engine and then :
app.get('/*', function (req, res) {
    return res.render('../path_to_ejs_view_file');
});
Or in your case maybe call next() function can solve problem:
app.get('/*', function (req, res, next) {
res.sendFile(path.join(__dirname, '../../build', 'index.html'));
next();
});

By the way, I have an project like you. Use Nodejs for api and Reacjs for SPA here: https://github.com/dangminhtruong/havana hope it useful


text:
Q: Peer to peer via Wi-Fi? Can I communicate from one WP7 device to another via UDP when one device enables tethering (becomes a wi-fi hotspot) and another one connects to him like to external Wi-fi hot-spot? Is this possible scenario? I just want to create p2p game.

A: To use UDP based socket connections on Windows Phone, all devices must already be connected to the same WiFi network. This means your scenario isn't possible.
See more on Windows Phone Sockets on MSDN at http://msdn.microsoft.com/en-us/library/hh202874(v=vs.92).aspx


text:
Q: Reduce log level in Sonar 2.1.x I have a Maven 3.x build that uses Sonar 2.1.x for quality control. The maven-sonar plugin is used from inside Jenkins to run the Sonar checks.
During the Jenkins build, when Sonar kicks in, it logs A LOT of not so useful information at INFO level:
[INFO] [15:29:14.195] Java version: 1.6
[INFO] [15:29:20.853] Execute PMD 4.3 done: 6658 ms
[INFO] [15:29:20.853] Sensor PmdSensor done: 6658 ms
[INFO] [15:29:20.854] Sensor ProfileSensor...
[INFO] [15:29:21.186] Sensor ProfileSensor done: 332 ms
[INFO] [15:29:21.187] Sensor ProfileEventsSensor...
[INFO] [15:29:21.190] Sensor ProfileEventsSensor done: 3 ms
[INFO] [15:29:21.190] Sensor ProjectLinksSensor...
[INFO] [15:29:21.192] Sensor ProjectLinksSensor done: 2 ms
[INFO] [15:29:21.192] Sensor VersionEventsSensor...
[INFO] [15:29:21.198] Sensor VersionEventsSensor done: 6 ms
[INFO] [15:29:21.198] Sensor Maven dependencies...
[INFO] [15:29:21.261] Sensor Maven dependencies done: 63 ms
...

The log is quite big. I have been trying to find a way to set the log level to WARN with no luck. Any idea?
Thanks!

A: Unfortunately, there's no way to mute this INFO-level log.

A: As discussed here log level can be changed at the maven plugin level.
Run mvn with -Dorg.slf4j.simpleLogger.showLogName=true it will show the logger name with log like below
2022-11-09T05:47:18.8604059Z [INFO] org.sonarsource.scanner.maven.SonarQubeMojo - SCM writing changed lines (done) | time=83ms
2022-11-09T05:47:18.8604819Z [INFO] org.sonarsource.scanner.maven.SonarQubeMojo - Analysis report generated in 287ms, dir size=5.2 MB
2022-11-09T05:47:18.8605606Z [INFO] org.sonarsource.scanner.maven.SonarQubeMojo - Analysis report compressed in 1993ms, zip size=4.1 MB
2022-11-09T05:47:18.8606333Z [INFO] org.sonarsource.scanner.maven.SonarQubeMojo - Analysis report uploaded in 282ms

then on executing mvn with -Dorg.slf4j.simpleLogger.log.org.sonarsource.scanner.maven.SonarQubeMojo=error it will change the log level.


text:
Q: LINQ - dictionary in dictionary I'm just learning how to program, and therefore I didn't really understand LINQ.
I have:
Dictionary<string, Dictionary<string, string>> dirData = new Dictionary<string, Dictionary<string, string>>
{
    {
        "key1", new Dictionary<string, string>
        {
            {"subKey1", "value546" },
            {"subKey2", "value412" },
            {"subKey3", "value100" },
            {"subKey4", "value27" }
        }
    },
    {
        "key2", new Dictionary<string, string>
        {
            {"subKey1", "value27" },
            {"subKey2", "value98" },
            {"subKey3", "value100" }
        }
    },
    {
        "key3", new Dictionary<string, string>
        {
            {"subKey1", "value29" },
            {"subKey2", "value202" },
            {"subKey3", "value22" },
            {"subKey5", "value1" },
            {"subKey6", "value3" }
        }
    }
};

I need to return the Dictionary<string, Dictionary <string, string >> where subkey == "subKey3" with the value value == "value100".
How can this be organized using LINQ?

A: You can use the following code snippet, there are two of them in your sample BTW:
var result = dirData.Values.Where(d => d.ContainsKey("subKey3") && d["subKey3"] == "value100");

Update

I need to return the Dictionary<string, Dictionary <string, string >>
where subkey == "subKey3" with the value value == "value100".

Get Dictionary of Dictionaries:
Dictionary<string,Dictionary<string,string>> result = dirData.Where(d => d.Value.ContainsKey("subKey3") && d.Value["subKey3"] == "value100").ToDictionary(k=>k.Key,v=>v.Value);

A: Something along the lines of
var vals = dirData.Where(x => x.Value.Keys.Contains("subKey1") && x.Value.Values.Contains(("value29")));

should work. I just tested it using vals.Count() and got the number 1 returning.
Also, just as a heads up: there are two missing commas in your sub-dictionaries :)
Edit: I think that the answer by @Access Denied actually is probably better. Just leaving mine as an alternative.

A: Just complicating it a bit, you can also use Linq-object this way
  var test =  from x in dirData
                           where x.Value.Any(m => m.Key == "subKey3" && m.Value == "value100")
                           select x;

A: Here's another way:
List<Dictionary<string, string>> result = dirData.Where(w => w.Value["subKey3"] == "value100").Select(s => s.Value).ToList();

I'm presuming that more than one of the dictionaries can match the condition based on your sample data, therefore this statement returns a list of dictionaries. If you only expect one match you should replace the ToList() with Single()/SingleOrDefault() as appropriate.

A: probably something like
var data = dirData.Where(d => d.Value.Any(x => x.Key == "subKey3" && x.Value == "value100")).ToList();

if you are looking for only those entries where key = "subKey3" and value = "value100" then probably use SelectMany() like
var data = dirData.SelectMany(x => x.Value).Where(x => x.Key == "subKey3" && x.Value == "value100").ToList();


text:
Q: Python: Rescale time-series in pandas by non-integer scale-factor I have no idea if this is feasible in Pandas. I thought df.resample may do the work but no. Here's my objective:
I have a time-series in a DataFrame, df that looks like this:
            return
12:30:00 -0.000202
12:30:01 -0.000257
12:30:02 -0.000230
12:30:03 -0.000229
12:30:04 -0.000253
...
12:59:49  0.001491
12:59:50  0.001523
12:59:51  0.001503
12:59:52  0.001484
12:59:53  0.001513
12:59:54  0.001523
12:59:55  0.001527
12:59:56  0.001545
12:59:57  0.001532
12:59:58  0.001535
12:59:59  0.001566
13:00:00  0.001605

This is the plot:

Now you can you see that the time goes from 12:30:00 to 13:00:00. I want to re-scale or stretch the this time-series to have observations from 12:30:00 to 14:15:00. Hence I need to have 3.5 more entries in my original time-series... so 3.5 times more duplicate entries for each observation in my time-series. If it was only 3 time mores, then I would transform my data into array and use np.reshape() and then re-assign a time index but this won't work in this particular case. Any suggestions?

A: You can convert the datetime to unix epoch, multiply by your scale factor and then convert back (epoch calculation using How to get unix timestamp from numpy.datetime64)
df['epoch'] = df.index.astype(np.int64) // 10 ** 9
start_epoch = df.epoch.iloc[0]
df['epochdelta']= df['epoch'] - start_epoch
df['newindex'] = pd.to_datetime((df.epochdelta * 3.5 + start_epoch),unit='s')


text:
Q: How to calculate 95% confidence intervals using bayesboot() I need help to calculate bootstrap-based credible intervals of the quantity qtt.ci from my regression coef.def.
So far my attempts have resulted in:

Error in quantile.default(s, c(0.025, 0.25, 0.5, 0.75, 0.975)) :
  missing values and NaN's not allowed if 'na.rm' is FALSE

preceded by:

Warning message: In bayesboot(dat, boot_fn) :   The sample from
  bayesboot contains either NAs, NaNs or NULLs. Make sure that your
  statistic function only return actual values.

Here are my sample data:
dat <- data.frame(
  A = c(1, 1, 0, 0), B = c(1, 0, 1, 0),
  Pass = c(278, 100, 153, 79), Fail = c(743, 581, 1232, 1731)

Below is my regression. The quantity I want to get the bootstrap-based 95% credible intervals is qtt.ci:
boot_fn <- function(dat) {
           coef.def = unname(coef(glm(cbind(Pass, Fail) ~ A * B, binomial,
           dat)))
                          }
qtt.ci <- exp(sum(coef.def[2:4])) - exp(coef.def[2]) - exp(coef.def[3]) + 1

Here is my attempt:
bb_ci <- bayesboot(dat, boot_fn)
summary(bb_ci)

Not certain how to get the bootstrap-based confidence intervals for qtt.ci.
Thank you in advance.
EDIT:
Following the answer by @RuiBarradas, I tried doing bootstrap to get the 95% CI for the quantity qtt.ci (which is the quantity for which I want to get the bootstrapped CI), but no success:
library(bayesboot)

boot_fn <- function(dat) {
      coef.def <- unname(coef(glm(cbind(Pass, Fail) ~ A * B, binomial, dat)))
      qtt<- (exp(sum(coef.def[2:4])) - exp(coef.def[2]) - exp(coef.def[3]) + 1)
      if(all(!is.na(qtt))) qtt else NULL
    }

Runs <- 1e2
qtt.ci <- bayesboot(dat, boot_fn, R = Runs, R2 = Runs)
summary(qtt.ci)

Quantiles:
 statistic    q2.5%     q25%   median     q75%   q97.5%
        V1 2.705878 2.705878 2.705878 2.705878 2.705878

Therefore, this does not give the CI for qtt.ci. The output is simply the point estimate for qtt:
qtt<-(exp(sum(coef.def[2:4])) - exp(coef.def[2]) - exp(coef.def[3]) + 1)
qtt
[1] 2.705878

Any help would be much appreciated.

A: The following solves the warning issue. I have tested it with much less runs, instead of 4000 just 100.
library(bayesboot)

boot_fn <- function(dat) {
  fit <- glm(cbind(Pass, Fail) ~ A * B, binomial, dat)
  coef.def <- unname(coef(fit))
  if(all(!is.na(coef.def))) coef.def else NULL
}

Runs <- 1e2
bb_ci <- bayesboot(dat, boot_fn, R = Runs, R2 = Runs)
summary(bb_ci)

Edit.
According to the formula in the question and the dialog in comments with the OP, to get the bootstrap-based CI run:
qtt <- exp(sum(bb_ci[2:4])) - exp(bb_ci[2]) - exp(bb_ci[3]) + 1


text:
Q: wrap xml column values into outer for xml path query I want to wrap the xml from a column into an out for xml path query without
the column name as an element.
declare @tab table (col xml)
insert @tab
select '<element/>'

select  'val' AS "@att" , col
from  @tab
for xml path ('ROOT')

This gives
<ROOT att="val">
  <col>
    <element />
  </col>
</ROOT>

but i want
<ROOT att="val">
    <element />
</ROOT>

All help most appreciated.

A: select
  'val' AS "@att",
  (select col)
from  @tab
for xml path ('ROOT')

A: A little cleaner method.
SELECT
    'val' AS [@att],
    [col] AS [*]
FROM
    @tab
FOR XML PATH ('ROOT');


text:
Q: Video tag won't autoplay in firefox, DOMException I'm using Firefox 62.0.3 on my tablet, it works on one of the tablets but not the other.
On one tablet I am getting an error that says
DOMException: "The fetching process for the media resource was aborted by the user agent at the user's request."
I am not at all sure what this is telling me, does my video need to be within a clickhandler? I thought if autoplay is true and muted is true, i am good to go?
Again it works on the other tablet with the same firefox version.
<video id="asd" class="asd" oncreate={(el) => stream.start(el)}> Sorry, your browser doesn't support embedded videos.</video>
I then do
this.peerConnection.ontrack = (event) => {
        const mediaStream = event.streams[0];
        let remoteVideoElement = document.getElementById('stream');
        remoteVideoElement.autoplay = "true";
        remoteVideoElement.defaultMuted = "true";
        remoteVideoElement.muted = "muted";
        remoteVideoElement.playsinline = "true";

        if ('srcObject' in remoteVideoElement) {
            remoteVideoElement.srcObject = mediaStream;
        } else {
            // Avoid using this in new browsers, as it is going away.
            remoteVideoElement.src = URL.createObjectURL(mediaStream);
        }
        let playPromise = remoteVideoElement.play();

        if (playPromise !== undefined) {
            playPromise.then((_) => {
                // will play video
            }).catch((err) => {
                console.error("playPromise error: ", err);
            })
        } else {
            console.error("playPromise is undefined: ", playPromise);
            remoteVideoElement.load();
        }
    }

It works but when i try to resolve playPromise it gives the DOMException error, and load() does not work either on the tablet that is giving issues.


text:
Q: Edge from a node to itself in Roassal Is there a way to make Roassal draw an edge from one node to itself?
I looked at a bunch of the examples and I cannot find any that does that, and simply adding an edge in the source code produces nothing.
i.e.
view shape rectangle size: 1.
view nodes: (1 to: 5).
view shape arrowedLine.
view
    edges:  ((OrderedCollection new) add: (1->1); add: (2->2); add: (3->3); add: (4->4); add: (5->5); yourself)
    from: #key
    to: #value.
view circleLayout.

produces no edges at all.

A: I'm not sure if Roassal implements that kind of edge.
I tried the same in Roassal2 and although the edge is created it is not showed. It seems that it creates a line where the origin and the end is the same point.
As a workaround you could reuse Bezier lines by specifying a different behaviour for that case:

   RTDirectedLine>>pointsFrom: from To: to
   | point mid |
   from = to
        ifTrue: [
            mid := to * (1 - offset) + (from * offset).
            point := from + (50 @ 50).
            ^ Array with: from - (10 @ 0) with: point with: to - (0 @ 10) ]
        ifFalse: [
            mid := to * (1 - offset) + (from * offset).
            point := from + (mid - from) rightRotated.
            ^ Array with: from with: point with: to ]

Then you can run in a workspace:

| b |
b := RTGraphBuilder new.
b nodes
    size: 20;
    color: Color gray.
b edges
    directed;
    connectTo: #yourself.

b layout circle.
b addAll: (1 to:5).

b open.
b view canvas

You should see this:
http://cdn.imghack.se/images/1aaea2de365d0a16818ec8bcf991348a.png


text:
Q: Certain mathematical equations run on arrays in Ruby return single digits when double digits expected My calculator correctly subtracts and divides, but cannot correctly add or multiply correctly when there is a number that is multi-digit. Whenever I use such a number, it cuts off the last digit of the multi-digit number. For example, 12*2 becomes 2, 10*10 becomes 1, and so on.
Updated to include init method
class Sci_Calc
    def self.init
        puts "Which function of this calculator would you like to use? "
        calc_fun = gets.chomp
        case calc_fun
        when "sub"
            self.sub
        when "add"
            self.add(gets.chomp.split("").map(&:to_i))
        when "mult"
            self.mult(gets.chomp.split("").map(&:to_i))
        when div
            self.div
        end
    end
    def self.sub()
        puts "Please put the number you would like to sub from first. "
        num1 = gets.chomp.to_i
        puts "Second number: "
        num2 = gets.chomp.to_i
        num3 = num1 - num2
        puts num3
        self.init
    end
    #For now, it can only add 1 digit numbers
    def self.add(num_array)
        sum=0;
        sum=num_array.sum
        puts sum
        self.init
    end
    #code taken from https://stackoverflow.com/questions/7050869/ruby-multiply-all-elements-of-an-array
    def self.mult(mult_array)
        #Take each element in the array, and add it together.
        result = 1
        mult_array.each do |i|
            #Ignores zeroes in array.
            if i!=0
                result = result*i
            else
                result
            end
        end
        puts result
    end
    def self.div
        puts "Pick the number you would like to divide from first: "
        div1 = gets.chomp.to_i
        puts "Second number, please: "
        div2 = gets.chomp.to_i
        puts "Result is: "
        div3 = div1/div2
        puts div3
    end
end
Sci_Calc.init

I will gladly put the rest of the code into a pastebin if needed to answer this question.

A: irb> '12 2'.split("")
=> ["1", "2", " ", "2"]

max pleanar pointed in the right direction.
It should be .split(" ")
otherwise you end up working with single digits (and zeros for " ")


text:
Q: trying to get the both card and cash members Hi  I have done like this for getting  members details for  payment method type cash
       SELECT members.member_Id, members.member_Lastname, members.member_Firstname, members.member_PostCode,
            members.member_Reference,  members.member_Dob,30*memberToMship_ChargePerPeriod/DateDiff(memberToMship_EndDate, memberToMship_StartDate) As monthly_amount, mshiptypes.mshipType_Name, mshipstatustypes.mshipStatusType_Name,
            membertomships.memberToMship_EndDate, IF(mshipOption_Period='year', TIMESTAMPDIFF (YEAR,memberToMship_StartDate, memberToMship_EndDate),
            TIMESTAMPDIFF (MONTH ,memberToMship_StartDate,memberToMship_EndDate ) ) *memberToMship_ChargePerPeriod As Total
          FROM members LEFT JOIN membertomships ON membertomships.member_Id = members.member_Id,
          LEFT JOIN mshipstatustypes ON mshipstatustypes.mshipStatusType_Id = membertomships.mshipStatusType_Id,
          LEFT JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id,
          LEFT JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id,
          WHERE membertomships.memberToMship_PayMethod='Cash'
          AND members.member_Active LIKE 'y%'
          AND (mshipstatustypes.mshipStatusType_Id='2'
            OR mshipstatustypes.mshipStatusType_Id = '3'
            OR mshipstatustypes.mshipStatusType_Id='6')"

and another query like this for getting  members details with payment method  type card
                               SELECT members.member_Id, members.member_Lastname, members.member_Firstname, members.member_PostCode,
          members.member_Reference,  members.member_Dob,
          30*memberToMship_ChargePerPeriod/DateDiff(memberToMship_EndDate, memberToMship_StartDate) As monthly_amount,
          mshiptypes.mshipType_Name, mshipstatustypes.mshipStatusType_Name,
          membertomships.memberToMship_EndDate,
          IF(mshipOption_Period='year', TIMESTAMPDIFF (YEAR,memberToMship_StartDate, memberToMship_EndDate),
          TIMESTAMPDIFF (MONTH ,memberToMship_StartDate,memberToMship_EndDate ) ) *memberToMship_ChargePerPeriod As Total
        FROM members LEFT JOIN membertomships ON membertomships.member_Id = members.member_Id
        LEFT JOIN mshipstatustypes ON mshipstatustypes.mshipStatusType_Id = membertomships.mshipStatusType_Id
        LEFT JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id
        LEFT JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id
        WHERE membertomships.memberToMship_PayMethod='Card'
        AND members.member_Active LIKE 'y%'
        AND (mshipstatustypes.mshipStatusType_Id='2' OR  mshipstatustypes.mshipStatusType_Id = '3'
            OR mshipstatustypes.mshipStatusType_Id='6')"

but i want the member details those who have payment methods are  "cash and card" (both type members)
would any one help on this  query...
i am using MySQL
Many Thanks........
Modified Query
                       SELECT members.member_Id, members.member_Lastname, members.member_Firstname, members.member_PostCode,
          members.member_Reference,  members.member_Dob,30*memberToMship_ChargePerPeriod/DateDiff(memberToMship_EndDate, memberToMship_StartDate) As monthly_amount, mshiptypes.mshipType_Name, mshipstatustypes.mshipStatusType_Name,
          membertomships.memberToMship_EndDate,
          IF(mshipOption_Period='year', TIMESTAMPDIFF (YEAR,memberToMship_StartDate, memberToMship_EndDate),
          TIMESTAMPDIFF (MONTH ,memberToMship_StartDate,memberToMship_EndDate ) ) *memberToMship_ChargePerPeriod As Total
        FROM members
         INNER JOIN membertomships ON membertomships.member_Id = members.member_Id
        INNER JOIN mshipstatustypes ON mshipstatustypes.mshipStatusType_Id = membertomships.mshipStatusType_Id
        INNER JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id
        INNER JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id
        WHERE membertomships.memberToMship_PayMethod IN ('Card','Card','Cheque')
        AND members.member_Active LIKE 'y%'
        AND ( mshipstatustypes.mshipStatusType_Id='2' OR  mshipstatustypes.mshipStatusType_Id = '3'
          OR mshipstatustypes.mshipStatusType_Id='6');

but it does not showing correct values..
Hi but one problem I have six Card members and 3 cash members individually it shows 6 and three but when combining(card and cash) it will shows only 4 .but it has to be shown (6+ 3) i dont know how it was like this would yoy pls tell any solution.

A: Assuming the only payment types are cash or card, you can leave out the where clause membertomships.memberToMship_PayMethod='Card'
If there are other payment types, you can change it to
membertomships.memberToMship_PayMethod in ('Card', 'Cash')

A: Use OR or IN
WHERE membertomships.memberToMship_PayMethod IN ('Card','Cash')

WHERE (membertomships.memberToMship_PayMethod ='Card' OR membertomships.memberToMship_PayMethod ='Cash')


text:
Q: How to add a custom array to a polydata in paraview? I know that I can use the Calculator filter for operations on arrays, but I want to perform some more complicated computations. I managed to do it in Paraview python shell, but the missing step now is to go back to the viewer again (or save the new polydata to file).
Here is what I have so far:
polydata = servermanager.Fetch(FindSource("mydataalreadyopeninparaview"))
region_size = paraview.vtk.vtkIntArray()
region_size.SetNumberOfComponents(0)
region_size.SetName("regionsize")
for i in range(polydata .GetNumberOfPoints()):
   region_size.InsertNextValue(somecomputedvalue)
polydata.GetPointData().AddArray(region_size)

How can I "import" in the paraview pipeline my newly created data?

A: Better approach would be use the Programmable Filter to add the array to your input dataset. In ParaView 4.1, the following script can be added to the Script on Properties panel for the Programmager Filter
polydata = output
array = vtk.vtkIntArray()
array.SetNumberOfComponents(0)
array.SetName("regionsize")
for i in range(polydata .GetNumberOfPoints()):
    array.InsertNextValue(somecomputedvalue)
polydata.GetPointData().AddArray(array);

A: The method which works better with the pipeline is using a programmable filter. (related: Paraview Python -- Reverse operation to servermanager.Fetch()? )
For saving the new polydata to file:
(discovered thanks to http://markmail.org/message/4kp7cxl2ani25cak when importing all ctk modules)
from paraview.vtk.vtkIOLegacy import *
writer = vtkPolyDataWriter()
.....

A more "rough" method is to export the data as csv using numpy.savetxt , then reading the csv and apply the TableToPoints filter or Python scripting.
It could be possible to use TrivialProducer and GetClientSideObject  when client and server share the same memory space (with the builtin server) as explained here http://public.kitware.com/pipermail/paraview/2011-February/020120.html , but I haven't tried it


text:
Q: Is there a faster implementation of the following code? I have a one-dimensional numpy array, which is quite large in size. For each entry of the array, I need to produce a linearly spaced sub-array upto that entry value. Here is what I have as an example.
import numpy as np
a = np.array([2, 3])
b = np.array([np.linspace(0, i, 4) for i in a])

In this case there is linear space of size 4. The last statement in the above code involves a for loop which is rather slow if a is very large. Is there a trick to implement this in numpy itself?

A: You can phrase this as an outer product:
In [37]: a = np.arange(100000)

In [38]: %timeit np.array([np.linspace(0, i, 4) for i in a])
1 loop, best of 3: 1.3 s per loop

In [39]: %timeit np.outer(a, np.linspace(0, 1, 4))
1000 loops, best of 3: 1.44 ms per loop

The idea is to a take a unit linspace and then scale it separately by each element of a.
As you can see, this gives ~1000x speed up for n=100000.
For completeness, I'll mention that this code has slightly different roundoff properties than your original version (likely not an issue in practical applications):
In [52]: np.max(np.abs(np.array([np.linspace(0, i, 4) for i in a]) -
    ...:               np.outer(a, np.linspace(0, 1, 4))))
Out[52]: 1.4551915228366852e-11

P. S. An alternative way to express the idea is by using element-wise multiplication with broadcasting (based on a suggestion by @Scott Gigante):
In [55]: %timeit a[:, np.newaxis] * np.linspace(0, 1, 4)
1000 loops, best of 3: 1.48 ms per loop

P. P. S. See the comments below for further ideas on making this faster.


text:
Q: сохранение меток на яндекс картах в json файл. яндекс апи Всем привет. Не получается реализовать сохранение меток которые добавил пользователь на карту в json файл для дальнейшего их вывода и отображения на карте.
ymaps.ready(init);

function init () {
    // Создаем карту.
    var myMap = new ymaps.Map("map", {
            center: [55.751574, 37.573856],
            zoom: 10
        }, {
            searchControlProvider: 'yandex#search'
        });
    // Контекстное меню, позволяющее изменить параметры метки.
    // Вызывается при нажатии правой кнопкой мыши на метке.
    myMap.events.add('click', function (e) {
        // Если меню метки уже отображено, то убираем его.
        if ($('#menu').css('display') == 'block') {
            $('#menu').remove();
        } else {
            // HTML-содержимое контекстного меню.
            var menuContent =
                '
\

\

Номер дома:
 <input type="text" name="icon_text" />
\

Квартира:
 <input type="text" name="hint_text" />
\

Стоимость:
 <input type="text" name="balloon_text" />
\

\

<input type="submit" value="Сохранить" />
\

';

                    var placemark = new ymaps.Placemark(e.get('coords'), {

    }, {
        // Красная иконка, растягивающаяся под содержимое.
        preset: "islands#redStretchyIcon"
    });

            $('body').append(menuContent);

            // Задаем позицию меню.
            $('#menu').css({
                left: e.get('pagePixels')[0],
                top: e.get('pagePixels')[1]
            });

            // При нажатии на кнопку "Сохранить" изменяем свойства метки
            // значениями, введенными в форме контекстного меню.
            $('#menu input[type="submit"]').click(function () {
                placemark.properties.set({
                    balloonContentHeader: $('input[name="icon_text"]').val(),
                    balloonContentFooter: $('input[name="hint_text"]').val(),
                    balloonContentBody: $('input[name="balloon_text"]').val()
                });
            myMap.geoObjects.add(placemark);
                // Удаляем контекстное меню.
                $('#menu').remove();
            });
        }
    });
    myMap.geoObjects.add(placemark);

}


text:
Q: Selective random colors in JavaScript Given the following code to generate random colors (credit):
'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)

What conditions can be added to this code, in order to make it produce only bright colors but darker than pure white #ffffff.
The elements which are assigned these colors, need to be displayed on a dark background (#111).

A: Rather than messing with the bitwise left-shift, it's probably easier to generate each digit separately, like so:
var color = '#';
for (var i = 0; i < 3; i+=1) {
  var first = Math.floor((Math.random()*8+8)).toString(16);
  var second = Math.floor((Math.random()*16)).toString(16);

  color = color + first + second;
}

If you want to adjust exactly how light/dark the colors are, change the Math.random()*8+8 to adjust the first digit in each of the R, G, B values. As it stands, this will generate anything from #808080 to #ffffff. If you wanted from #a0a0a0 to #ffffff, change it *10+6 - it can be anything in the form *x+y so long as x and y add up to 16.


text:
Q: No module named 'kebab' in django devserver I created an app called 'kebab' locally and it all works fine. I've added it to settings.py and url's and it's all good.
However, when we pull our local changes onto the development server, ubuntu returned the "no module named 'kebab'" error. We added it to settings.py on the devserver but still no luck. A little stumped at the moment. Any suggestions?
We're running Ubuntu and an Apache server.
Traceback:
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
   utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named kebab


text: Q: Recursive values and move forward values I have two tables  and table A is having which is matching with B and all the 10 version is matching some codes, some code is changed from version to version. but one of the domain code alue is not available in version 10 and 11 . But automatically the value of 9 should be carried forward to 10 and 11. I am using while condition and CTE recursive it is not giving the result expected


text:
Q: Does $1+\frac{1}{3}-\frac{2}{5}+\frac{1}{7}+\frac{1}{9}-\frac{2}{11}+...$ converge? I'm having a hard time figuring if the following series converges or diverges.
$$
1+\frac{1}{3}-\frac{2}{5}+\frac{1}{7}+\frac{1}{9}-\frac{2}{11}\:+\:...
$$
I think that if I'll place the brackets in the right place I can figure what type of series are laying under. But I can't figure it out. Any help is appreciated!

A: Hint: each group of three terms is of the form
$$\frac{1}{3k-2}+\frac{1}{3k}-\frac{2}{3k+2}=\frac{18k-4}{27k^3-12k}.$$


text:
Q: Mysql: insert a new row in a child table with new values except for foreign key column which is obtained from parent table I'm having this situation. i want to insert a new row into a table which has a foreign key constraint to another table. when i insert a new row, i have new values obtained from user input except for the foreign key column which is to be obtained from the parent table. and the foreign key is an auto_increment primary key in the parent table. here is a the minimized schema to illustrate, only the relevant columns are shown.
CREATE TABLE CUSTOMER (
  CUSTOMER_CODE INTEGER NOT NULL AUTO_INCREMENT,
  FIRST_NAME VARCHAR (20) NOT NULL,
  EMAIL VARCHAR (50) UNIQUE NOT NULL,
      .
  .
  .

  PRIMARY KEY (CUSTOMER_CODE)
);

CREATE TABLE BOOKING (
  BOOKING_CODE INTEGER NOT NULL AUTO_INCREMENT,
  CUSTOMER_CODE INTEGER NOT NULL,
  BOOKING_DATE DATE NOT NULL,
  .
  .
  .

  PRIMARY KEY (RESERVATION_CODE),
  CONSTRAINT BOOKING_CUSTOMER_FK FOREIGN KEY (CUSTOMER_CODE) REFERENCES CUSTOMER
                                                                        (CUSTOMER_CODE)
);

i want to know the insert statement that will feed into the BOOKING table a new row with values generated based on user interaction with the system for the rest of the columns (like booking_date) but obtain the customer_code from the customer table with a where email= clause with an email obtained from user input.

A: To combine 2 statements you can use INSERT ... SELECT like this:
INSERT INTO
    BOOKING
    (CUSTOMER_CODE, BOOKING_DATE)
SELECT
    CUSTOMER_CODE, $booking_date
FROM
    CUSTOMER
WHERE
    CUSTOMER.email=$email

You put your values into SELECT as hard-coded and fetch CUSTOMER_CODE for the appropriate email. But make sure, that you are protected from SQL injection.


text:
Q: image not displaying in rails app I'm having a very confusing problem with my rails app.  I am trying to display an image on a page, and I know the path is correct.  This is verified by "test.html", the entirety of which is:
<img src="/Users/xxxxx/MHE_website/app/assets/images/aggi5.jpg" >

And when I load this page locally I see the picture.  However, the exact same text does not load when I put it into my rails app.  What gives?  I notice that when I am hosting locally for developing, I get the following error message in my terminal:
ActionController::RoutingError (No route matches [GET] "/Users/xxxxx/MHE_website/app/assets/images/aggi5.jpg"):

What does this mean?  I've never had to do this before.  The following is my Gemfile, this may or may not be relevant but I'm at a loss.
source 'https://rubygems.org'

#toggle this on for dev mode
# group :development, :test do
#   gem 'sqlite3'
# end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.4'
# Use sqlite3 as the database for Active Record
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

gem 'owlcarousel-rails', '~> 1.1.3.3'
gem 'bootstrap-sass', '2.3.2.0'

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

group :development, :test do
  gem 'sqlite3'
end

group :production, :staging do
    gem 'pg'
    gem 'rails_12factor'
end
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

A: You need to use image_tag helper to display images in your application. See documentation.
You should use something like this in your view:
<%= image_tag( 'aggi5.jpg' ) %>

A: Try changing the permission of the image to 777. It should work


text:
Q: Need to identify webp images from urls with .jpeg extensions then convert them to true jpg I have a feed of data that contains car dealer's inventory.  For example:
https://pictures.dealer.com/t/troncallisubarusoa/1849/6aa77e5ac38a3b1f7fe87c15fec40550x.jpg?t=20200708
As you can see, the extension is ".jpg", but if you open the image and try to right click -> save... it shows as a ".webp".  This leads me to believe that it's truly a webp and not a jpg.
This fact is messing up an ffmpeg script that I have since it can't handle webp images.  As a result, I'm trying to create a script that will check inventory urls and try to identify urls that are truly a webp link and then download & convert to a jpeg then store the newly created jpeg in the databse.
I've tried using the exif_imagetype() function as well as viewing the wrapper_data of the url, and both come back with jpg.
Is there a way to determine if the image of a url is a webp?


text: Q: How to identify a new topic created in a kafka cluster? I want to identify any new topic created in Kafka cluster. Using zookeeper we can get a list of topics created. But I want to continuously get alerts for new topics created. Also is there a way to solve this using yahoo Kafka manager or LinkedIn burrow?


text:
Q: When using vue.js 2.0, how do you pass an array index to a method inside of a v-on:click? I am trying out vue 2.0 for the first time today. You can see my first attempt at using vue below. I am trying to pass the index of the array into a method. I have tried lots of different ways of doing this but none have been successful. What is the correct way to do this? Thanks!

title: {{entry.title}}

names: {{entry.names}}

index: {{index}}

            <button v-on:click="addName('{{index}}','susan')">Susan</button>

A: You should not use interpolation inside attribute values.
Please, try:
<button v-on:click="addName(index, 'susan')">Susan</button>

You can use the shorthand @ for v-on:
<button @click="addName(index, 'susan')">Susan</button>


text:
Q: Python3.9 pandas save pivotted data frame as a proper csv I have this csv:
Label,Visits,Actions,Maximum actions in one visit,Total time spent by visitors (in seconds),Bounces,Visits with Conversions,Unique visitors (daily sum),Users (daily sum),Metadata: segment,Metadata: referrer_type, cmpgn_group2, cmpgn_group3
Search Engines,4386,5836,15,351989,3547,0,4098,0,referrerType==search,2, name_1, 08-09
Campaigns,2618,3007,20,68609,2385,0,2579,0,referrerType==campaign,6, name_1, 08-09
Direct Entry,2266,3056,21,211456,1833,0,1943,0,referrerType==direct,1, name_1, 08-09
Websites,1097,2002,15,149385,722,0,987,0,referrerType==website,3, name_1, 08-09
Social Networks,691,787,8,18003,623,0,655,0,referrerType==social,7, name_1, 08-09
Search Engines,4045,10889,78,454772,2124,0,3860,0,referrerType==search,2, name_2, 08-09
Direct Entry,1046,3246,111,127677,572,0,943,0,referrerType==direct,1, name_2, 08-09
Websites,139,498,43,21249,61,0,133,0,referrerType==website,3, name_2, 08-09
Social Networks,81,176,16,6667,54,0,77,0,referrerType==social,7, name_2, 08-09
Direct Entry,6752,20806,60,994228,2994,0,5956,0,referrerType==direct,1, name_3, 08-09
Search Engines,3266,14436,50,920652,805,0,2982,0,referrerType==search,2, name_3, 08-09
Websites,250,1413,30,87955,51,0,233,0,referrerType==website,3, name_3, 08-09
Campaigns,27,165,28,8428,3,0,27,0,referrerType==campaign,6, name_3, 08-09
Social Networks,12,31,11,3900,4,0,12,0,referrerType==social,7, name_3, 08-09

What I want to do is to aggregate (sum) the Visits column with Label as columns and  cmpgn_group2 as rows, so the final result would look like this:
cmpgn_group2,Campaigns,Direct Entry,Search Engines,Social Networks,Websites
name_1,2618.0,2266.0,4386.0,691.0,1097.0
name_2,,1046.0,4045.0,81.0,139.0
name_3,27.0,6752.0,3266.0,12.0,250.0

However when I just print my data frame, I get this:
                 Visits
Label         Campaigns Direct Entry Search Engines Social Networks Websites
 cmpgn_group2
 name_1          2618.0       2266.0         4386.0           691.0   1097.0
 name_2             NaN       1046.0         4045.0            81.0    139.0
 name_3            27.0       6752.0         3266.0            12.0    250.0

Which is good inside of my Jupyter notebook for readability, however when I use the to_csv() function, I would like to have a proper csv (looking like the one I showed above), unfortunately what I get is this:
,Visits,Visits,Visits,Visits,Visits
Label,Campaigns,Direct Entry,Search Engines,Social Networks,Websites
 cmpgn_group2,,,,,
 name_1,2618.0,2266.0,4386.0,691.0,1097.0
 name_2,,1046.0,4045.0,81.0,139.0
 name_3,27.0,6752.0,3266.0,12.0,250.0

Which is not a proper csv from my point of view and I cant use it in my workflow.
This is my code:
df = pd.read_csv('channels_26_Oct_2020.csv')
df2 = pd.pivot_table(df, values=['Visits'], columns=['Label'], index=' cmpgn_group2', aggfunc=np.sum)
print(df2)
df2.to_csv('channels_26_Oct_2020_2.csv')

What is the correct approach to this? How can I create a proper csv?
Thank you very much

A: The reason is pivot_table creates multi-index DataFrames. You can collapse them into a single index like this:
df2 = pd.pivot_table(df, values=['Visits'], columns=['Label'], index=' cmpgn_group2', aggfunc=np.sum)
df2.columns = df2.columns.map('_'.join)
df2.to_csv('ex1.csv')

Ouput CSV file:
 cmpgn_group2,Visits_Campaigns,Visits_Direct Entry,Visits_Search Engines,Visits_Social Networks,Visits_Websites
 name_1,2618.0,2266.0,4386.0,691.0,1097.0
 name_2,,1046.0,4045.0,81.0,139.0
 name_3,27.0,6752.0,3266.0,12.0,250.0


text:
Q: PyQt QComboBox setting number of visible items in dropdown I'm working on an application in PyQt that takes an object dictionary and allows you to plot the variables streaming from a robot in real time.  One of the things I'm working on to enable this is a drop down menu.  Unfortunately, we have a couple hundred variables, so my PyQt Combobox pops up from the top of the screen to the bottom with items when clicked.  I'd like to limit the number of items displayed at a time to 20, with the ability to scroll to see the rest.  I've tried using the documented setMaxVisibleItems method, but it doesn't affect the drop down at all.  Any recommendations?
Code here:
#!/usr/bin/env python

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QComboBox, QApplication

from cli.parc2_od import cli_od
import sys

app = QApplication(sys.argv)

items = cli_od.OD.keys() #Items to populate dropdown.
combo = QComboBox()

#The solution:
combo.setStyleSheet("QComboBox { combobox-popup: 0; }")
combo.setMaxVisibleItems(10)

combo.addItems(items)

combo.resize(300, 30)
combo.show()

sys.exit(app.exec_())

A: According to the documentation:

The property maxVisibleItems is ignored for non-editable comboboxes in styles that returns true for `QStyle::SH_ComboBox_Popup such as the Mac style or the Gtk+ Style.

And you can override that SH_ComboBox_Popup style hint with a style sheet:
combo.setStyleSheet("QComboBox { combobox-popup: 0; }");


text:
Q: Running AUCTeX on Windows - problem writing files I love AUCTeX, and use it on an Ubuntu machine all the time. Right now, however, I am stuck with a Windows machine and would like some help getting around a problem. Whenever I try to compile my .tex file with C-c C-c and the file is also open in the viewer, I get the error that "I can't write on abc.pdf".
Of course, I can close the viewer every time I want to compile, but I hope that someone knows how to get around this.

A: If your PDF-viewer is the Adobe Reader (as it often is on Windozs), the Windozs version locks the PDF-file when it is open. Change the viewer to f.ex. Sumatra PDF.


text:
Q: document.elementFromPoint not precise I defined a function in JS:
function getElementIDAtPoint(x,y) {

   console.log("Touch Down ("+x+", "+y+")");

   var id = '';
   var element  = document.elementFromPoint(x,y)

   while(!element.id && element.tagName != 'BODY'){
       element = element.parentElement;
       alert('tagname: ' + element.tagName + ' id: ' + element.id)
   }

   return id;
}

Sometimes i don't get an id, even though the element i clicked on has an id. The elements are small and maybe that's causing the issue. How can i make this more precise? i'm not a js expert


text:
Q: Saving large image to filesystem with emgu CV I am trying to save a large image (2048 x 2048 pixels) from a C# software to the filesystem using the emgu cv library:
var mat = new Mat( pathToFile, ImreadModes.GrayScale );
mat.Save( "imagename.png" );

The second line of the code snippet throws an exception with the message

System.ArgumentException: Parameter is not valid. at
  System.Drawing.Bitmap..ctor(Int32 width, Int32 height, Int32 stride,
  PixelFormat format, IntPtr scan0)

I found out, that the size of the image can be a problem, when the save() function creates a bitmap.
What other possibilites do you suggest, to save the Mat-image onto the filesystem?
Note that I the Image is not already stored in the filesystem as my code snippet implies. I am receiving it from a camera.

A: In fact the problem was not the size of the image. Before saving the image, some strange settings were made to the camera what made all taken pictures unreadable.
Now it works.


text:
Q: Unit Testing a Keycloak-enabled Angular app I'm trying to write a test suite for an Angular app that uses Keycloak for authentication.
However, as Keycloak requires you to manually bootstrap Angular and set up a few interceptors, I'm unable to fire any test due to the following error:
Error: $injector:unpr
Unknown Provider: AuthProvider <- Auth <- authInterceptor <- $http <- $templateRequest <- $route

This is the code for the interceptor that raises the error:
angular.module('MPMReportGenerator')
  .factory('authInterceptor', function authInterceptor ($q, Auth, $log) {
    return {
      request: function (config) {
        var deferred = $q.defer()
        Auth.updateToken(5).success(function () {
          config.headers = config.headers || {}
          config.headers.Authorization = 'Bearer ' + Auth.token
          deferred.resolve(config)
        }).error(function () {
          deferred.reject('Failed to refresh token')
        })
        $log.info(deferred.promise)
        return deferred.promise
      }
    }
  })

My thinking is that I should mock the interceptor and just have it return the request.
However, I fail to see how I could do that, since this interceptor is never injected anywhere as a dependency, it's simply declared with the block above and that's it. My understanding of mocked services is that they need to be injected somewhere to be mocked.
My implementation of Keycloak into Angular comes straight from their examples, if that helps.
Edit
I've been trying to inject a mocked Auth module into the service I'm writing a test for, but still no change.
I'm very new to unit testing in general, so I'm a bit lost trying to track this down. I feel like I know where the issue is, but not how to solve it (The Auth service is added during the bootstrap of the app, I need to mock it for things to work, but it seems I don't know how/where to mock it properly)
Here's the whole testing code:
describe('Services', function () {
  'use strict'

  beforeEach(module('MPMReportGenerator'))

  module(function ($provide) {
    $provide.factory('Auth', function () {
      return null
    })
  })

  var sectionService, $httpBackend, mockAuth
  beforeEach(inject(function (_sectionService_, _$httpBackend_, Auth) {
    sectionService = _sectionService_
    $httpBackend = _$httpBackend_
    mockAuth = Auth
  }))

  it('should get sections', function () {
    $httpBackend.expect('GET', '/MPMReportGenerator/api/categories/all').respond(200)

    sectionService.getSections()

    expect($httpBackend.flush).not.toThrow()
  })
})

Edit 2
I've managed to get past my initial error by making a mock version of Auth.
I am now facing issues implementing a mock version of Keycloak's Javascript library.
My current mock code is as follow:
beforeEach(module(function ($provide) {
    $provide.factory('Auth', function ($q) {
      return {
        updateToken: function (minValidity) {
          return {
            success: function (fn) {
              var deferred = $q.defer()
              deferred.resolve('')
              fn(deferred.promise)
            },
            error: function (fn) {
              var deferred = $q.defer()
              deferred.resolve('Error')
              fn(deferred.promise)
            }
          }
        },
        token: 'thisisafaketokenfortesting'
      }
    })
  }))

And throws this error:
Expected function not to throw, but it threw TypeError: undefined is not an object (near '...}).error(function () {...').
    target/MPMReportGenerator-1.0.0/js/app.service.spec.js:42:43
    loaded@http://localhost:9876/context.js:151:17

My actual test is this:
  it('should get sections', function () {
    $httpBackend.expect('GET', '/MPMReportGenerator/api/categories/all').respond(200)
    sectionService.getSections()
    expect($httpBackend.flush).not.toThrow()
  })

A: I finally figured it out.
Here is the needed code if anyone wants to test an Angular app with keycloak:
beforeEach(
  module(function ($provide) {
    $provide.factory('Auth', function ($q) {
      return {
        updateToken: function (minValidity) {
          return {
            success: function () {
              return {
                error: function () {
                  var deferred = $q.defer()
                  return deferred.promise
                }
              }
            }
          }
        },
      token: 'thisisafaketokenfortesting'
    }
  })
}))

Note that you will likely need to mock other parts of the keycloak library if you intend to test the interceptors provided in the official examples.
Edit
Don't use the code above, the following works much better:
$provide.factory('Auth', function () {
  return {
    updateToken: function (minValidity) {
      return {
        success: function () {
          return this
        },
        error: function () {
          return this
        }
      }
    },
    token: 'thisisafaketokenfortesting'
  }
})


text:
Q: Posted data contains only null values in asp.net mvc 4 the problem is whenever i try to save the data using the view. I always get null data. Please help. My codes for controller, models and view are as follows. Thanks.
public class OverallData
{
    public List<UserInfo> userInfo = new List<UserInfo>();
    public UserActivity userActivity = new UserActivity ();
}

public class UserInfo
{
    public int UserID { get; set; }
    public action UserName { get; set; }
    public action UserPassword { get; set; }

}

public class UserActivity
{
     public int ActivityID{ get; set; }
     public string ActionPerformed { get; set; }
}

View
@model BusinessProcess.Models.OverallData

List of Usernames

@foreach (var item in Model.userInfo)
{
    @Html.DisplayFor(modelItem => item.UserName)
}

Enter some action Performed

@using (Html.BeginForm("EditUserActivity", "ManageUser", FormMethod.Post, new { id = "EditUserActivity" }))
{
@Html.ValidationSummary()

    @Html.DisplayNameFor(model => model.userActivity.ActionPerformed)
    @Html.EditorFor(model => model.userActivity.ActionPerformed)

    <button type="submit">Save</button>
}

Controller
[HttpPost]
public string EditUserActivity(UserActivity tempUserActivity)
{
    string postedValue = tempUserActivity.ActionPerformed;
    //When i debug this the "postedValue" is null
}

A: I think your controller method EditUserActivity() should be expecting a parameter of type OverallData instead of UserActivity based on the model used in the view which may explain why ActionPerformed is null.

A: Your model is of type BusinessProcess.Models.OverallData so your action is expecting that type. I'd say you should change your action method to
[HttpPost]
public string EditUserActivity(OverallData overallData )
{
    string postedValue = overallData.userActivity.ActionPerformed;
}

A: The model binder is set to be using OverallData.
This is because of name of the input elements in your view.The model binder uses the names of the form elements to bind them to the class you're passing into the controller.
@Html.EditorFor(model => model.userActivity.ActionPerformed)

This will be generated with the name userActivity.ActionPerformed, so the model binding will look to assign it to userActivity.ActionPerformed, instead of just to ActionPerformed. Since OverallData doesn't have userActivity.ActionPerformed, that value doesn't get assigned to anything.
If you just pass in OverallData as your parameter, it'll work.
Edit:
Change your view model to look like this:
public class OverallData
{
    public OverallData()
    {
        userActivity = new UserActivity();
        userInfo = new List<UserInfo>();
    }
    public List<UserInfo> userInfo { get; set; }
    public UserActivity userActivity { get; set; }

}

A: just try
  [HttpPost]
  public string EditUserActivity(OverallData tempUserActivity)
   {
     string postedValue = tempUserActivity.userActivity.ActionPerformed;

   }


text:
Q: NTLM authentication in WCF calling .net core API I have a WCF service (A) that calls another WCF service (B) with the below configuration.
<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm" proxyCredentialType="None" realm="" />
  <message clientCredentialType="UserName" algorithmSuite="Default" />
</security>

I'm working on calling service B from a .net core (v2.2) service. I have the below setup:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
basicHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Ntlm;
basicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

// doesn't have Default as the option. Only TripleDes
//basicHttpBinding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.TripleDes
basicHttpBinding.MaxReceivedMessageSize = int.MaxValue;
basicHttpBinding.ReceiveTimeout = new TimeSpan(250000000000);//Timespan in nanoseconds.

EndpointAddress endpointAddress = new EndpointAddress("http://");

customerServiceClient = new CustomerServiceClient(basicHttpBinding, endpointAddress);
NetworkCredential networkCredential = new NetworkCredential("user", "password", "domain");
customerServiceClient.ClientCredentials.Windows.ClientCredential = networkCredential;
customerServiceClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

I'm getting the error: Authentication failed because the connection could not be reused. Below is the partial stack of the exception:
{"Message":"Authentication failed because the connection could not be reused.","Data":{},"InnerException":{"Message":"Authentication failed because the connection could not be reused.","Data":{},"InnerException":null,"StackTrace":"   at System.Net.Http.HttpConnection.DrainResponseAsync(HttpResponseMessage response)\r\n   at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)\r\n   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n   at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)\r\n   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n   at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n...

Please let me know how to get this fixed. Also, this API will be deployed into PCF.
Thanks,
Arun

A: At present, NetCore doesn't support message security mode. Thereby the below statement won't work.
basicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

But the NetCore2.2 supports the WCF service with TransportCredentialOnly security mode.
Here is an example of invocating the service.
 ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
        NetworkCredential nc = new NetworkCredential("administrator", "abcd1234!");
        client.ClientCredentials.Windows.ClientCredential = nc;
        var result = client.TestAsync().Result;
        Console.WriteLine(result);

After we add connected service reference, the binding settings and endpoints have already configured in the Reference.cs file.
We just need to modify the default service endpoint address.

Then we configure the Windows credential on the client-side. On my side, it works.
Please make sure your client project based on AspNet Core2.2
Besides, please refer to the discussion in the official Github repository. It might be useful to you.
https://github.com/dotnet/wcf/issues/2923
Feel free to let me know if there is anything I can help with.


text:
Q: Change backcolor on selected menu item asp.net masterpage I have a menu in a MasterPage constructed of unordered list. I am trying to use javascript to change selected tab color. It works fine if i have href="#" in the anchor tags, but if I put an actual link to another page then the color tab reverts back to the home page. I change the listitem id to onlink when selected.
I have been searching for couple days with dead end answers. Is there a clean solution for this?
How does stackoverflow accomplish this in their menu?
[Questions] [Tags] [Users] [Badges] [Unanswered]
Html for menu

Home

View

About

Contact

Javascript

Css for the selected tab
...stuff

#navbar ul li a#onlink
{
   background: #FFF;
   color: #465c71;
}
#navbar ul li a#onlink:hover
{
   background: #FFF;
   color: #465c71;

...more stuff

A: You need to set the selected link when you actually move to that page. Try something like this.
$(function(){
    var url=document.location.href;
    $("div#navbar ul#menulist li a").each(function(){
            var t=$(this).attr("href");
            if(t && url.indexOf(t)>0){
                $(this).addClass("onlink");
            }
    });
});

please check if the navbar and menulist are the IDs of rendered elements. Otherwise you either need to use 'ClientIdMode="Static"' on div and ul or use '<%= navbar.ClientID%>' to get id. see the working example  here: jsfiddle
Also you need to make slight change to your CSS, instead of:
 #navbar ul li a#onlink

please use:
 #navbar ul li a.onlink


text:
Q: Serialize a hierarchical structure of objects in java I have an abstract class Screen and child classes: GameScreen, SpellScreen, StatsScreen, etc.
The game works in this way: a Renderer class creates a root
    Screen screenRoot = new GameScreen()

which then is free to add screens to itself, which then may add screens to themselves and so it goes. Therefore a tree-like structure is formed, every Screen containing a list of its child-screens.
Now I am wondering if it's possible to perform serialization and deserialization on that - I'd like to recreate all the screens in the same hierarchy.
Is it enough to serialize only the screenRoot object, and then deserialize it (provided I want to preserve the whole screens tree), or do I need to traverse the tree myself somehow?
How would you go about serializing this?
P.S. the game is for Android and uses OpenGL ES 2.0.

A: A hierarchy of objects is no impediment to using Java Serialization, as the latter can cope with arbitrary object graphs - and yes, serializing an object using Java Serialization will serialize all objects it refers to (unless that reference is marked transient). Assuming that's what you want, serializing the hierarchy is as simple as:
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filename)))) {
   oos.write(rootScreen);
}

and reading as simple as:
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filename)))) {
    return (GameScreen) ois.readObject();
}

A: There are two issues here.
First, screens should be just that--screens. They shouldn't contain the "model" or object data that represents your game state; only the view/rendering of that state. So serializing and deserializing, doesn't really make sense. I would suggest looking at your architecture again to see if this is really what you want to do.
If you decide to do it, or if you have another game-state object root that you can serialize (I usually use the Player since it has all the essential data in it), you can easily do this with Gson:
// Save
RootObject o = ...; // The root of the hierarchy to serialize
Gson gson = new Gson();
String serialized - gson.toJson(o); // JSON object, eg. { "Player": { ... } }

// Load
RootObject deserialized = gson.fromJson(serialized, RootObject.class);

You can read more in their user guide.
Second, on the issue of JSON and Gson: I prefer this over standard serialization, because it's robust in the face of changes. If your class definitions change, you can still deserialize objects (albeit you get null/empty fields) instead of a runtime exception; you don't need to worry about versioning your classes, either.
Edit: questions like this are better suited to the Game Dev SE site.