text:
Q: Error not raising from BULK INSERT IN try block hi i have written the below code inside a try block but does not raising error to catch block . but stand alone bulk insert generating error messages.
BEGIN TRY

SET @sql =
                '
                    BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium--<-- table view
                    FROM ''' + @SourceFilePath + '''
                    WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'' );
                '

EXECUTE (@sql)

END TRY
BEGIN CATCH

        SELECT
            @error_number = ERROR_NUMBER(),
            @error_message = ERROR_MESSAGE(),
            @error_line = ERROR_LINE()
        SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.'

END CATCH

A: You are not raising an error in the CATCH block, only assigning a variable value. Try adding RAISERROR:
BEGIN TRY
    SET @sql = ' BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium --<-- table view
FROM ''' + @SourceFilePath + ''' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'', MAXERRORS = 0 );'
    EXECUTE (@sql);
END TRY BEGIN CATCH
    SELECT
        @error_number = ERROR_NUMBER(),
        @error_message = ERROR_MESSAGE(),
        @error_line = ERROR_LINE();
    SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.';
    RAISERROR(@error_description, 16, 1);
END CATCH;

In SQL Server 2012 and later, the CATCH block can be simplified using THROW:
BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;

EDIT:
As suggested in the comments, a non-zero MAXERRORS specification is useful in situations where some records in the source cannot be parsed and may be skipped. The default is 10 if not specified.


text:
Q: How to activate touch pad in Ubuntu 16.04 Could anybody suggest me how to activate touch pad  in Ubuntu 16.04

A: You can go to Settings -> Mouse & Touchpad then click the toggle button with an external mouse.
See screenshot below:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my zip file not showing any contents? I've created a zip file method in my web api which returns a zip file to the front end (Angular / typescript) that should download a zip file in the browser. The issue I have is the file shows it has data by the number of kbs it has but on trying to extract the files it says it's empty. From a bit of research this is most likely down to the file being corrupt, but I want to know where I can find this is going wrong. Here's my code:
WebApi:
I won't show the controller as it basically just takes the inputs and passes them to the method. The DownloadFileResults passed in basically have a byte[] in the File property.
    public FileContentResult CreateZipFile(IEnumerable<DownloadFileResult> files)
    {
        using (var compressedFileStream = new MemoryStream())
        {
            using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update))
            {
                foreach (var file in files)
                {
                    var zipEntry = zipArchive.CreateEntry(file.FileName);
                    using (var entryStream = zipEntry.Open())
                    {
                        entryStream.Write(file.File, 0, file.File.Length);
                    }
                }
            }

            return new FileContentResult(compressedFileStream.ToArray(), "application/zip");
        }
    }

This appears to work in that it generates a result with data. Here's my front end code:
let fileData = this._filePaths;
this._fileStorageProxy.downloadFile(Object.entries(fileData).map(([key, val]) => val), this._pId).subscribe(result => {
            let data = result.data.fileContents;
            const blob = new Blob([data], {
                type: 'application/zip'
            });
            const url = window.URL.createObjectURL(blob);
            window.open(url);
        });

The front end code then displays me a zip file being downloaded, which as I say appears to have data due to it's size, but I can't extract it.
Update
I tried writing the compressedFileStream to a file on my local and I can see that it creates a zip file and I can extract the files within it. This leads me to believe it's something wrong with the front end, or at least with what the front end code is receiving.
2nd Update
Ok, turns out this is specific to how we do things here. The request goes through platform, but for downloads it can only handle a BinaryTransferObject and I needed to hit a different end point. So with a tweak to no longer returning a FileContentResult and hitting the right end point and making the url simply an ahref it's now working.


text:
Q: Sending data between classes in separate files I'm a new programmer and I'm trying to figure out how to send data between classes in separate files.  My goal is to take input from the user, and send it to another class.  The class then takes the int input to create and set the size of an array.  This is what I have:
Main class:
int size = input.nextInt();

    Thing thing = new Thing(size);

Second class:
public class Thing {

public static int[] Thing(int size) {
    int[] thing;
    thing = new int[size];

}

I would like to be able to have a useable array of size size, but I'm not sure about what I need to tackle this.  I appreciate any help you can give.

A: Looking at your code, I'm not sure if you are going for a static implementation, or an object implementation. Here are both ways to approach it. Personally, I'd recommend the object approach.
You pretty much did it already. If you want a static method, I would suggest changing the name of your method and doing something like so:
public static int[] createThing(int size) {
    int[] thing;
    thing = new int[size];
    return thing;
}

Then you would call it like:
int[] Thing = Thing.createThing(size);

If you are trying to do this as an object, you need to create a constructor, which will return a thing object, but you'll need change your Thing class to:
public class Thing {
int[] thingArray;

 public Thing(int size) {
    this.thingArray = new int[size];
 }
 public int[] getThingArray(){
    return this.thingArray;
 }
}

then you would call:
Thing thing = new Thing(size);

to create a new Thing object, and to get the array from the object you do:
thing.getThingArray();


text:
Q: Django + Postgres: saving PDF file with NUL (0x00) characters to DB and decoding it back to PDF I have a pdf file that I want to save in my Postgres DB

When I tried to save the file it brings A string literal cannot contain NUL (0x00) characters. so I followed the solution from here which replaces the null with a � character
unicode(ppbData[0], errors='ignore').replace("\x00", "\uFFFD")

The problem is that I can't convert it back to PDF now. I tried encode() and other methods

file = open('new.pdf', 'wb')
file.write(text.encode())
file.close()

but it returns blank pdf
Is there any way to replaces the � character with a null or any other way to convert it back to normal pdf? Maybe the first solution with replacing also wasn't right and there is another way?

A: The Django model class has a FileField which stores the filename in the database.
https://docs.djangoproject.com/en/3.2/topics/files/#using-files-in-models
The actual file contents are stored via settings.DEFAULT_FILE_STORAGE, which is normally on the filesystem.
https://docs.djangoproject.com/en/3.2/topics/files/#file-storage
However, cloud storage can also be used:

*

*https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html

*https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html
If you really want to store the file in the database, you can either base64 encode it (as Ross Rogers mentioned) or you can use a BinaryField.


text:
Q: Show and Hide Navigation and Tab Bar in Swift 2.3 I am developing a iOS application having tabBar navigation. My requirement is that first time the app starts I need to play a video which should show on top of the tabbar and the navigation bar. To do this I did -
self.tabBarController!.tabBar.hidden = true
self.navigationController!.navigationBar.hidden = true

But if I hide the tabBar and navigation Bar, the elements in my View which shows after the video is played get stretched. Can some one give me a better solution to this. XCode 8.0, Swift 2.3
Thanks.

A: Try to set,
 self.extendedLayoutIncludesOpaqueBars=true;

You can set it from interface builder also - select your view controller - attribute inspector - under view controller - Check Under opaque bars(under extend edges)


text:
Q: how test returned object from a mocked dependency that accepts two arguments inside the mocked object? I couldn't find any post related to my problem. I'm using Mockito and I want to test the behavior inside a controller. I think the core of the problem is that I'm not using Mockito correctly when I send in two arguments to the mocked interface. It works fine if I only send in one argument. I don't think the fact that I'm also using Spring mock mvc has anything to do with this.
I have an interface MyService:
public MyObject doSomeDoggyStuff(long id, SomeOtherObject soo);

The purpose of the interface is to do things and return MyObject if it was successful. If it can't find the object then just return null.
I have a controller MyController:
@RestController
@RequestMapping(value = "/dogs")
public MyController
<snip>

 @RequestMapping(method = RequestMethod.POST, value = "/{id}/toys/{toy}")
  ResponseEntity<MyObject> doDoggyStuff(@PathVariable Long id, @RequestBody Toy toy) {
    MyObject result = this.myService.doSomeDoggyStuff(id, toy);
    if(result == null) {
       return new ResponseEntity("errorinfo", HttpStatus.NOT_FOUND);
     }
    else {
      return new ResponseEntity<MyObject>(result,HttpStatus.CREATED)'
     }
  }

My test class looks like this:
Public MyControllerTest <snip>

  @Mock
  private MyService myServiceMock;

  @InjectMocks
  private MyController myController;

The relevant logic of test method looks this.
MyObject myObj = new MyObject();
Toy toy = new Toy();

when(myServiceMock.doSomeDoggyStuff(1, toy)).thenReturn(myObj);
mockMvc
    .perform(
        post("/dogs/{id}/toys/{toys}", 1, toy).contentType(
            TestUtil.APPLICATION_JSON_UTF8).content(
            TestUtil.convertObjectToJsonBytes(toy))).andExpect(status().isCreated())
    .andReturn();

The problem I'm having is that I expect in this scenario that when it tests MyController that on the line: MyObject result = this.myService.doSomeDoggyStuff(id, toy);
result should be the myObj I set up in the thenReturn but it's always set to null. I have other methods in my service that just accepts one argument and it works fine. I can't grasp what I need to do differently when I send in two arguments using Mockito.

A: If I understand your requirements correctly you should use the mock like this:
when(myServiceMock.doSomeDoggyStuff(eq(1), any(Toy.class))).thenReturn(myObj);
The way you have written your code, the mock will return myObj only when called with the Toy object which you instantiated it with, which is never since Spring will instantiate the class on it's own. The problem doesn't have anything to do with the number of arguments.
If however you want to test for a specific Toy and not just any instance of it, you will need to add an equals (and to be correct with the spec, a hashCode) method so mockito can match the Toys. In the absence of any equals method, the references are checked and of couse those are not equals because the instances are not the same.

A: You need to either implement equals in your Toy or use ArgumentCaptor to check details of the object passed. Otherwise (like geoand already managed to mention) you compare the references.


text:
Q: How is Partitioning done in Hazelcast I am using Hazelcast v2.5. I have a few doubts related to partitioning in a cluster.

*

*How are the partitions identified ?

*When a m.get request is made how does Hazelcast identify in which partition the data resides? (
apart from the key )

*How is partitioning done when a new member joins the cluster?

*Can I get the entries in a partition if partition-ID is entered?

A: Hazelcast has a book that covers questions like yours.
Partitions are inner technique for providing fault-tolerance. You can set partitions count (271 by default).
As a client, you can work with more user-friendly objects, like Collections\Queues..
For maps, you can control backup-count and should hazelcast read from backups.
I guess you can manage partitions using PartitionManager


text:
Q: Cómo generar una lista de elementos basado en un array de objetos por clave ¿Cómo puedo generar una nueva lista (array) cuyos elementos sean el valor de un indice específico?
Ejemplo, tengo este array:
listas = [
{
    "PRF_NOMBRE_PREDIO": "INVERSIONES MINDALA 2012",
    "PRF_CIUDAD": "No Registra",
    "PRF_DEPARTAMENTO": "No Registra",
    "PRF_VEREDA": "No Registra"
},
{
    "PRF_NOMBRE_PREDIO": "PLANTACION LOTE 2013",
    "PRF_CIUDAD": "No Registra",
    "PRF_DEPARTAMENTO": "No Registra",
    "PRF_VEREDA": "No Registra"
},
{
    "PRF_NOMBRE_PREDIO": "La Caimanera",
    "PRF_CIUDAD": "No Registra",
    "PRF_DEPARTAMENTO": "No Registra",
    "PRF_VEREDA": "No Registra"
}]

¿Es posible filtrar solo los valores que pertenezcan al índice PRF_NOMBRE_PREDIO sin la necesidad de usar for?
Este es el resultado que busco:
nuevaLista = [
    "INVERSIONES MINDALA 2012",
    "PLANTACION LOTE 2013",
    "PLANTACION LOTE 2013"
]

A: Como te lo indicaron en los comentarios, lo puedes lograr con un map.
La función map retorna una nueva lista con los valores que resuelven en true en la condición. En este caso la condición es que retorne el valor del key obj['PRF_NOMBRE_PREDIO'], si ese key no existen en un objeto se retorna null.
let result = listas.map(obj => obj['PRF_NOMBRE_PREDIO'])

console.log(result) // ["INVERSIONES MINDALA 2012","PLANTACION LOTE 2013","PLANTACION LOTE 2013"]


text:
Q: Dynamic Mutidimensional array value Count using php I am trying to count the array value in the multidimensional array for the following Array value.
$allMultiGridRes = Array
(
    [0] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                )
        )
    [1] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
        )
    [2] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
        )
)

I am expecting the following output.
Array
(
    [1] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 3
        )
    [2] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 2
        )
)

I have tried the following method using the for loop but I cannot able to achieve the above output like above.
$allMultiGridRes =array();
$paramCheck =array();
foreach ($allMultiGridRes as $gMKey => $GMvalue){
    if(!empty($GMvalue)){
        foreach ($GMvalue as $gMKey2 => $gMValue2){
            if(!empty($gMValue2)){
                $allGridCount[$gMKey2] = array_count_values($gMValue2);
                foreach ($gMValue2 as $gMKey3 => $gMValue3){
                    $paramCheck = !empty($allGridCount[$gMKey2])?$allGridCount[$gMKey2]:array();
                    $GMindex1 = $gMValue3;
                    $allGridCount[$gMKey2][$GMindex1] = array_key_exists($GMindex1,$paramCheck) ? $allGridCount[$gMKey2][$GMindex1]++ : 1;
                    }
                }
            }
        }
    }
}

Using this method I am getting the following output but value are not counting as expected.
Array
(
    [1] => Array
        (
            [grid multi col1] => 1
            [grid multi col2] => 1
        )
    [2] => Array
        (
            [grid multi col1] => 1
            [grid multi col2] => 1
        )
)

I am open to suggestions also I have tried a lot of methods but still I cannot achieve it. I am stuck here for long time
Thanks in advance.

A: You can use array_reduce and foreach
$allMultiGridRes = ;//Your array

$result = array_reduce($allMultiGridRes, function($c, $v){
    foreach ( $v as $key => $value ) {
        if ( !isset( $c[$key] ) ) $c[$key] = array();

        foreach( $value as $o ) {
            if ( !isset( $c[$key][$o] ) ) $c[$key][$o] = 0;
            $c[$key][$o]++;
        }
    }
    return $c;
},array());

print_r( $result );

This will result to:
Array
(
    [1] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 3
        )

    [2] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 2
        )

)

A: You need to use second foreach() iteration key to distinguishing records as well as for proper addition
$allGridCount = [];
foreach ($allMultigridRes as $gMKey => $GMvalue){
    if(!empty($GMvalue)){
        foreach ($GMvalue as $gMKey2 => $gMValue2){
            if(!empty($gMValue2)){
                foreach ($gMValue2 as $gMKey3 => $gMValue3){
                    $allGridCount[$gMKey2][$gMKey3][$gMValue3] = (isset($allGridCount[$gMKey2][$gMKey3][$gMValue3])) ? $allGridCount[$gMKey2][$gMKey3][$gMValue3]+1 : 1;
                }
            }
        }
    }
}
echo "<pre/>";print_r($allGridCount);

Output:-https://eval.in/1004977
Note:-  Instead of !empty() use is_array() && count() to check that it's an array and have some value in it to iterate furhter
$allGridCount = [];
foreach ($allMultigridRes as $GMvalue){
    if(is_array($GMvalue) && count($GMvalue) >0){
        foreach ($GMvalue as $gMKey2 => $gMValue2){
            if(is_array($gMValue2) && count($gMValue2) >0){
                foreach ($gMValue2 as $gMKey3 => $gMValue3){
                    $allGridCount[$gMKey2][$gMKey3][$gMValue3] = (isset($allGridCount[$gMKey2][$gMKey3][$gMValue3])) ? $allGridCount[$gMKey2][$gMKey3][$gMValue3]+1 : 1;
                }
            }
        }
    }
}
echo "<pre/>";print_r($allGridCount);


text:
Q: jQuery post error on Android 2.3.x (working on Android v4.x) I'm writing my first Android app with PhoneGap 2.5; the app is straight simple, just read local gps coordinates and send them to a remote server along with some device data (uuid, android version) and some input fields.
when the app start it sends a sort of "device registration" to remote server and receives back some data
As of now i'm only using jquery v1.9.1, no jquery mobile nor other javascript libraries.
Here's the code
onDeviceReady: function() {
    $.support.cors = true;
    app.deviceRegister();
    // navigator.splashscreen.hide();
},

deviceRegister: function() {
    var params = {
        'device_uuid': window.device.uuid,
        'device_platform': window.device.platform,
        'device_model': window.device.model,
        'device_version': window.device.version,
    };
    var url = app.data.url + 'devices/register'; // app.data.url defined elsewhere
    $.ajax(url, {
        type: "POST",
        data: params,
        timeout: 5000,
        success: function(response) {
            // updates html with received data
            $("#user_badge").html(response.badge);
            $("#user_name").html(response.full_name);
        },
        error: function(x, t, m) {
            if (t === 'timeout') {
                navigator.notification.alert('timeout error');
            } else {
                navigator.notification.alert('error: ' + t);
            }
        },
        dataType: 'json'
    });
},

When applied to Android v4.x (both emulator and real device) it works perfectly, data is sent to remote server and response is correctly managed.
The problem is if i run the app on Android v2.3.x (both emulator and real devices): no data is sent and all i get is an alert with "error: error".
I assume there's something worng between android 2.3 and jquery 1.9, but i just can't get where the problem is.
Any guess?

A: your params object has an extra , at the end.

A: I'm betting app.data.url is a secure URL (https). I had the same issue and had to write an exception for Android versions below 4 to use a normal, non-secured, http connection. Never found an answer on why it wouldn't work tho.


text:
Q: How to reset jsDOM functions which has been overwritten I am overwriting jsdom localstorage API like this in jest, so as to test my try catch code.
    Storage.prototype.setItem = jest.fn(() => {
        throw new Error("error");
    });

How do  reset its implementation ?
I am presently doing this. Is there a cleaner way to do this ?
    const setImplementation = Storage.prototype.setItem;
    Storage.prototype.setItem = jest.fn(() => {
        throw new Error("error");
    });
    expect(() => {
        localStorageHelper.setData(key, value);
    }).not.toThrow();
    Storage.prototype.setItem = setImplementation;
    done();

A: Object methods should never be mocked by assigning, exactly because they cannot be restored this way. Restoring them manually is reinventing the wheel because this can be handled by Jest:
jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
    throw new Error("error");
});

A mock like this one should be used with jest.restoreAllMocks() or restoreMock configuration option to be consistently restored without a risk to affect other tests.


text:
Q: Web crawler crashes after collecting 2 pages of data I am scraping a website that cells iPhone cases.
The web scraper should collect the name of the product and the price. When I run the program my code crashes and I get this error:

Traceback (most recent call last):
  File "phonecases.py", line 12, in <module>
    price = content.find(class_="products-grid-price").get_text().replace('\n','')
AttributeError: 'NoneType' object has no attribute 'get_text'

This is because some items are on sale, when an item is not on sale the class is products-grid-price and when an item is on sale the class is products-grid-price-sale.
Therefore, the program collects the data I want until it reaches an item on sale and then it crashes.
How do I fix my program so that it either skips the item on sale or collects them as a different data point?
This is my code:
import requests
from bs4 import BeautifulSoup

url = 'https://www.cellphonecases.com/Apple-Iphone-11-C2429.html?page='
    for page in range(1, 5):
        response = requests.get(url + str(page))
        soup = BeautifulSoup(response.text, 'html.parser')
        contents = soup.find_all(class_="products-grid-container-out")

    for content in contents:
        title = content.find(class_="products-gridname").get_text().replace('\n','')
        price = content.find(class_="products-grid-price").get_text().replace('\n','')
        print(title, price)

A: Use a try/except, for example:
price = None
try:
    price = content.find(class_="products-grid-price").get_text().replace('\n','')
except:
    price = content.find(class_="products-grid-price-sale").get_text().replace('\n','')

It will first try the code, if it throws an exception (error) it will catch it and run the code in the except block.
Or something like:
price = None
price_field = content.find(class_="products-grid-price")
if price_field:
    price = price_field.get_text()
else:
    price = content.find(class_="products-grid-price-sale").get_text()

# clean price
price = price.replace('\n','')


text:
Q: ImportError: no module named src или почему Pycharm работает, а терминал - нет? Предположим, есть два скрипта:
-wsgi.py
и рядом с ним второй, называется controller.py .
wsgi - очень простой, там написано:
'from src.dev.controller import app
 'if __name__ == "__main__":
  app.run(threaded=True)'

Запускаю из Pycharm - ок, все работает.
Захожу в терминал под тем же виртуальным окружением (virtualenv), что и в настройках PyCharm-a  - получаю Traceback:
$python wsgi.py
'Traceback (most recent call last):
 File "wsgi.py", line 4, in <module>
from src.dev.controller import app
ImportError: No module named 'src' '

я полез разбираться - повторил вот это(там про добавление PYTHONPATH) http://forum.ubuntu.ru/index.php?topic=197830.0 - не сработало.
все init.py написаны и лежат пустые во всех папках.
Пытался в wsgi.py дописывать sys.path.insert(0,r'/home/spotapov/testbuild/image-processor/src/dev'
 - тоже не сработало.
Надеюсь на помощь, спасибо!

A: Если судить по ошибке файл wsgi.py не находится в одном каталоге с директорией модулей src. Обеспечьте доступность: положите в общую папку или добавьте в sys.path (используйте путь как вы пробовали только окончание сделайте ../image-processor)
В PyCharm вероятней всего ваш проект оформлен package и он правильно добавляет в PYTHONPATH, print sys.path в консоли и в pycharm и сравните.


text:
Q: JSON parsing of ClusterRole in Go is not working I have a problem parsing the metadata in ClusterRole object from Json in Go.
I made this example:
package main

import (
    "encoding/json"
    "fmt"

    "k8s.io/kubernetes/pkg/apis/rbac"
)

func main() {
    clusterDemo := rbac.ClusterRole{}

    clusterRolesRaw := `{
        "apiVersion": "rbac.authorization.k8s.io/v1",
        "kind": "ClusterRole",
        "metadata": {
            "creationTimestamp": "2021-01-21T08:07:13Z",
            "managedFields": [],
            "name": "kubeadm:get-nodes",
            "resourceVersion": "220",
            "uid": "c78a8b10-cd20-4b64-8e4d-4f7f758c7b65"
        },
        "rules": []
    }`
    err := json.Unmarshal([]byte(clusterRolesRaw), &clusterDemo)
    if err != nil {
        fmt.Printf("unmarshal file: %v", err)
    }
    fmt.Printf("Name: %s\n", clusterDemo.Name)
    fmt.Printf("Kind: %s\n", clusterDemo.Kind)
}

Run it with
# go get -v ./...
# go run <filename>
Name:
Kind: ClusterRole

As you can see, the Kind field is parsed, but the Name field (part of the metadata) is not.
My question is why? It looks like the nested structure is not parsed.
Any help is appreciated, I think I am missing something

A: Change your import from "k8s.io/kubernetes/pkg/apis/rbac" to rbac "k8s.io/api/rbac/v1".
It should work.


text:
Q: Is an unenclosed cable modem circuit board a fire hazard? I've come up with a clever hack to save space and reduce # power adapter eye sores by bolting my cable modem (Netgear CM500) under the Wifi router (WRT 3200ACM).

The heat sink over the Broadcom baseband processor is very hot to touch. I measured ~70C for the processor and ~55C for the RF (de)modulator enclosure (had to set mode to glossy or else readings for shiny surfaces are wildly underestimated). Modem consumes 8W max.

As clever as it seems, I was worried if there's any fire hazard or other problems if I were to let the heatsink lie on top of a a wood surface or carpet.
I had a read some of this guide,
https://incompliancemag.com/article/electrically-caused-fire-in-multilayer-circuit-boards/
and the main take away was that for fire, it had to generate a temperature beyond the ignition temperature. But I didn't see any way to calculate the
 temperature. That would be a function of the power density and thermal resistance of the heating element.
Also, it said to distinguish between normal conditions and fault conditions.
Normal condition of ~70C already feels worrisome.
But most developer boards for embedded platforms are unenclosed. I guess they would've thought about fire hazards also?

A: 70 c is not enough to spontaneously ignite paper let alone wood. The carpet depends on the material. But there is no reason you have the heatsink touching anything. Use stand offs.
That said, of you do catch your house on fire, I'm sure your insurance would rule that cable modem as voiding your insurance.

A: I doubt that it is a fire hazard but it will likely put both the cable modem and the router in a higher temperature environment than they were designed to handle.  This will potentially increase error rates, cause random crashes, or even cause the devices to fail entirely.
The modem is normally vertically oriented so that convection currents help cool the heatsink.  With the modem sitting under the router, the heat can't escape as easily.  The trapped heat will cook both the modem and to a lesser extent the router.
If you really want to do this, sit the whole thing on top of a mini laptop cooling fan.

A: It is easier to mechanically damage the circuit board. This could cause a short circuit, and thus fire.
You have removed the fire retardant plastic casing, meaning you can place other flammable materials near it.
Yes, you have increased the fire hazard.
It is not an direct fire hazard, it's still a low power device using an AD/DC adapter.


text:
Q: (IONIC 4) ion-tab-button do not change color when clicked/selected I have an ion-tab with differents ways to redirect: By Routes at the tabs.module.ts and by [routerLink] in html.
The problem is: when the ion-tab-buttons are clicked, they navigate to other pages correctly but the color only change when using Routes and "loadchildren" routing.
using CSS:
ion-tab-button {
 --color-selected: var(--ion-color-text-secondary);
}

I tried to use loadChildren routing in all tabs but some tabs are to redirect to a component and was not successful.
I also tried to use pseudo-classes in CSS like
ion-tab-button:active {
    color: blue;
}

ACTUAL FILES:
tabs.page.html
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="home">

    </ion-tab-button>

    <ion-tab-button [routerLink]="['/tabs/home/feed/feed-user/' + id]">

    </ion-tab-button>

    <ion-tab-button [routerLink]="['/tabs/home/trade-room']">

    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

tabs.module.ts
const routes: Routes = [
  {
    path: '',
    component: TabsPage,
    children: [
     {
        path: '',
        redirectTo: '/tabs/home',
        pathMatch: 'full'
     },
      {
        path: 'home',
        loadChildren: '../home/home.module#HomePageModule'
      },
    ]
  }
];

I need some way to change the color button when they are clicked

A: You can change the class of the button 'tab-selected' from true to false when you detect the right path.
<ion-tab-button [routerLink]="['/tabs/home/feed/feed-user/' + id]" [class.tab-selected]="selectedPath.includes('feed')">

</ion-tab-button>

A: I'm not sure this is exactly what you are looking for but maybe you can use some form of this idea to solve your problem.
You can subscribe to the router events in tabs.page.ts and evaluate the url and apply css if the url matches one of the redirects.
tabs.page.ts
import { Component } from '@angular/core';
import { Router, RouterEvent } from '@angular/router';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {

  selectedPath = '';

  constructor(private router:Router) {
    this.router.events.subscribe((event: RouterEvent) => {
      if(event && event.url){
        this.selectedPath = event.url;
      }
    });
  }
}

tabs.page.html
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="home">

    </ion-tab-button>

    <ion-tab-button [routerLink]="['/tabs/home/feed/feed-user/' + id]" [class.active-item]="selectedPath.includes('feed')">

    </ion-tab-button>

    <ion-tab-button [routerLink]="['/tabs/home/trade-room']" [class.active-item]="selectedPath.includes('trade')">

    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

tabs.page.scss
.active-item {
  color: red;
}

This will not affect the existing behavior of the tabs defined in tabs.module.ts. You will probably have to write a bit more to manage the css of those tabs.
I came across this pattern here by Simon Grimm. He has some really great tutorials.
Hope this helps


text:
Q: Java Cant read or write object to file There is this method klasOpslaan(Klas deKlas). I need to write deKlas to an object. Afterwards I need to read it with method klasInladen. I am getting an error writing aborted; java.io.NotSerializableException: week5.practicum4.Klas although I implemented Serializeable. I did note that when writing my object it makes the object but doesn't write to it. I did implement everything but StackOverflow wont let me post it.
public class KlasManager implements Serializable {

    public void klasOpslaan(Klas deKlas) throws IOException, FileNotFoundException {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        System.out.println("Klas opgeslassgen");

        oos.writeObject(deKlas);

        oos.close();

    }

    public Klas klasInladen() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);

        Klas deKlas = (Klas) ois.readObject();
        ois.close();

        return deKlas;

    }
}

edit: needed Serializeable in other classes, not in this one.


text:
Q: Characterising functions $f$ that can be written as $f = g \circ g$? I'd like to characterise the functions that 'have square roots' in the function composition sense. That is, can a given function $f$ be written as $f = g \circ g$ (where $\circ$ is function composition)?
For instance, the function $f(x) = x+10$ has a square root $g(x) = x+5$.
Similarly, the function $f(x) = 9x$ has a square root $g(x) = 3x$.
I don't know if the function $f(x) = x^2 + 1$ has a square root, but I couldn't think of any.
Is there a way to determine which functions have square roots? To keep things simpler, I'd be happy just to consider functions $f: \mathbb R \to \mathbb R$.

A: I showed you the link to the MO question mostly to convince you that this is a hard question.  I will "answer" it in the special case that $f$ is a bijection.
Recall that given a bijection $f : S \to S$, where $S$ is a set, a cycle of $f$ length $n$ is a set of distinct points $x, f(x), ... f^{n-1}(x)$ such that $f^n(x) = x$.  A cycle of infinite length is a set of distinct points $x, f(x), f^2(x), ...$.  It is not hard to see that $S$ is a disjoint union of cycles of $f$.
Claim:  A bijection $f : S \to S$ has a square root if and only if there are an even number of cycles of $f$ of any given even length.  (For the purposes of this result, infinity is an even number; so there can be an infinite number of cycles, and you need to consider cycles of infinite length.)
Proof.  First we show that any bijection with a square root has this property.  Let $g : S \to S$ be a bijection such that $g(g(x)) = f(x)$.  Then each cycle of $g$ corresponds to either one or two cycles of $f$, as follows.  If the cycle has odd length, it corresponds to one cycle of $f$.  For example, the cycle $1 \to 2 \to 3 \to 1$ of $g$ would correspond to the cycle $1 \to 3 \to 2 \to 1$ of $f$.  If the cycle has even length, it corresponds to two cycles of $f$.  For example, the cycle $1 \to 2 \to 1$ of $g$ would correspond to the pair of cycles $1 \to 1$ and $2 \to 2$, and the cycle $1 \to 2 \to 3 \to ... $ would correspond to the pair of cycles $1 \to 3 \to ... $ and $2 \to 4 \to ...$.  In particular, cycles of $f$ of odd length can come from cycles of $g$ one at a time or two at a time, but cycles of $f$ of even length can only come from cycles of $g$ two at a time.
Now we show the reverse implication.  Given a cycle of $f$ of odd length $2k+1$, consider the corresponding cycle of $f^{k+1}$ of odd length.  Since $f^{2k+2} = f$ when restricted to this cycle, make this a cycle of $g$.  Given a pair of cycles of $f$ of the same even length, just weave them together to get a cycle of $g$.
I say "answer" instead of answer because it's not obvious if you can always find the cycle decomposition of some complicated bijection on an infinite set.  In any case, if $f$ isn't assumed to be a bijection this question becomes much harder; the analogue of cycle decomposition is much more difficult to work with.  I suggest you look at some examples where $S$ is finite if you really want to get a grip on this case; best of luck.


text:
Q: File or path to database in prometheus where alerts are stored in json or other format that reflects in grafana What did you do?
I am not sure whether this is right forum to ask this questions but I am looking for file or path to database in prometheus where alerts are stored in json or other format that reflects in grafana. I want to write a scripts to take some actions based on alerts/triggers. Normally alerts can be seen on dashboard and notified accordingly on email or messages. My concerns is to trace the path from where the alerts are relflected in grafana.
What did you expect to see?
I expect to have path to database or any json file in which alerts are populated on run time.
Environment
System information:
Linux 3.10.0-1160.53.1.el7.x86_64 x86_64
Prometheus version:
prometheus, version 2.30.0-rc.0 (branch: HEAD, revision: 05a816b)
build user: root@438506e6c112
build date: 20210909-13:31:07
go version: go1.17
platform: linux/amd64
Alertmanager version:
alertmanager, version 0.20.0 (branch: HEAD, revision: f74be0400a6243d10bb53812d6fa408ad71ff32d)
build user: root@00c3106655f8
build date: 20191211-14:13:14
go version: go1.13.5
Any help in this regard would be highly appreciated.


text:
Q: demo code provided by overleaf causes error on overleaf overleaf doc gives this demo to illustrate the usage of xeCJK
\documentclass{article}
\usepackage{xeCJK}
\begin{document}

\section{前言}

\section{关于数学部分}
数学、中英文皆可以混排。You can intersperse math, Chinese and English (Latin script) without adding extra environments.

這是繁體中文。
\end{document}

run the code above on overleaf causes 28 errors.
here is the first one
 /usr/local/texlive/2018/texmf-dist/tex/xelatex/xecjk/xeCJK.sty, line 43
Critical Package xeCJK Error: The xeCJK package requires XeTeX to function.

(xeCJK)
(xeCJK)                         You must change your typesetting engine to
(xeCJK)                         "xelatex"
(xeCJK)                         instead of plain "latex" or "pdflatex" or
(xeCJK)                         "lualatex".
(xeCJK)                         Loading xeCJK will abort!

For immediate help type H <return>.
 ...

l.43 ..._critical:nn { xeCJK } { Require-XeTeX } }

it seems that I need to change the typesetting engine. How to change the typesetting engine overleaf?

A: Link to instructions for changing backend compiler according to Overleaf's website.
It suggests going to Menu --> Settings --> Compiler and select the appropriate one.


text:
Q: Trying to move elements into empty arrays. Code runs, but nothing is being returned I'm very new to coding and I've been trying to practice arrays and storing new elements into empty arrays. this code runs, but nothing comes back. what am I doing wrong?
const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];

for (let i=0; i<myArr.length; i++) {
    if (myArr[i] % 2 == 0)
    myArr.push(evenArray[i])
    return evenArray
} if (myArr[i % 2 !== 0]) {
    myArr.push(oddArray[i])
}
    return oddArray

console.log(evenArray)

A: There are a lot of problems with your code.
For example:
You are trying to use return out of a function.
You are pushing into myArr, instead of even or odd arrays..
You are also not correctly using the curly braces. Here is how you should do it.

const myArr = [2, 2, 3, 4, 4, 5];

const evenArray = [];
const oddArray = [];

for (let i = 0; i < myArr.length; i++) {
  if (myArr[i] % 2 === 0) {
    // even
    evenArray.push(myArr[i]);
  } else {
    // odd
    oddArray.push(myArr[i]);
  }
}

console.log({ evenArray });
console.log({ oddArray });
console.log({ myArr });
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: Main problems with how you are writing your code:

*

*Return statement not within function

*Not using if statements correctly

Here is a solution:
      const myArr = [2, 2, 3, 4, 4, 5];
      const evenArray = [];
      const oddArray = [];

      for (let i = 0; i < myArr.length; i++) {
        if (myArr[i] % 2 == 0) {
          evenArray.push(myArr[i]);
        } else {
          // We can just use an else statement here because anything thats not even is odd
          oddArray.push(myArr[i]);
        }
      }

      console.log(evenArray, oddArray); // Now that the loop has run console.log the results

Note: Stack overflow is not the place to ask questions about the basics of coding! I would recommend checking out freeCodeCamp.org and their YouTube channel because you seem to have problems with the fundamental principals of js.

A: You dont need return statements. Only save values into new arrays.

const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];

for (var i=0; i < myArr.length; i++) {
    if (myArr[i] % 2 == 0) {
       evenArray.push(myArr[i]) //push even elements into evenArray
    }
    if (myArr[i] % 2 !== 0) {
        oddArray.push(myArr[i]) //push odd elements into oddArray
     }
}
console.log(evenArray) //evenArray will have even numbers
console.log(oddArray)  //oddArray will have odd numbers

A: Please share which programming language you're using.
As per your code it seems you are pushing the empty array value to your myArr array. Try using evenArray.push(myArr[i]) instead of myArr.push(evenArray[i])


text:
Q: Api Gateway S3 Proxy with Cloud Formation wont accept Bucket ARN but will accept all buckets I have a simple Cloud Formation script that I am working with. It creates a host of resources including an API Gateway and S3 bucket, the former of which I want to server as a Proxy for the later when uploading objects. Here is the role definition:
BucketItemApiMethodRole:
Type: AWS::IAM::Role
Properties:
  AssumeRolePolicyDocument:
    Version: "2012-10-17"
    Statement:
      - Effect: Allow
        Principal:
          AWS: "*"
          Service: apigateway.amazonaws.com
        Action: "sts:AssumeRole"
  Path: "/"
  Policies:
    - PolicyName: "tc-bucketitemmethodrole"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Action: "s3:Put*"
            Resource: !GetAtt RawBucket.Arn

Here is the relevant portion from API Gateway Method that does the Put against S3:
Integration:
    Type: AWS
    Credentials: !GetAtt BucketItemApiMethodRole.Arn
    IntegrationHttpMethod: PUT
    PassthroughBehavior: WHEN_NO_MATCH
    RequestParameters:
      integration.request.header.Content-Disposition: method.request.header.Content-Disposition
      integration.request.header.Content-Type: method.request.header.Content-Type
      integration.request.path.key: method.request.path.item
    Uri:
      Fn::Join:
        - "/"
        - - "arn:aws:apigateway:us-east-1:s3:path"
          - !Ref RawBucketName
          - "{key}"
    IntegrationResponses:
      - StatusCode: 201

My question is this: When I set the Resource for the Role to "*" it works fine. When I specify the Arn directory, as shown, I get an Access Denied error from S3. Looking for any thoughts as to what I might be running into.
Thanks

A: Needed a BucketPolicy - that fixed it


text:
Q: Setup ArcGIS 10.2.2 and SQL Server 2012 I installed on Oracle VM VirtualBox two Windows Server 2008 R2.
•   One with ArcGIS Server and ArcGIS Desktop 10.2.2 10.2.2
•   The second SQL Server 2012 in Mixed Mode
Because I'm not connected to a network, I use the Host-Only Ethernet Adapter Mode to let the host communicating with guests.
My questions are:
On what virtual machine should I have to install ArcSDE and Microsoft SQL Server 2012 SP1 Native Client.
If you could point me to a good tutorial, that would be great.


text:
Q: =IF() Not working properly in some rows MS EXCEL2013
Can Someone help me with this formula because some rows are working properly and some rows are not such as this one in the image i shared. its says failed even though m266 and d266 is the same (400.00). I also checked if its in TEXT or NUMBER format
i already tried some troubleshooting like =IF(D266>0,"TRUE","FALSE") and =IF(M266>0,"TRUE","FALSE")
This is the formula:
M266 = =IF(K266-L266+P266=0,"-",K266-L266+P266)
N266 =IF(OR(M266=D266),"Success","Failed")


text:
Q: Access control for adb connection of phone I need to prevent others from accessing my phone via adb. Any way we can have password protection for adb connection?

A:
Since Android 4.2.2, connections to ADB are authenticated with an RSA keypair. This prevents unauthorized use of ADB where the attacker has physical access to a device.

Security Enhancements in Android 4.3

A: As far as I know, there's no way to set an extra password specific to adb access.
If you have USB debugging (adb) enabled, on Android 4.3 or later you need to manually accept the host computer on your device before debugging is enabled.
So unless somebody has access and PIN/password to your phone AND the computer you already authorized for USB debugging that phone, your phone should be safe. However, there are security holes such as this which means that if you're using an old device, maybe it's time for a custom ROM based on a recent version of Android.
With earlier versions of Android, I used an app called Delayed Lock with the "helper app" add-on (ROOT required), that automatically enabled/disabled USB debugging when you unlock/lock your phone.

A: As long as the "USB debugging" (check it here) is disabled and phone is locked so no one can have the access to this option, no one can use your phone for adb connection.
Refer wipe data remotely for an ill fortunate situation.


text:
Q: Hamming Ecc computation Consider the example of hamming ECC https://en.wikipedia.org/wiki/Hamming_code
Suppose after receiving you find that parity bits 16 and 8 are incorrect  , which bit do you correct

A: The question is a bit vague, but here are some possible answers:
1) 20-bit (20, 15) SEC code
If you have the code shown in the table without the "..." section filled in, then it depends on the implementation of the decoder but in theory it should be a detectable error. The decoder would probably raise the "detectable but uncorrectable error" (DUE) signal.
2) 31-bit (31, 26) SEC code
If you're talking about the code in the table with the "..." section filled in, this is a (31, 26) code. The error will mistakenly miscorrect the 8+16=24th bit, causing silent data corruption (SDC).
3) a 21-bit (21, 15) SEC-DED or 32-bit (32, 26) SEC-DED code
If you add an overall parity bit to the code (see section "Hamming codes with additional parity (SECDED)"), then the code can properly detect any two-bit errors. Therefore this error will be properly detected and the decoder will raise the DUE signal.


text:
Q: Docker on Ubuntu unable to connect to localhost but works connecting to its ip I am running Ubuntu 18.04
$ uname -r
5.3.0-46-generic

I have docker installed
$ docker --version
Docker version 19.03.8, build afacb8b7f0

I have a simple docker image that exposes port 80. The Dockerfile that generated it was
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
COPY publish .
EXPOSE 80
ENTRYPOINT ["dotnet", "SampleWebApp.dll"]

When I run a container for this image I can see the following:
$ docker run myimage:latest -p 8080:80
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:80
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /

And if I see the containers running:
$ docker ps
CONTAINER ID        IMAGE                                                                              COMMAND                  CREATED             STATUS              PORTS               NAMES
6f5bea7b329d        registry.gitlab.com/whatever/myimage:latest   "dotnet SampleWebApp…"   4 seconds ago       Up 2 seconds        80/tcp              dreamy_leavitt

So I can see that it's running on the port 80/tcp.
Not sure why it does not run on port 8080 which is where I wanted to map it.
Also, the http://[::]:80 seems confusing. I've read something about it being IPv6. No idea what consequences this has or why normal IPv4 wouldn't work.
My interface info:
$ ifconfig
docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:71ff:fe7f:305  prefixlen 64  scopeid 0x20<link>
        ether 02:42:71:7f:03:05  txqueuelen 0  (Ethernet)
        RX packets 131843  bytes 105630866 (105.6 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 201439  bytes 268197990 (268.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp3s0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 1c:1b:0d:a4:83:16  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 118628  bytes 17999594 (17.9 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 118628  bytes 17999594 (17.9 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

vethca5fd09: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet6 fe80::3c56:d6ff:fe0c:846  prefixlen 64  scopeid 0x20<link>
        ether 3e:56:d6:0c:08:46  txqueuelen 0  (Ethernet)
        RX packets 7  bytes 533 (533.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 52  bytes 7342 (7.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp6s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.135  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::8a58:c682:3833:3bb1  prefixlen 64  scopeid 0x20<link>
        ether e4:be:ed:4f:0f:21  txqueuelen 1000  (Ethernet)
        RX packets 519710  bytes 524989683 (524.9 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 439859  bytes 165781721 (165.7 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

So.. docker interface seems to have the address 172.17.0.1.
However I cannot access my container using the following urls:
$ curl http://localhost:8080
curl: (7) Failed to connect to localhost port 8080: Connection refused

$ curl http://localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused

$ curl http://0.0.0.0:80
curl: (7) Failed to connect to 0.0.0.0 port 80: Connection refused

$ curl http://0.0.0.0:8080
curl: (7) Failed to connect to 0.0.0.0 port 8080: Connection refused

$ curl http://172.17.0.1:8080
curl: (7) Failed to connect to 172.17.0.1 port 8080: Connection refused

$ curl http://172.17.0.1:80
curl: (7) Failed to connect to 172.17.0.1 port 80: Connection refused

$ curl http://127.0.0.1:8080
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

$ curl http://127.0.0.1:80
curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused

so no access using localhost, 127.0.0.1 or the docker interface IP.
If I inspect the container:
sasw@Z3:~$ docker inspect 6f5bea7b329d
[
    {
        "Id": "6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a",
        "Created": "2020-04-20T13:06:37.883347676Z",
        "Path": "dotnet",
        "Args": [
            "SampleWebApp.dll",
            "-p",
            "8080:80"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 30636,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-04-20T13:06:38.295411125Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:e00403d6c5eb3ccbe3c5c7b6ec8cf8289158e4c9fbe6ff5872ea932e69d60f38",
        "ResolvConfPath": "/var/lib/docker/containers/6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a/hostname",
        "HostsPath": "/var/lib/docker/containers/6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a/hosts",
        "LogPath": "/var/lib/docker/containers/6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a/6f5bea7b329d05bcb534953745f376da9c7efbe54de5532f8648b618152b722a-json.log",
        "Name": "/dreamy_leavitt",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/8f56c544522ccb6556358601706cb900c405c19b47e54c25d8b3dac979100e5b-init/diff:/var/lib/docker/overlay2/81bfee49e33d9761a6ca78dfd6f3f9a54a9333b4d4fc9986e8084f6b45232f04/diff:/var/lib/docker/overlay2/c2add2cb2d687126c6826c7dd9e1c85be1473a53d6b878554aa87615701344a0/diff:/var/lib/docker/overlay2/ebd0b92c5111423fb8d1219f757e41013a1473bdbe5cf3553cecbd4337f76766/diff:/var/lib/docker/overlay2/9197af6ebe4c70f0a84c7c267b1ba069aa710d917abe9fb3fee13320a17ab765/diff:/var/lib/docker/overlay2/1f463e8667b6eecc7c251ac05316b8d5d32840bff13d9f5cb7853c88e6f1f40e/diff:/var/lib/docker/overlay2/b7c9450f53334bef02f50cc854b33140b97f4ff3d2343b3fcac7b20f647c454e/diff",
                "MergedDir": "/var/lib/docker/overlay2/8f56c544522ccb6556358601706cb900c405c19b47e54c25d8b3dac979100e5b/merged",
                "UpperDir": "/var/lib/docker/overlay2/8f56c544522ccb6556358601706cb900c405c19b47e54c25d8b3dac979100e5b/diff",
                "WorkDir": "/var/lib/docker/overlay2/8f56c544522ccb6556358601706cb900c405c19b47e54c25d8b3dac979100e5b/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "6f5bea7b329d",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": true,
            "AttachStderr": true,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "ASPNETCORE_URLS=http://+:80",
                "DOTNET_RUNNING_IN_CONTAINER=true"
            ],
            "Cmd": [
                "-p",
                "8080:80"
            ],
            "Image": "registry.gitlab.com/ddd-malaga/continuous-deployment-gitlab-docker-dotnet:latest",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "dotnet",
                "SampleWebApp.dll"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "4e53bd2bc6cb83b7c0cba9fcdf07eb564a11ca6b955514670ba3f464aa0a96b7",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/4e53bd2bc6cb",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "83976112bb202b79880777563cd1b06ef27781fd288b210b19fb499e3bf51c90",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "7589efd57cea8d2b04823657fcfc54225991bc58c93ff0e463b6f12acb28b853",
                    "EndpointID": "83976112bb202b79880777563cd1b06ef27781fd288b210b19fb499e3bf51c90",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

I can see the IP Address 172.17.0.2. Again, I don't know where this comes from.
But now I can try to access the container IP at the port I told it to map:
$ curl http://172.17.0.2:8080
curl: (7) Failed to connect to 172.17.0.2 port 8080: Connection refused

Surprisingly, if I access the same container IP but the exposed port 80 it works
sasw@Z3:/$ curl http://172.17.0.2:80
Hello World!

If I stop and delete complete container and images and try again with the following random port:
$ docker run myimage:latest -p 1234:1234
Status: Downloaded newer image for registry.gitlab.com/myimage:latest
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:80
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /

it seems those ports are completely ignored and it remains listening on the container ip and port 80
$ curl http://172.17.0.2:80
Hello World!

It's clear I am missing some knowledge here and the links I find are not very useful or the point me to things about IPv6 like this https://docs.docker.com/config/daemon/ipv6/ that mentions something about a /etc/docker/daemon.json which I don't even have.
Could anybody point me into the right direction to understand what's happening and why? Thanks!

A: It seems the problem was that none of my arguments to docker run was taking effect because I placed them AFTER the image. Insane!
So this:
docker run myimage:latest -p 8080:80 --name whatever

will run the container ignoring completely the port mapping and the container assigned name.
However this:
docker run -p 8080:80 --name whatever myimage:latest

Will map the port 80 to my localhost:8080 so that the web app is available at https://localhost:8080


text:
Q: Understanding macro code statement with lambda and __attribute__ My program(C++) is defining a macro for throw statements. It is something like:
#define FOO_THROW(some-exception-type, some-error-message)  \
    do                                                      \
        {                                                   \
            [&]() __attribute__((cold, noinline))           \
            {                                               \
                using exception_type = some-exception-type; \
                std::ostringstream ss;                      \
                ss << some-error-message << "";             \
                throw exception_type(ss.str());             \
            }                                               \
            ();                                             \
        }                                                   \
    while (0);

Then, it is getting called in the program, something like:
FOO_THROW(std::runtime_error, "error specfic message here")

I can see that we use do...while(0) structure with the macro, what I want to understand is the use of lambda and __attribute__ here, can someone explain that in simple words?
Basically, my focus is what is the need of lambda function here, when it can be done without it, is there can be any specific advantage of it here?
I am a beginner in C++, so any hint in the right direction will do as well!

A: do...while(0) allows the macro to by called with semicolon at the end, i.e. macro(x,y,z); (note the semicolon at the end), that's an old trick back from C, you can look it up separately.
As for the rest... it defines a lambda (immediate function object) capturing everything by reference (not sure why) that throws exception of a given type with a given message and calls it immediately, effectively throwing an exception.
The attributes signify the lambda is unlikely to be called (cold) and prevent from inlining (noinline), see: https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html


text:
Q: Selenium - looking for examples of converting xpath locators to css I have a ton of tests written in xpath that I need to convert to css.
I don't want to use an automation tool as I want to take the opportunity to learn the way to do things using the css approach in selenium.
Where can I find examples of 'before' and 'after' when changing from xpath to css for locators

A: I know you've answered it yourself, but I swear by this site, has a very nice diagram showing you exactly what you are asking:
https://www.simple-talk.com/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/

A: Here are 30 examples of 'before' and 'after' xpath to css:
Note that css also uses 0 based positioning and xpath uses 1 based, as in:
Example:
xpath=(//li[contains(@id,'topic_roles_input')]//input[@type="checkbox"])[1]
css=li#topic_roles_input input[type=checkbox]:nth(0)

The list:
//ul[contains(@id,'district-switcher')]//li/ul/li[4]/a
css=ul#district-switcher li > ul > li:nth(3) > a

//ul[contains(@id,'district-switcher')]//a[contains(text(),'District Management Council')]
css=ul#district-switcher a:contains('District Management Council')

//ul[contains(@id,'district-switcher')]//a[contains(text(),'${QA_run_number}')]
css=ul#district-switcher a:contains('${QA_run_number}')

//h3[contains(@id,'active-district')]
css=h3#active-district

//ul[contains(@class,'home-menu')]//a[contains(text(),'Calendar')]
css=ul.home-menu a:contains("Calendar")

//tr[1]//td[contains(@class,'starts_on')]
css=tr td.starts_on

//tr[1]//td[contains(@class,'ends_on')]
css=tr td.ends_on

//ul[contains(@class,'home-menu')]//a[contains(text(),'Schools')]
css=ul.home-menu a:contains('Schools')

//table[contains(@id, 'schools')]//tbody//tr//td/a
css=table#schools tbody tr td a

//a[contains(text(),'6DAYERS')]
css=a:contains('6DAYERS')

//ul[contains(@class,'home-menu')]//a[contains(text(),'Students')]
css=ul.home-menu a:contains(Students)

//body//td[contains(text(),'QA-001')]
css=td:contains('QA-001')

//ul[contains(@class,'home-menu')]//a[contains(text(),'Roles')]
css=ul.home-menu a:contains(Roles)

//table//tr//td[contains(text(),"Language Therapist")]
css=table tr td:contains(LanguageTherapist)

//table//tr//td[contains(text(),"Speech Therapist")]
css=table tr td:contains(Speech Therapist )

//table//tr//td[contains(text(),"DELETE_ME")]
css=table tr td:contains(DELETE_ME)

//ul[contains(@class,'home-menu')]//a[contains(text(),'Activities')]
css=ul.home-menu a:contains(activities)

xpath=(//li[contains(@id,'activity_roles_input')]//input[@type="checkbox"][1])
css=li#activity_roles_input input[@type="checkbox"]:nth(0)

//table[contains(@id,'activities')]//tr//td[contains(text(),"Activity001")]
css=table#activities tr td:contains("Activity001")

//ul[contains(@class,'home-menu')]//a[contains(text(),'Practitioners')]
css=ul.home-menu a:contains(Practitioners)

//table//tr//td[contains(text(),'mdurrant+${QA_run_number}_001@dmcouncil.org')]
css=table tr td:contains(mdurrant+${QA_run_number}_001@dmcouncil.org)

//ul[contains(@class,'home-menu')]//a[contains(text(),'Topics')]
css=ul.home-menu a:contains(Topics)

xpath=(//li[contains(@id,'topic_roles_input')]//input[@type="checkbox"])[1]
css=li#topic_roles_input input[type=checkbox]:nth(0)

//a[contains(text(),'Topic001')]
link=Topic001

//ul[contains(@class,'home-menu')]//a[contains(text(),'Settings')]
link=Settings

//ul[contains(@class,'home-menu')]//a[contains(text(),'Settings')]
css=ul.home-menu a:contains(Settings)

xpath=(//li[contains(@id,'setting_roles_input')]//input[@type="checkbox"])[1]
css=li#setting_roles_input input[type=checkbox]:nth(0)

xpath=(//table/tbody/tr//td/a[contains(@class,'delete_link')])
table > tbody > tr td > a.delete_link

//td[contains(text(),'Setting001')]
css=td:contains('setting001')

//a[contains(text(),'Practitioners')]
css=a:contains(Practitioners)

//tr[td[contains(.,'6 Day')]][1]/td[8]/a@href
tr td:contains('6 Day'):nth(0) + td + td a[href]


text:
Q: System.Data.OleDb.OleDbException: Operation must use an updateable query I'm confused. I'm trying to add a single record into an Access 2000 database using ASP.Net.
However, when I try to add new record, I get the following error:
Exception Details: System.Data.OleDb.OleDbException: Operation must use an updateable query.

A: Admittedly, the error message is misleading.
The reason for this error message is that the process runs under an identity (usually ASP.NET) that only has read access to the database and hasn't access to modify that.
So, to solve this problem you must set full access of ASP.Net user to Database file.
If run it on local machine you can right click on the database file in Windows Explorer, go to the Security tab, and give the ASP.NET user modify rights to the file, but if your web site on the internet you must using your Control panel setting (such as C-Panel or Plesk) to set permission.


text:
Q: POST request with httr package using R I would like to get the output from POST request using httr from following site:
http://www.e-grunt.ba

You can see submit form when you click "ZK Ulošci".
There I would like to send POST request and get the output. For example, you can select anything from drop down window and enter 1 in filed "Broj Uloška", and than click "Traži".
Here is my try:
library(httr)
library(tidyverse)
library(rvest)

    output <- httr::POST(
      "http://www.e-grunt.ba/home.jsf",
      body = list(
        "form:court_focus" = "440",
        "form:cuTransferLast" = "17.07.2019",
        "form:municipality_input" = "4400000001",
        "form:mpart_focus" = "44000087",
        "form:folder" = 1,
        `recaptcha-token` = "some token",
        submit = "form:j_idt61"
        ),
      add_headers(Referer = "http://www.e-grunt.ba/"),
      encode = "form",
      verbose()
    )

But this just returns content of the home page.
I know it is easier with (R)Selenium, but I would like to do it with httr and POST if it is possible.

A: I have found the way to scrape this ASP.net site. I am providing the code if somebody will need something similar:
start_session <- function() {
  p <- html_session(
    "http://www.e-grunt.ba",
    user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36")
  )
  viewState <- p %>% html_nodes("input") %>% .[[2]] %>% html_attr("value")
  p <- rvest:::request_POST(
    p,
    "http://www.e-grunt.ba/home.jsf",
    add_headers(
      'Referer' = 'http://www.e-grunt.ba'
    ),
    body = list(
      "javax.faces.partial.ajax" = "true",
      "javax.faces.source" = "j_idt8:j_idt15",
      "javax.faces.partial.execute" = "@all",
      "javax.faces.partial.render" = "content",
      "j_idt8:j_idt15" = "j_idt8:j_idt15",
      "j_idt8" = 'j_idt8',
      'javax.faces.ViewState' = viewState
    ),
    encode = "form"
  )
  attr(p, "viewState") <- viewState
  p
}

# EXTRACT METADATA --------------------------------------------------------

p <- start_session()
name_value_pairs <- function(html, css, cnames) {
  x <- read_html(html) %>%
    html_nodes(css) %>%
    html_children() %>%
    html_attr("value")
  y <- read_html(html) %>%
    html_nodes(css) %>%
    html_children() %>%
    html_text()
  df <- cbind.data.frame(x, y, stringsAsFactors = FALSE)
  df <- df[df[, 1] != -1, ]
  colnames(df) <- cnames
  df
}
courts <- name_value_pairs(p$response$content, css = '[id="form:court_input"]', cnames = c("court_id", "court"))

metadata_post <- function(session_zk, view_state, id) {
  p <- rvest:::request_POST(
    session_zk,
    "http://www.e-grunt.ba/home.jsf",
    add_headers(
      'Referer' = 'http://www.e-grunt.ba'
    ),
    body = list(
      'javax.faces.partial.ajax' = 'true',
      'javax.faces.source' = 'form:court',
      'javax.faces.partial.execute' = 'form:court',
      'javax.faces.partial.render' = 'msgs msgsBottom form:municipality form:mpart form:cuTransferLast',
      'javax.faces.behavior.event' = 'change',
      'javax.faces.partial.event' = 'change',
      'form' = 'form',
      'g-recaptcha-response' = '',
      'form:court_focus' = '',
      'form:court_input' = id,
      'form:cuTransferLast' = '',
      'form:municipality_focus' = '',
      'form:mpart_focus' = '',
      'form:folder' = '',
      'form:parcel' = '',
      'form:parcelSub' = '',
      'javax.faces.ViewState' = view_state
    ),
    encode = "form"
  )
  return(p)
}

muni_post <- function(session_zk, view_state, id, muni_id) {
  p <- rvest:::request_POST(
    session_zk,
    "http://www.e-grunt.ba/home.jsf",
    add_headers(
      'Referer' = 'http://www.e-grunt.ba'
    ),
    body = list(
      'javax.faces.partial.ajax' = 'true',
      'javax.faces.source' = 'form:municipality',
      'javax.faces.partial.execute' = 'form:municipality',
      'javax.faces.partial.render' = 'msgs msgsBottom form:mpart',
      'javax.faces.behavior.event' = 'change',
      'javax.faces.partial.event' = 'change',
      'form' = 'form',
      'g-recaptcha-response' = '',
      'form:court_focus' = '',
      'form:court_input' = id,
      'form:cuTransferLast' = '',
      'form:municipality_focus' = '',
      'form:municipality_input' = muni_id,
      'form:mpart_focus' = '',
      'form:folder' = '',
      'form:parcel' = '',
      'form:parcelSub' = '',
      'javax.faces.ViewState' = view_state
    ),
    encode = "form"
  )
  return(p)
}

metadata_i <- list()
for (i in seq_along(courts$court_id)) {
  print(i)
  p <- metadata_post(p, attributes(p)$viewState, courts$court_id[i])
  muni <- name_value_pairs(p$response$content, css = '[id="form:municipality_input"]', cnames = c("muni_id", "muni"))

  if (nrow(muni) > 1) {
    muni_ko <- list()
    for (j in seq_along(muni$muni_id)) {
      # print(j)
      p <- muni_post(p, attributes(p)$viewState, courts$court_id[i], muni$muni_id[j])
      ko <- name_value_pairs(p$response$content, css = '[id="form:mpart_input"]', cnames = c("ko_id", "ko"))
      if (nrow(ko) == 0) {
        ko <- data.frame(ko_id = NA, ko = NA, stringsAsFactors = FALSE)
      }
      muni_ko[[j]] <-  cbind.data.frame(muni[j, ], ko, stringsAsFactors = FALSE)
    }
    metadata_i[[i]] <- cbind.data.frame(courts[i, ], do.call(rbind, muni_ko), stringsAsFactors = FALSE)
  } else {
    ko <- name_value_pairs(p$response$content, css = '[id="form:mpart_input"]', cnames = c("ko_id", "ko"))
    meta <- cbind.data.frame(courts[i, ], muni, stringsAsFactors = FALSE)
    metadata_i[[i]] <- cbind.data.frame(meta, ko, stringsAsFactors = FALSE)
  }
}
metadata <- do.call(rbind, metadata_i)

metadata_post <- function(session_zk, view_state, recaptcha, court,
                          date = as.character(format.Date(Sys.Date() - 4, "%d.%m.%Y")),
                          muni, ko, zk
) {
  p <- rvest:::request_POST(
    session_zk,
    "http://www.e-grunt.ba/home.jsf",
    add_headers(
      'Referer' = 'http://www.e-grunt.ba'
    ),
    body = list(
      'form' = 'form',
      'g-recaptcha-response' = recaptcha,
      'form:court_focus' = '',
      'form:court_input' = court,
      'form:cuTransferLast' = date,
      'form:municipality_focus' = '',
      'form:municipality_input' = muni,
      'form:mpart_focus' = '',
      'form:mpart_input' = ko,
      'form:folder' = zk,
      'form:parcel' = '',
      'form:parcelSub' = '',
      'form:j_idt61' = '',
      'javax.faces.ViewState' = view_state
    ),
    encode = "form"
  )
  return(p)
}

# example
result <- break_captcha()
p <- metadata_post(session_zk = p, view_state = attributes(p)$viewState,
                   recaptcha = result, court = metadata$court_id[i],
                   muni = metadata$muni_id[i], ko =  metadata$ko_id[i], zk = j)


text:
Q: What does it mean by with parameter 6 and 8? I am working on an assigment and i am stuck on this question.
Its in a book and i cant understand what the program wants?

I take a value from user and stores it in z.i dont have the value of 'a'.Suppose i also get that from user.i create a variable 'first' and assign it with function one done but what does it mean by with parameters 6 and 8?
This was already in book. i have done a part of question but b i cant understand.
 int one(int x, int y);
    double two(int x, double a);
    int main()
    {
    int num;
    double dec;
    .
    .
    .
    return 0;
    }
int one(int x, int y)
{
.
.
.
}
double two(int x, double a)
{
int first;
double z;
.
.
.
}

I will be thankful for your help

A: You have to pass in the 6 and 8 in the function one and give the value of the function one.
Like:
double two(int x, double a){
    int first = one(6,8);
 }

if you would do it step by step:
double two(int x, double a){
   /*step 1*/
    int z = 0;
    std::cin >> z;

   /*step 2*/
    z=z+a;
   /*step 3*/
   int first = one(6,8);

   /*step 4*/
   first = first + x;
 }

I will let you work it out the last one!
Good Luck!


text:
Q: ERROR: relation "author" does not exist SQL state: 42P01 I am a starter in Postgresql and i am trying to create a simple function with inner join inside it
CREATE OR REPLACE FUNCTION GetBooks()
RETURNS TABLE( Id int, Title text, AuthorName text) as
$BODY$
BEGIN
SELECT bo.Id , bo.Title , au.Name
        FROM "Book" bo INNER JOIN Author au ON (au.Id = bo.AuthorId);

END;
$BODY$
  LANGUAGE plpgsql;

when i execute the following
SELECT public.getbooks()

I am getting this error
ERROR:  relation "author" does not exist
LINE 2:       FROM "Book" bo INNER JOIN Author au ON (au.Id = bo.Aut...
                                    ^
QUERY:  SELECT bo.Id , bo.Title , au.Name
        FROM "Book" bo INNER JOIN Author au ON (au.Id = bo.AuthorId)
CONTEXT:  PL/pgSQL function getbooks() line 3 at SQL statement
********** Error **********

ERROR: relation "author" does not exist
 SQL state: 42P01
Context: PL/pgSQL function getbooks() line 3 at SQL statement

A: CREATE OR REPLACE FUNCTION GetBooks()
RETURNS TABLE( Id int, Title text, AuthorName text) as
$BODY$
BEGIN
  RETURN QUERY
SELECT bo."Id" , bo."Title" , au."Name"
        FROM "Book" bo INNER JOIN "Author" au ON (au."Id" = bo."AuthorId");

END;
$BODY$
  LANGUAGE plpgsql;


text:
Q: Why doesn't a glass french press shatter when boiling water is poured in? When I was little, I accidentally shattered a glass cooking instrument due to applying far too drastic a temperature change to it.  Since then, I've been a bit afraid of doing it again.  Of late, I've been using a french press to make coffee; one that happens to be made of glass.  Since I am now pouring almost boiling water into a room temperature glass object, I'm a bit worried it will shatter.  Double so since if it does, I could have almost boiling water flowing from my desk to my lap.
After dozens of uses, there hasn't been a problem.  And if there would've been one, I don't think they would have been allowed to sale it.  But I'm still concerned about how cold it can still be used at.  For example, if I leave it in my car on a cold night and bring it into the office, can it be used straight away?
So why doesn't it shatter and how cold can it be before I need to worry?
Demensions: roughly 20cm tall with a diameter of 10cm, if that is of any relevance.
Material: Glass, I assume a special kind that is better able to handle heat, but I don't kow the details.

A: As PMPJohn mentioned, it's probably made of Pyrex (a borosilicate glass).  This material has about 1/3 the thermal expansion of conventional glass, so thermal stresses are much lower and it can easily accommodate the kinds of thermal shock you describe.
Interestingly, glass made today in the US under the Pyrex name is actually no longer borosilicate glass, but is instead tempered conventional glass.  It appears to be less resistant to thermal shock than borosilicate glass.  In Europe, a similar brand-name is Duran, which still is borosilicate.
There's more information here

A: 20mm tall and 10mm in diameter seems a bit small ;)
Anyway, you know that glass is quite fragile under some circumstances, e.g., mechanical stress (bending) and high temperature gradient (which is the main culprit in a french press scenario), which means a portion of the glass is heated up more than another, causing it to epand and thus exercising mechanical stress, which can lead to shattering. That's called  thermal shock.
As the wiki article states, you can extend the resistance to thermal shock in several ways, the most obvious being to use stronger/thicker glass, and heating it up slowly and evenly.
My guess is that your french press has quite thick glass compared to, say, a drinking glass, and is also probably made from a special heat-resistant glass that either spreads heat more evenly or is more durable due to some additive (Pyrex glass seems to have added Borone).
If you want to be safe I'd advise to not use the hot, bubbling water right away, but rather let it cool a few centigrades (for maybe 15-30 seconds) before pouring it into your press. Additionally, you maybe shouldn't drop the hot press into ice cold water right away (and vice versa, which is the "press out of cold car"-situation you mentioned. Just heat it to room temperature first with lukewarm water). But you're right, if the glass the press is made out of wasn't relatively safe, I'd wouldn't be allowed for sale.

A: Actually, they can shatter from just the hot water.  Happened to me this morning.  Poured the boiling water in, turned to get the plunger and it just gushed hot water on my sweat pants and socks.  I pulled my clothes away from me, but my left foot got burned some.  I'm not sure how bad, it's only been 10 minutes.


text:
Q: \Longrightarrow doesn't look good in 12pt I'm using the standard CM fonts in 12pt (and amsmath if this is relevant). My problem is that \Longrightarrow gives something like this  output, which I find a bit annoying. I know that it's a composed symbol, but in 10pt and in 11pt it looks perfect, so why doesn't it also work in 12pt?
By the way, I produced the image by typing \Huge\Longrightarrow on mathurl.com, so it's not an artefact of my TeX system (and it tells us that mathurl uses 12pt ...). Moreover, it's not just something on the screen, I also see it on a printout (where I don't know which LaTeX distribution was used for typesetting).
I think I've first seen this when I was still using LaTeX 2.09 a long time ago!

A: (Posting as CW since I don't like to take credit for my good Google Fu)
A hack was provided in http://programming.itags.org/tex/124077/ where you re-implement the construction of \Longrightarrow by using instead of the cmr12 version of the = sign, the cmr10 version suitably rescaled. So this way the \Longrightarrow will be just like the 10-pt version but bigger. The following is the example provided by Ulrike Fischer in that thread.
\documentclass[12pt]{article}
\DeclareFontFamily{OT1}{cmrx}{}
\DeclareFontShape{OT1}{cmrx}{m}{n}{<->cmr10}{}
\begin{document}\pagestyle{empty}
$\Longrightarrow$

%Redefine \Longrightarrow as the following to get the 'fixed' version
$\mathrel{%
  \mbox{\fontfamily{cmrx}\fontencoding{OT1}\selectfont=}}%
\joinrel\Rightarrow$

\end{document}

The disadvantage of the above solution is that it's dangerous to use it as a patch for existing files: The fixed \Longrightarrow is slightly longer than the original one, so this might affect linebreaks. Here's a version that doesn't have this drawback:
\documentclass[12pt]{article}
\DeclareFontFamily{OT1}{cmrx}{}
\DeclareFontShape{OT1}{cmrx}{m}{n}{<->cmr10}{}
\let\saveLongrightarrow\Longrightarrow
\makeatletter
\renewcommand*{\Longrightarrow}{%
    \mathrel{\rlap{\fontfamily{cmrx}\fontencoding{OT1}\selectfont=}%
    \hphantom{\saveLongrightarrow}%
    \llap{$\m@th\Rightarrow$}}}
\makeatother
\begin{document}
$a\saveLongrightarrow b$

$a\Longrightarrow b$
\end{document}

A: Another faux solution: use tikz to draw the arrow for you:
\usepackage{tikz}

\newcommand{\tikzLongrightarrow}{%
 \mathbin{\tikz{\draw[arrows={-latex},line width=1.2pt,double=white] (0,0) -- (3em,0);}}
}
\let\oldLongrightarrow=\Longrightarrow
\def\Longrightarrow{\tikzLongrightarrow}

One disadvantage is that tikz is a lot to include just for one symbol.  Not a problem if you're already including tikz.  Another disadvantage is that it will take more work to make it look like the regular \Longrightarrow.

A: There is a preliminary package on Github that implements the fix suggested in the comments, see http://github.com/phst/longarrows (the documentation is outdated, but the package might already work).

A: The problem is that while there exists a cmr12 font (which is used by pdflatex), there is no cmsy12, so cmsy10 is scaled to 12pt to make it match. Unfortunately, there are subtle differences between the 10pt and 12pt versions of the computer modern fonts (slightly different metafont parameter settings), and the result of the mismatch is the effect your are witnessing.
Side note: when you zoom in a lot, you will see that the actual difference is quite small, but the effect is worsened by the different antialiasing|hinting used for the two separate fonts.
The only 'solution' I can come up with is to patch the ot1cmr.fd file such that it will use cmr10 instead of cmr12, but perhaps a LaTeX expert will know a better approach.

A: OK, I managed to produce some hack that works. The idea is to use \textcolor{white} from the xcolor package, similarly as in my not so great approach to lowering \widetilde. Here's the code:
\makeatletter
\newcommand{\myRelbar}{%
    {\Rightarrow}%
    \llap{\textcolor{white}{\rule[-0.2ex]{1.1ex}{2ex}}}%
    \kern-1.5ex}
\let\saveLongrightarrow\Longrightarrow
\renewcommand{\Longrightarrow}{%
    \mathrel{\rlap{$\m@th\myRelbar\myRelbar$}%
    \phantom{{\saveLongrightarrow}}%
    \llap{$\m@th\Rightarrow$}}}
\makeatother

The problem is the the LaTeX \Relbar is just =, and that there in 12pt the to horizontal bars are too close to each other. So I construct \myRelbar by taking \Rightarrow and chopping off the arrow head with a white box. This is not quite long enough, so I take two of those.
I've tried a second version that uses \scalebox from the graphicx package. I strongly discourage the use of this version; it's just an attempt based on my short discussion with Taco Hoekwater, and it shows that Taco was right: Scaling makes it a bit better, but it's still not perfect.
\Relbar\joinrel\mathrel{\raisebox{0.024ex}{\scalebox{0.956}{${\Rightarrow}$}}}


text:
Q: ZF2 - override gettext translations I'm working on a Zend Framework 2 project which uses gettext (mo/po) files for translation. For each language I have one translations file.
Is it possible to override some of the existing default translations just for certain clients? So for example: all clients will have translate('Cancel') translated into Cancel, except one client which will load the default translation plus an additional .mo file so that translate('Cancel') translates into Give up. How can this be done?
Only some labels should have different translation. I don't want to load a different file for each customer but to load only additional override translations for certain clients.
Thanks

A: If a client only uses a single language, this is trivial: make up a new language to serve to a client. This language would differ from the base language only to the extent specified by the client. It becomes easier if the base language is the key language as you only need to include those specific translations in your language. The difficult part is to do client specific language  detection.


text:
Q: Laravel destroy nested resource I have a resource name OrganizationEmailDomain
Route::resource('organizations.emaildomains', 'OrganizationEmailDomainController', ['except' => ['show']]);

and able to index it just fine

In that view, when clicking in the three dots there's the destroy part
<form action="{{ route('organizations.emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
    @csrf
    @method('delete')
    <button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
        {{ __('Delete') }}
    </button>
</form>

If in that index view I echo $email_domains (<?php echo $email_domains;?>) then I get as expected (note that the following was before the images were added, so the records don't match the images)
[{"id":1,"email_domain":"test.com","organization_id":1,"created_at":"2021-03-02T14:46:50.000000Z","updated_at":"2021-03-02T14:46:56.000000Z"},{"id":2,"email_domain":"gmail.com","organization_id":1,"created_at":null,"updated_at":null}]

When I try to destroy
/**
 * Remove the specified resource from storage.
 *
 * @param  \App\OrganizationEmailDomain  $emailDomain
 * @return \Illuminate\Http\Response
 */
public function destroy(Organization $organization, OrganizationEmailDomain $emailDomain)
{
    //dd($emailDomain);

    $emailDomain->delete();

    return redirect()->route('organizations.emaildomains.index',$organization->id)->withStatus(__("Organization's email domain successfully deleted."));
}

that dd($emailDomain) returns this

As langbox states

(...) hasMany relationship (...) so it returns a Collection always

So, inspired in this answer from Dan, just substituted
$emailDomain->delete();

with the following
$org_email = OrganizationEmailDomain::where('id', $organization->org_email_domains->pluck('id'))->delete();

given that in Organization model I have
/**
 * Get the email domains of the organization
 *
 * @return void
 */
public function org_email_domains()
{
    return $this->hasMany(OrganizationEmailDomain::class);
}

What's the problem here?

It always deletes the record that is in the row above.
For example, let's delete DDDDDDDDDDDDDDDDDDD

this deleted the first row, AAAAAAAAAAAAAAAAA

If I then try to delete BBBBBBBBBBBBBBB (which now became the first row) it'll delete just fine.

For reference, here's the index.blade.php where the form I shared previously is at

            {{ __('Organization') }}
            {{ __('Email Domain') }}
            {{ __('Creation date') }}
            @can('manage-org-emaildomains', App\User::class)

            @endcan

        @foreach ($email_domains as $email_domain)

                {{ $organization->name }}
                {{ $email_domain->email_domain }}
                {{ $email_domain->created_at ? $email_domain->created_at->format('d/m/Y H:i') : "NULL" }}
                @can('manage-org-emaildomains', App\User::class)

                        @if (auth()->user()->can('update', $email_domain) || auth()->user()->can('show', $email_domain) || auth()->user()->can('delete', $email_domain))

                                    @can('show', $email_domain)
                                         $id, 'emaildomain' => $email_domain->id]) }}">{{ __('Show') }}
                                    @endcan
                                    @can('update', $email_domain)
                                         $id, 'emaildomain' => $email_domain->id]) }}">{{ __('Edit') }}
                                    @endcan
                                    @if (auth()->user()->can('delete', $email_domain))
                                        <form action="{{ route('organizations.emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
                                            @csrf
                                            @method('delete')
                                            <button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
                                                {{ __('Delete') }}
                                            </button>
                                        </form>
                                    @endif

                        @endif

                @endcan

        @endforeach

A: You cant delete just the id, you are passing only the id.
in the controller you Must do Find , Ex :
$flight = Flight::find($emaidomain);

then u do
$flight->delete();

You are just passing id in the form, you must find the item in the controller via the id then delete, u cant delete id only.

A: I've changed the route to shallow nesting
Route::resource('organizations.emaildomains', 'OrganizationEmailDomainController', ['except' => ['show']])->shallow();

then the form to
<form action="{{ route('emaildomains.destroy', ['organization' => $id, 'emaildomain' => $email_domain->id]) }}" method="post">
    @csrf
    @method('delete')
    <button type="button" class="dropdown-item" onclick="confirm('{{ __("Are you sure you want to delete this email domain?") }}') ? this.parentElement.submit() : ''">
        {{ __('Delete') }}
    </button>
</form>

and the destroy() to
/**
 * Remove the specified resource from storage.
 *
 * @param  \App\OrganizationEmailDomain  $emailDomain
 * @return \Illuminate\Http\Response
 */
public function destroy(Request $request, OrganizationEmailDomain $emailDomain)
{
    $path = $request->path();

    $id = substr($path, strrpos($path, '/') + 1);

    $emailDomain = OrganizationEmailDomain::find($id);

    $emailDomain->delete();

    return redirect()->route('organizations.emaildomains.index',$request->query()['organization'])->withStatus(__("Organization's email domain successfully deleted."));
}

and now it works fine.


text:
Q: A is recursive iff A is the range of an increasing function which is recursive Working a problem stated in Enderton, but stated better and apparently stronger in Soare. All citations hereon are for Soare (1987). Would appreciate help on the proof. I know there has to be a more elegant proof than what I have attempted, assuming my proof is correct (it may not be).
The problem is stated as in the title of this post, on page 32 problem 1.19.
We are told, btw, that a function f is increasing when f(x) < f(x+1) for all x. I add a definition that Soare does not: we say f enumerates a set A iff A = {f(0), f(1), . . .}.
PROOF:
SUBPROOF 1: Left to right direction of "iff".
Let A be infinite, and recursive. Thus
$\rightarrow$ A and A* (read complement of A) are recursively enumerable (r.e. hereon) -- by complementation theorem 1.12, page 30.
$\rightarrow$ (A* = $\emptyset$) v (A = Range of f*, where f* is total, recursive) -- By listing theorem 1.8 page 29.
$\rightarrow$ (A = $\emptyset$) v (A = Range of f, where f is total, recursive) -- Ditto.
$\rightarrow$ A $\neq$ $\emptyset$ -- Since A is infinite by hypothesis
$\rightarrow$ A = Range of f s.t f is total and recursive -- disjunctive syllogism, previous two lines
$\rightarrow$ A = {f(0), f(1), . . .} -- A is the range of f
$\rightarrow$ Suppose A* = $\emptyset$
$\rightarrow$ A* is r.e.
$\rightarrow$ Suppose on the other hand A* $\neq$ $\emptyset$.
$\rightarrow$ A* = Range of f* for f* recursive, total. -- disjunctive syllogism, last line and second line.
$\rightarrow$ A* = {f*(0), f*(1), . . . } -- A* is the range of f*
Hence either way, there is an r.e. function which enumerates A, A*, so that A must be the range of a recursive f.
END SUBPROOF 1.
SUBPROOF 2: Right to left direction of the "iff".
Let A be infinite, and let f be a recursive function s.t. f is increasing, and let A = Range of f. Need to show A = {y : f(x) = y} forms a recursive set. To this end, suppose otherwise. Thus there is some y $\in$ A for which f is undefined, i.e. for arbitrary choice of x $\in$ A under f, y$\ne$ f(x). Hence y > f(x). But then f is increasing for all x, y $\in$ A, so that y = f(x + 1); contradiction.
Right?
END SUBPROOF 2.
END PROOF.


text:
Q: Definiteness of Negative Symmetric Matrix with Largest Values on the Diagonal. I have a symmetrix matrix, $M = M^T$ which has negative values everywhere i.e., $M_{i,j}<0$ for all $i, j$. Furthermore, I know that we have $M_{i, i} \leq M_{i, j} \forall i,j$ and additionally that  $M_{i, i} \leq M_{j, i} \forall i,j$ i.e., that the largest (most negative) values in each row and column are on the diagonal.
What can I say about the definiteness of $M$?
EDIT: the conditions I have above weren't quite what I had in mind. Let me rephrase, in the situation I mean.
I have $I$ features in a database, which counts how often each feature is active. The matrix $M$ has values:
$$
M_{i,j} = \begin{cases} -N_i,\quad i=j\\ -N_{i,j}\quad otherwise\end{cases}
$$
where $N_i$ is the number of days that $i$ is active and $N_{i,j}$ is the number of days that both $i$ and $j$ are active. I want to know whether this matrix is negative semi-definite.
This matrix satisfies the conditions above, but they aren't strict enough. For example,
$$
M = -\begin{bmatrix} 10 & 10 & 5 \\\ 10 & 10 & 10 \\\ 5 & 10 & 10\end{bmatrix}
$$
satisfies the conditions I mentioned above. However, it could not have been generated from data. The second row implies that every time the second feature is active, the first and third features are also active. The first row implies that the third feature is not always active if the first feature is second, which is a contradiction.
I'm not entirely sure how to encode this constraint, but I feel as though this matrix should come out to be negative semi-definite.

A: Let $D$ be the set of all days in the record and $A=(a_{id})$ be the matrix such that $a_{id}=1$ if feature $i$ is active on day $d$ or $a_{id}=0$ otherwise. Then $a_{id}a_{jd}$ is equal to $1$ if both features $i$ and $j$ are active on day $d$, or $0$ otherwise. It follows that $m_{ij}=-\sum_{d\in D}a_{id}a_{jd}$, i.e. $M=-AA^\top$. Hence $M$ is negative semidefinite.