text:
Q: Reading secrets from Kubernetes within Python based app I'm packaging a Python app for use within a Kubernetes cluster. In the code base this method exists :
   def get_pymongo_client(self):
        username = test;
        password = 'test';
        url = 'test
        conn_str = "mongodb+srv://" + username + ":" + password + "/"+ url

        return pymongo.MongoClient(conn_str)

I'm attempting to secure the username, password & URL fields so that they are not viewable within the src code. For this, I plan to use secrets.
The URL https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl/ details how to create a secret. But I'm not sure how to read the secret from the Python app.
.Dockerfile for my app:
#https://docs.docker.com/language/python/build-images/

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

Reading Python flask application access to docker secrets in a swarm details the use of secrets in a docker-compose file, is this also required for Kubernetes? What steps are involved in order to read secret parameters from the Python src code file?

A: The traditional way is via environment variable
spec:
  containers:
  - name: your-app
    # ...
    env:
    - name: PYMONGO_USERNAME
      valueFrom:
        secretKeyRef:
           name: your-secret-name-here
           key: PYMONGO_USERNAME

Or you can make that yaml less chatty by using a well-formed Secret and the "envFrom:" field
kind: Secret
metadata:
  name: pymongo
stringData:
  PYMONGO_USERNAME: test
  PYMONGO_PASSWORD: sekrit
---
spec:
  containers:
  - name: your-app
    envFrom:
    - secretRef:
        name: pymongo
    # and now the pod has all environment variables matching the keys in the Secret

and then your code would just read it from its environment as normal
   def get_pymongo_client(self):
        username = os.getenv('PYMONGO_USERNAME')
        password = os.getenv('PYMONGO_PASSWORD')
        # etc

An alternative, but similar idea, is to mount the Secret onto the filesystem, and then read in the values as if they were files
spec:
  containers:
  - name: your-app
    env:
    # this part is 100% optional, but allows for easier local development
    - name: SECRETS_PATH
      value: /secrets
    volumeMounts:
    - name: pymongo
      mountPath: /secrets
  volumes:
  - name: pymongo
    secret:
      secretName: your-secret-name-here

then:
   def get_pymongo_client(self):
        sec_path = os.getenv('SECRETS_PATH', './secrets')
        with open(os.path.join(sec_path, 'PYMONGO_USERNAME')) as fh:
            username = fh.read()


text:
Q: AttributeError: 'Programa' object has no attribute 'root' I'm looking to make a one-screen app. I have 3 text fields and a button. I can't get the values from the text fields.
this is my main.py file
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout

class Programa(MDBoxLayout):
    def calcular(self):
        print("O valor de soma é {}".format(self.root.ids.namee.text))

class TesteApp(MDApp):
    def build(self):
        pass

TesteApp().run()

this is my TesteApp.kv
Programa:

    MDGridLayout:
        cols: 1

        MDToolbar:
            title: "SDK Calc"
            left_action_items: [["menu", lambda x: app.callback()]]

        MDGridLayout:
            cols: 1
            padding: [22,32]

            MDTextField:
                id: soma
                hint_text: "Soma"

            MDTextField:
                hint_text: "Digitos"

            MDTextField:
                hint_text: "Exceção"

            MDFillRoundFlatIconButton:
                text: "Calcular"
                icon: "calculator-variant-outline"
                on_release: root.calcular()
                pos_hint: {"center_x": .5, "center_y": .5}

I'm getting the error.
   File "/python/kivymd/main.py", line 6, in calcular
     print("O valor de soma é {}".format(self.root.ids.namee.text))
 AttributeError: 'Programa' object has no attribute 'root'

What am I doing wrong?

A: To access with widgets from your App class, you need to use self.root.ids.blablabla..., but accessing your widgets in other classes and the story goes like this: you use self.ids.blablabla... instead:
class Programa(MDBoxLayout):
    def calcular(self):
        print("O valor de soma é {}".format(self.ids.namee.text))

Another note is that although my answer should be correct, you might wanna recheck your kivy code cuz I ain't seeing any widget named namee there (Of course if the namee is an example of how it doesn't work then it's fine)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove Text Horizontal Padding in SwiftUI There is extra horizontal padding for text in SwiftUI. This extra padding appears in some devices (canvas, simulator, and physical device) like iPhone 14 Pro, while it does not exist in other devices like iPhone 14 Pro Max (xCode Version 14.2). I'd like to have the text and H1 aligned leading. How can I remove the extra padding?
struct TestView: View {
    var body: some View {
        VStack {
            HStack {
                Text("H1")
                    .font(.custom("GillSans-bold", size: 18))
                Spacer()
                Image(systemName: "doc")
            }
            Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.")
                .font(.custom("GillSans", size: 18))
                .background(.cyan)

        }
        .background(.yellow)
        .padding()
    }
}

A: This is not a padding. The box of your text is aligned to the center by default and text can't be of exact with of the screen. So you probably want to do something like:
VStack (alignment: .leading) {
...
}

Also you could do the same trick that you did in the first line by adding Spacer in HStack which will push the text to the edge.


text:
Q: SOAP and Rest Webservice using Spring boot I'm developing my first Spring Boot application containing both Soap and rest webservice.  I've to pass Request in url as a parameter. I'm able to pass request in URL for Rest service. Is it possible to send request in URL for SOAP webservice?

A: Ok I am not sure what are your intentions but about SOAP.
---------------                      ----------------
|             |   someMethodInvoke   |              |
|  Your API   | -------------------->| WEB Service  |
|             |<-------------------- |              |
---------------    someResult        ----------------

Now attending a communication with a WS you need firstly to have the schema of that API or the .WSDL from which you can generate Objects with which you will make the calls you need.
I am personally am using JAXB for generating .java classes from schema.
After for the call it self org.springframework.ws.client.core.WebServiceTemplate is the thing that gets the job done. You can use marshalSendAndReceive.
For example:
public class SomeService extends WebServiceGatewaySupport {
     ObjectFactory oFactory = new ObjectFactory();

     public ExpectedResultObject someMethodInvoke(RequestObjectGeneratedFromSchema request){
            JAXBElement<ExpectedResultObject> response = (JAXBElement<ExpectedResultObject>) getWebServiceTemplate()
                .marshalSendAndReceive("http://yourURL.com", oFactory.createreRequestObjectGeneratedFromSchemaInputMessage(request));
            return response.getValue();
     }
}

Firstly extend the WebServiceGatewaySupport so you can invoke the getWebServiceTemplate() which return just exactly what you need : org.springframework.ws.client.core.WebServiceTemplate. Here is an example how you can use the WebServiceTemplate
Of course there are a lot of factors like security, connectivity and so on which maybe should be set. But that depends on the WS. But basicly that is all :

*

*Generate .java classes from WSDL(schema)

*Fill generated object with information

*Use some WebServiceTemplate for calling the END point

Hope I gave you some directions.


text:
Q: what exactly is the actual image data inside IDAT chunck in PNG file? PNG Specification here says PNG file contains a chunk IDAT which contains the actual image data.
My question is when I modify (using hex editor) LSB of any 1 byte in IDAT the whole image goes bad(colors changes randomly or image becomes transparent with some outline remaining or completely blank).
How just changing 1 byte can cause this?

A: It says exactly what's in there in the specification you linked. Did you consider reading the specification?


text:
Q: Binding progress bar to a service in JavaFX I am attempting to bind a progress bar to the progress of a service. I have created the progress bar in scene builder, and have attempted the below code. But the progress bar continually runs, and does not represent the service it is connected to. It should be running while the service is running, and representing the data being downloaded. How do I bind the progress bar to represent the service I have created.
@FXML
private ProgressBar ProgressBar;
service.start();
ProgressBar.progressProperty().bind(service.workDoneProperty());

A: You should bind ProgressBar's progressProperty() to Service's progressProperty() and not to its workDoneProperty i.e.
import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        ProgressBar progressBar = new ProgressBar();
        StackPane root = new StackPane(progressBar);
        Scene scene = new Scene(root, 200, 200);
        primaryStage.setScene(scene);
        primaryStage.show();
        Service service = new Service() {
            @Override
            protected Task createTask() {
                return new Task() {
                    @Override
                    protected Object call() throws Exception {
                        for(int i=0; i<100; i++){
                            updateProgress(i, 100);
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        return null;
                    }
                };
            }
        };
        progressBar.progressProperty().bind(service.progressProperty());
        service.start();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}


text:
Q: Generating all possibles combinations of values from a list of single values Basically, I want to generate truth table list of values using Python.
For instance, if I have the following values: [0, 1], I want the following list to be generated:
[(0, 0), (0, 1), (1, 0), (1, 1)]
If I want my table to have three inputs, then the following list should be generated:
[(0, 0, 1), (0, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 0), (1, 0, 1), (1, 1, 1)]
So:

*

*All permutations should be generated

*No duplicate permutation in the list

Right now my solution is the following but I find it heavy:
from itertools import permutations

number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = list(dict.fromkeys(list(permutations(set_of_values  * number_of_inputs, number_of_inputs))))

Do you have a better solution ? Such as a one-liner function call

A: It seems like product is enough:
number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = itertools.product(set_of_values, repeat=3)
print(*list_of_permutations)
# (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1)

A: does this work?
from itertools import permutations

number_of_inputs = 3
set_of_values = [0, 1]
result = set(permutations(set_of_values  * number_of_inputs, number_of_inputs)


text:
Q: How to find 90th% value? I have this list:
def grades = [5,4,3,2,1,1]

Where index is a grade, and value is an occurrence of the grade:

Grade
Occurrence

0
5

1
4

2
3

3
2

4
1

5
1

How can I calculate the 90th percentile for the grades?

A: A total of 16 grades have been given. 90% are 14.4 grades, so discard the lowest 14 grades and take the smallest remaining (in your example it will be 4).
How to code? There are some ways:

*

*You may count through the array you have got. Subtract 5 from 14 (= 9), then 4, then 3, then 2. Once you reach zero, you're at the index of the 90th percentile.

*Maybe easier to understand, but will require a few more code lines: Put all 16 grades into an array (or list): [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5]. Since the array is sorted, the median is found at index 14.

A: This gets me a whole grade. I was hoping to find an exact value of 90th percentile, but this will do for me.
def grades = [5,4,3,2,1,1]

sum=grades.sum()

per_grade=0
per_value=sum*0.9
 grades.eachWithIndex { grade_count, grade ->
  per_value-=grade_count
   if (per_value<0){per_grade=grade-1}
   if (per_value==0){per_grade=grade}
 }
out.write(per_grade)


text:
Q: Vue.js components internal state being reused when underlying data changes I am working on a medium size web application based on vue.js. I've been facing several virtual DOM issues mostly related to vue instances life cycle.
The following code snippet (jsFiddle also available here) demonstrates some of these problems. The test-component vue component receives a property value and updates its internal state using that value.
Whenever the data set changes (by sorting or by new data), the properties are updated, but the internal state is not. This is pretty easy to see by running the code snippet and clicking on the buttons.
I understand the data component attribute is a function and it looks like it is invoked only when the component is created. That kind of explains what is going on. The thing is I don't know how to achieve the intended behavior which is: all the children components internal state to be updated whenever the data source changes.

*

*Is there a life cycle callback that triggers when the component is
"refreshed"? I want a component refresh only callback. Do I need to watch for prop changes individually? That would be ugly.

*Is there a clean way to update the internal state when the props change?

*Is it possible to destroy all children components and force them to be recreated? I know this is not the best option but it would solve all my data binding problems :)

*How does vue decides when a component will be released or reused? In my example components go away when the data set size changes from 4 to 3, but the first 3 items internal state don't change so the first three items are being recycled.

Moving all the state to vuex would be a possible solution but some components are generic and I don't want them to contain knowledge about the vuex store details. Actually I am using vuex for most components, but for truly generic components I don't think it is a good option.

var testComponent = Vue.component('test-component', {
  template: '#component_template',
  props: ['prop1'],
  data: function(){
    return {
      internalState: this.prop1
    }
  }
})

new Vue({
  el: "#app",
  data: function(){
    return {
      items: [
        'Item 1',
        'Item 2',
        'Item 3'
      ],
      dataToggle: true,
      sorted: true
    };
  },
  methods: {
    sortDataSet: function(){
      if(this.sorted){
        this.items.reverse();
      } else {
        this.items.sort;
      }
    }
    ,changeDataSet: function(){
      if(this.dataToggle){
        this.items = ['Item 4', 'Item 5', 'Item 6', 'Item 7'];
      } else {
        this.items = ['Item 1', 'Item 2', 'Item 3'];
      }

      this.dataToggle = !this.dataToggle;
    }
  }
});

    Components internal state is not being updated

    <button v-on:click="changeDataSet">
      Change data
    </button>
    <button v-on:click="sortDataSet">
      Sort data
    </button>

        <test-component :prop1="item">
        </test-component>

A: Use a key.

It is recommended to provide a key with v-for whenever possible,
unless the iterated DOM content is simple, or you are intentionally
relying on the default behavior for performance gains.

    <test-component :prop1="item">
    </test-component>

Updated fiddle.


text:
Q: Using an iframe on asp.net mvc 3 to create an editor I am using an iframe on asp.net mvc 3 to create an editor. This is not working.
This is the javascript:
 $(document).ready(function () {
    document.getElementById('textEditor').contentWindow.document.designMode = "on";
    document.getElementById('textEditor').contentWindow.document.close();

    $("#save").click(function () {

    alert('ooosooooo');
    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");

    } else {
        $(this).addClass("selected");
    }

    on();

});

});

function on() {

var edit = document.getElementById("textEditor").contentWindow;
edit.focus();

//edit.document.execCommand('SaveAs', '1', 'e:\');
//edit.document.execCommand('foreColor', false, "#000000");
var ifi = document.getElementById('textEditor');
alert('ifi.innerHTML');
alert(ifi.innerHTML);

alert($("#textEditor").html());

//Trying to copy the content of text editor t hidden
//not working its always empty the textEditor
$("#hidden_field_id").val($("#textEditor").html());

edit.focus();
}

This is the html:
     @using (Html.BeginForm("Save", "Home", FormMethod.Post, new { enctype = "multipart/form-data", target="textEditor"}))
       {

      @*this is the iframe*@
      <iframe id="textEditor" name="textEditor" width="100%" height="500px"></iframe>
      <input type="hidden" id="hidden_field_id" name="hidden_field_id" value="ww"/>
      <input type="submit" id="save" class="save" value="send" />
       }

The problem is that when I insert text on the text editor when I press send/save the value copied from iframe to hidden is always empty "".

A: Try the following:
function on() {
    var edit = document.getElementById("textEditor").contentWindow;
    var html = $('body', edit.document).html();
    $("#hidden_field_id").val(html);
}

A: i did it like this :
function on() {

    edit.focus();

    var ifi = document.getElementById('textEditor');

    $("#hidden_field_id").val(ifi.contentWindow.document.body.innerHTML);

    edit.focus();
}

thanks
pedro


text:
Q: Calculate Sum of Several Rows and Create Bar Graph Excel I have a large set of values:
ID HOURS
29  9
29  9
29  8
29  9
29  10
29  9
29  9
29  7
29  9
29  9
29  8
29  10
29  8
29  9
29  9
29  8
29  9
29  10
29  9
29  9
29  8
29  6
29  9
29  9
29  6
29  9
29  8
29  9
29  9
29  8
29  9
29  9
29  8
29  9
29  9
29  9
29  8
29  10
29  9
29  7
29  10
29  8.5
29  8.5
29  7.5
29  7
29  6
29  9
29  8.5
29  10
29  9
29  8.5
29  9
29  9
29  8
29  8.5
29  8
29  9
29  8.5
29  8.5
29  10
29  8
29  7.5
29  7.5
29  7.5
29  9
29  7.5
29  9
29  10
29  10
29  8.5
29  7.5
29  8
29  8.5
29  9.5
29  7
29  9.5
29  9
29  8.5
29  8.5
29  7.5
29  8
29  8
29  8.5
29  9
29  8.5
29  9
29  9
29  8.5
29  9
29  10
29  9
29  8.5
29  9
29  7
29  9
28  7
28  8
28  9
28  8
28  7
28  9
28  9
28  9
28  8
28  9
28  9
28  8
28  9
28  9
... all the way to ID 1
There is a random number of hours for every ID, and I have to create a bar graph that sums up the values of each ID and displays them in a bar graph. I am very new to excel, how do I do this?

A: Say your id's are in column A, cells A1:A500, and your hours are in B1:B500.
Type out numbers 1-29 in a column, say in cells c1:c29. In cell D1, you can type =sumif($A$1:$A$500,C1, $B$1:$B$500).
Basically this sums the values in column B, if the values in column A equal C1.  Now you can drag the formula down for all 29 values.  From there, just graph.

A: You can also do this using a PivotChart.
Highlight the range of your data and choose Insert | PivotChart.
Choose a location for the chart.
Drag the ID field into the Axis Fields box and the Hours field into the ∑ values box.
You should get something like this.


text:
Q: Join Mysql statement issue I have two form drop-downs that capture two IDs, which relate to PKs from a table named nodes.
I want to delete those two nodes from within another table, named relationships.
So after I gather the 2 node IDs, I'm trying to delete the one node that is in a relationship with the other node.
In my relationship I have the id and goingto both as nodes, however only id is an FK and the other one isn't.
So how do I delete that if it is in a relationship?
Here is my attempt
$goingto = $_POST['id_one']; //get from form both from id in nodes
$id = $_POST['idtwo']; //get from form both from id in nodes

mysql> DELETE from relationships where $id = $goingto;

Here is my table structure:
nodes                 relationships
-----                 -------------
id int(11),           id int(11),
name varchar(35),     goingto int(11), //this is the destinationnode from the id relation
color varchar(7),     data varchar(0) null
type varchar (12),    Foreign key (id) references nodes(id)
Primary key (id)

engine = innodb

A: Do you think this is what you mean:
DELETE from relationships where id = $id and goingto = $goingto;


text:
Q: How to recursively create subfolder in each folder of a directory in CMD Let's say I have a directory called Grandparent
Inside this directory are multiple other folders, Parent 1, Parent 2, etc.. My goal is to create a new folder, Child, inside each of the Parent folders.
For example, what I have:
Grandparent/
    Parent1/
    Parent2/
    ...
    ...
    ParentX/

What I want:
Grandparent/
    Parent1/
        Child/
    Parent2/
        Child/
    ...
    ...
    ParentX/
        Child/

Is there a way to do this in CMD? (Note: I cannot download Powershell or any other convenient tool that would make my life easier, I am stuck with the default Windows Command Prompt)
Update
Following the links in the comments, I have tried the following:
for /r %%a in (.) do (
  rem enter the directory
  pushd %%a
  echo In Directory:
  mkdir testFolder
  cd
  rem leave the directory
  popd
)

However, this creates the folder testFolder in every newly created folder:
Grandparent/
    Parent1/
        Child/
            Child/
                Child/
                    ...
    Parent2/
        Child/
            Child/
                Child/
                    ...
    ...
    ...
    ParentX/
        Child/
            Child/
                Child/
                    ...
    Child/
        Child/
            Child/
                ...

A: However, this creates the folder testFolder in every newly created folder
This is because the for /r command is updating the list of files to process every time you create a new directory, so is really only useful if you want to visit a fixed list of directories.
Here is a batch file (test.cmd) that will do what you want. Place it in the Grandparent directory.
test.cmd:
@echo off
setlocal
for /f "usebackq tokens=*" %%a in (`dir /b /a:d`) do (
  rem enter the directory
  pushd %%a
  echo In Directory: %%a
  md child
  rem leave the directory
  popd
  )
endlocal

Notes:

*

*dir /b /a:d is evaluated once, so the list of directories is fixed

*for /f will loop through this fixed list exactly once.

Example output:
> test
In Directory: Documentation
In Directory: subdir
In Directory: test
In Directory: test with space
In Directory: test1

> dir /b /a:d /s child
F:\test\Documentation\child
F:\test\subdir\child
F:\test\test\child
F:\test\test with space\child
F:\test\test1\child

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*dir - Display a list of files and subfolders.

*for /f - Loop command against the results of another command.

*md - Make Directory - Creates a new folder.

*pushd - Change the current directory/folder and store the previous folder/path for use by the POPD command.

*popd - Change directory back to the path/folder most recently stored by the PUSHD command.


text:
Q: c# How to know what is user input choice? I'm really new to c#, just knowing the basics..
I can't seems to find any solution to my problem I've tried every possible google search query.
So here's what I'm trying to do:
I want to determined if 1 or 2 was pressed by the user.
 int action;
 Console.WriteLine("ACTIONS: Press 1 to do quest, Press 2 to access teleport");

I'm trying if else statement but I always getting

use of unsigned local variabled 'action'

A: You can parse the number by reading it. Like:
string stg = Console.ReadLine();
int i = Int.Parse(stg);
if(i == 1){
//some code
}
else{
//some other code
}

And the "error" you're getting is no error at all. The program is just saying that you've declared the integer type Action and has not used it.


text:
Q: Using basicHttpbinding and get the response in raw data I've looked all day and I couldn't able to find a correct answer on how get the response of my Web Service using basicHttpBinding without the SOAP formatting.
Can anyone know how to do that ? or another way for getting the raw data ? (like a string)

A: You have to use webhttpBinding. Look at the following articles, it might help you:

*

*Creating WCF Service with SOAP/REST Endpoints

*How to enable REST and SOAP both on the same WCF Service

*An Introduction To RESTful Services With WCF


text:
Q: Is TRIM enabled/supported for this eMMC? I have a compact SoC (System On a Chip) Dell laptop with the DF4032 SanDisk eMMC 32 GB storage device soldered to its only PCB, and there is no information concerning TRIM support for it anywhere. The file fstrim is present at /etc/cron.weekly/
#!/bin/sh
# trim all mounted file systems which support it
/sbin/fstrim --all || true

Running fstrim manually returns "30 GB ('N' bytes) trimmed" (apparently working, right?)
sudo hdparm -I /dev/mmcblk0 | grep "TRIM supported"

BUT the above command returns
HDIO_DRIVE_CMD(identify) failed: Invalid argument

So how else can I check if Ubuntu is performing TRIM out-of-the-box for this eMMC or if it even supports it? Would it be safe to include --no-model-check on the fstrim file? I would need to specify the /dev/mmcblk0 device so it would not mess with the SDHC card inserted. TRIM can be deadly for some not so popular devices.

A: TRIM does not work through USB, but usually, you get a message about "unsupported ioctl" when you run it on such a device (external USB disk enclosure).  Confirm that your mmcblk0 is really not on USB:
lsblk -o TRAN,SUBSYSTEMS,NAME,TYPE

My SD cards on mmcblk0 do not list a TRAN, but seem to appear under the USB branch since it follows a USB. However, adding the SUBSYSTEMS shows they are not on the USB. Probably there is not an issue with TRIM on your device if you get no errors or complaints. My output:
sata   block:scsi:pci         sdb       disk
       block:scsi:pci         sdb1      part
       block:scsi:pci         sdb2      part
       block:scsi:pci         sdb3      part
usb    block:scsi:usb:pci     sdc       disk
       block:scsi:usb:pci     sdc1      part
       block:mmc:mmc_host:pci mmcblk0   disk
       block:mmc:mmc_host:pci mmcblk0p1 part
       block:mmc:mmc_host:pci mmcblk0p2 part


text:
Q: Upadte ListView with data from FilePicker I'm triying to create a list of File from FilePicker and add them to a ListView.
I have UpdateInformationScreen who has a child DocumentPicker. And DocumentPicker has a child DocumentCard.
The ListView is updated with a delay, example if I validate 1 file it will not be visible in the list if I validate a second one, only the first one will be visible.
I am sure that the problem comes from an async but I don't know where exactly
UpdateInformationScreen:
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:app_test/utils/utils.dart';
import 'package:app_test/view/information_screen.dart';
import 'package:app_test/widget/document_picker.dart';
import 'package:app_test/widget/photo_picker.dart';
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:provider/provider.dart';

import '../constant/color.dart';
import '../constant/text.dart';
import '../model/instructor.dart';
import '../provider/instructor_view_model.dart';

class UpdateInformationScreen extends StatefulWidget {
  static const String ROUTE_NAME = "/updateInformation";

  const UpdateInformationScreen({Key? key}) : super(key: key);

  @override
  State<UpdateInformationScreen> createState() => _UpdateInformationScreenState();
}

class _UpdateInformationScreenState extends State<UpdateInformationScreen> {
  final firstNameController = TextEditingController();
  final phoneNumberController = TextEditingController();
  String? phoneNumber;
  File? photo;
  String? photoURL;

  //----------------------------------------------------------------------------------------------
  //----------------------------- Free memory allocated to the existing variables ----------------
  //----------------------------------------------------------------------------------------------

  @override
  void dispose() {
    firstNameController.dispose();
    phoneNumberController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final instructor = ModalRoute.of(context)!.settings.arguments as Instructor;

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pushNamed(context, InformationScreen.ROUTE_NAME);
          },
        ),
        title: const Text(appTitle),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 20,),
            PhotoPicker(
              onImageSelected: (image) {
                print("Selected image: $image");
                setState(() {
                  photo = image;
                });
              },
            ),
            const SizedBox(height: 20,),
            //----------------------------- First name -------------------------
            TextField(
              controller: firstNameController,
              cursorColor: cursorColor,
              textInputAction: TextInputAction.next,
              decoration: InputDecoration(
                prefixIcon: const Icon(
                  Icons.person,
                  color: grey,
                  size: 30,
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.grey),
                  borderRadius: BorderRadius.circular(5.5),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.orange),
                  borderRadius: BorderRadius.circular(5.5),
                ),
                labelText: instructor.firstName != null
                    ? instructor.firstName.toString()
                    : updateFirstnameText,
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            //----------------------------- Phone number -----------------------
            IntlPhoneField(
              controller: phoneNumberController,
              initialValue: instructor.phoneNumber != null
                  ? Utils.phoneNumberWithoutCountryCode(instructor.phoneNumber.toString())
                  : phoneSignInLabelText,
              decoration: InputDecoration(
                labelText: instructor.phoneNumber != null
                    ? Utils.phoneNumberWithoutCountryCode(instructor.phoneNumber.toString())
                    : phoneSignInLabelText,
                border: const OutlineInputBorder(
                  borderSide: BorderSide(),
                ),
              ),
              initialCountryCode: 'FR',
              onChanged: (phone) {
                phoneNumber = phone.completeNumber;
                print(phone.completeNumber);
              },
            ),
            const SizedBox(
              height: 20,
            ),
            const DocumentPicker(),
            const SizedBox(height: 20,),
            //----------------------------- Update button ----------------------
            ElevatedButton(
              onPressed: () async {
                await _updateInstructorPhoto(instructor.uid!, photo);
                _clickOnUpdateInformationButton(
                    instructor.uid!,
                    //----------------------------- Photo ----------------------
                    photoURL.toString().isEmpty || photo == null
                    ? instructor.photo
                    : photoURL,
                    //----------------------------- First name -----------------
                    firstNameController.text.isNotEmpty
                    ? firstNameController.text.trim()
                    : instructor.firstName,
                    //----------------------------- Phone number ---------------
                    phoneNumberController.text.isNotEmpty
                    ? phoneNumber!
                    : instructor.phoneNumber,
                );
              },
              style: ElevatedButton.styleFrom(
                fixedSize: const Size(double.infinity, 50),
                primary: cursorColor,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: Row(
                children: const [
                  Padding(
                    padding: EdgeInsets.only(left: 5, right: 100),
                    child: Icon(
                      Icons.update,
                      color: Colors.white,
                      size: 25,
                    ),
                  ),
                  Text(
                    updateInfoButton,
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  //----------------------------------------------------------------------------
  //----------------------------- Click on update information button -----------
  //----------------------------------------------------------------------------

  void _clickOnUpdateInformationButton(String uid, String? storagePhotoUrl, String? firstName, String? phoneNumber) {
    final instructorViewModel = Provider.of<InstructorViewModel>(context, listen: false);
    instructorViewModel.updateInstructor(uid, storagePhotoUrl, firstName, phoneNumber);
    print("Instructor:  \n"
        "uid: $uid \n"
        "photo: $storagePhotoUrl \n"
        "firstname: $firstName \n"
        "phone: $phoneNumber \n");
    print("Photo: ${photoURL.toString()}");
    Utils.goToInformationScreen(context);
    Utils.showSuccessMessage(updateInformationSuccessText);
  }

  //----------------------------------------------------------------------------
  //----------------------------- Update instructor photo ----------------------
  //----------------------------------------------------------------------------

  _updateInstructorPhoto(String uid, File? file) async {
    if(photo != null){
      await InstructorViewModel.uploadInstructorPhoto(uid, file!);
      await getUrlPhoto(uid);
    }
  }

  //----------------------------------------------------------------------------
  //----------------------------- Get instructor photo from Storage ------------
  //----------------------------------------------------------------------------

  getUrlPhoto(String uid) async {
    final instructorViewModel = Provider.of<InstructorViewModel>(context, listen: false);
    photoURL = await instructorViewModel.getInstructorPhotoUrl(uid);
  }
}

DocumentPicker:
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:g_conduite_instructor_test/provider/document_view_model.dart';
import 'package:path/path.dart' as Path;

import '../constant/color.dart';
import '../constant/text.dart';
import '../model/document.dart';
import 'document_card.dart';

class DocumentPicker extends StatefulWidget {
  const DocumentPicker({Key? key}) : super(key: key);

  @override
  State<DocumentPicker> createState() => _DocumentPickerState();
}

class _DocumentPickerState extends State<DocumentPicker> {
  final photoTitleController = TextEditingController();
  File? _file;
  User? user = FirebaseAuth.instance.currentUser;
  List<Document>? documents = [];
  late Document document;
  String extension = "";

  //----------------------------------------------------------------------------------------------
  //----------------------------- Free memory allocated to the existing variables ----------------
  //----------------------------------------------------------------------------------------------

  @override
  void dispose() {
    photoTitleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String fileName = _file != null ? Path.basename(_file!.path) : noFileSelectedText;
    print("Extension 1: $extension");

    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //----------------------------- Pick file from device --------------
            TextButton.icon(
              onPressed: () async {
                _clickOnAddFile();
              },
              icon: const Icon(
                Icons.download,
                size: 30,
                color: googleButtonTextColor,
              ),
              label: const Text(
                addFile,
                style: TextStyle(
                  fontSize: 18,
                  color: googleButtonTextColor,
                ),
              ),
            ),
            //----------------------------- Validate picked file ---------------
            TextButton.icon(
              onPressed: () async {
                await _clickOnValidate();
                _clearPhotoTitleTextField();
              },
              icon: const Icon(
                Icons.done,
                size: 30,
                color: googleButtonTextColor,
              ),
              label: const Text(
                validate,
                style: TextStyle(
                  fontSize: 18,
                  color: googleButtonTextColor,
                ),
              ),
            ),
          ],
        ),
        //----------------------------- Picked file default name ---------------
        Text(
          fileName,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: black,
          ),
        ),
        const SizedBox(height: 10,),
        //----------------------------- Picked file title ----------------------
        TextField(
          controller: photoTitleController,
          cursorColor: cursorColor,
          textInputAction: TextInputAction.next,
          decoration: InputDecoration(
            prefixIcon: const Icon(
              Icons.edit,
              color: grey,
              size: 30,
            ),
            enabledBorder: OutlineInputBorder(
              borderSide: const BorderSide(color: Colors.grey),
              borderRadius: BorderRadius.circular(5.5),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: const BorderSide(color: Colors.orange),
              borderRadius: BorderRadius.circular(5.5),
            ),
            labelText: fileTitleText,
          ),
        ),
        const SizedBox(height: 10,),
        //----------------------------- Show list of picked file ---------------
        //documents!.isEmpty ? const SizedBox(height: 0,) : _showFileList(),
        _showFileList(),
      ],
    );
  }

  //----------------------------------------------------------------------------
  //----------------------------- Pick file from device ------------------------
  //----------------------------------------------------------------------------

  Future _clickOnAddFile() async{
    final result = await FilePicker.platform.pickFiles(
        allowMultiple: false,
        type: FileType.custom,
        allowedExtensions: ["jpg", "jpeg", "png", "pdf"],
    );

    if(result == null) return null;

    final path = result.files.single.path!;
    extension = result.files.first.extension!;

    setState(() => _file = File(path));
  }

  //----------------------------------------------------------------------------
  //----------------------------- Validate picked file -------------------------
  //----------------------------------------------------------------------------

  Future _clickOnValidate() async {
    if(_file == null) return null;

    final fileName = photoTitleController.text.trim();
    final destination = "instructorDocuments/${user!.uid}/$fileName";

    document = Document(_file, fileName);
    documents?.add(document);

    if (documents != null) {
      for (var d in documents!){
            DocumentViewModel.uploadInstructorDocument(destination, d.documentPhoto!);
          }
    }
  }

  //----------------------------------------------------------------------------
  //----------------------------- Clear photo title text field -----------------
  //----------------------------------------------------------------------------

  _clearPhotoTitleTextField() {
    photoTitleController.clear();
  }

  //----------------------------------------------------------------------------
  //----------------------------- Add List of file from file picker -----------------
  //----------------------------------------------------------------------------

  /*Future<Widget>*/Widget _showFileList() /*async*/{
    return ListView.builder(
      itemCount: documents!.length,
      itemBuilder: (context, index) => DocumentCard(document: documents![index], extension: extension,),
      shrinkWrap: true,
      physics: const BouncingScrollPhysics(),
    );
    /*setState(() {
      ListView.builder(
        itemCount: documents!.length,
        itemBuilder: (context, index) => DocumentCard(document: documents![index], extension: extension,),
        shrinkWrap: true,
      );
    });
    return const SizedBox(height: 0,);*/
  }
}

DocumentCard:
import 'package:flutter/material.dart';
import 'package:app_test/model/document.dart';

import '../constant/color.dart';

class DocumentCard extends StatelessWidget {
  final Document document;
  final String extension;

  const DocumentCard({Key? key, required this.document,
    required this.extension}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("Extension 2: $extension");

    return Card(
      elevation: 5,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15.0),
      ),
      child: Row(
        children: [
          extension == "pdf"
          ? Image.asset(
              fit: BoxFit.cover,
              width: 100,
              height: 100,
              "assets/images/pdf.png",
          )
          : Image.file(
            fit: BoxFit.cover,
            width: 100,
            height: 100,
            document.documentPhoto!,
          ),
          const SizedBox(width: 20,),
          Text(
            document.photoTitle!,
            style: const TextStyle(
              fontSize: 16,
              color: black,
            ),
          ),
          const Spacer(),
          IconButton(
              onPressed: () {
                print("Delete icon clicked");
              },
              icon: const Icon(
                Icons.delete,
                color: red,
              )
          ),
        ],
      ),
    );
  }
}

Edit: I've tried this with the same result
 Future _clickOnValidate() async {
    if(_file == null) return null;

    final fileName = photoTitleController.text.trim();
    final destination = "instructorDocuments/${user!.uid}/$fileName";

    document = Document(_file, fileName);
    documents?.add(document);

    if (documents != null) {
      for (var d in documents!){
            DocumentViewModel.uploadInstructorDocument(destination, d.documentPhoto!);
          }
    }
  }

  //----------------------------------------------------------------------------
  //----------------------------- Get future document list ---------------------
  //----------------------------------------------------------------------------

  Future<List<Document>>? getDocumentList() async {
    print("Future selected list: $documents");
    return documents!;
  }

And added a FutureBuilder:
        //documents!.isEmpty ? const SizedBox(height: 0,) : _showFileList(),
        //_showFileList(),
        FutureBuilder<List<Document>>(
          future: getDocumentList(),
          builder: (context, future) {
            if(future.hasData) {
              List<Document>? selectedFilesList = future.data;
              print("Selected file list $selectedFilesList");
              return ListView.builder(
                itemCount: selectedFilesList!.length,
                itemBuilder: (context, index) => DocumentCard(
                   document: selectedFilesList[index],
                   extension: extension,
                ),
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
              );
            }
            else {
              return const SizedBox(height: 0,);
            }
          },
        ),

Thanks in advance

A: @Sayyid J thanks for the StreamBuilder suggestion, I've searched and found this:
How to add controller to streamBuilder?
So I've done this and it works
class _DocumentPickerState extends State<DocumentPicker> {
  final photoTitleController = TextEditingController();
  File? _file;
  User? user = FirebaseAuth.instance.currentUser;
  List<Document>? documents = [];
  late Document document;
  String extension = "";
  String destination = "";
  final FileListController fileController = FileListController(); <---------------------

  //----------------------------------------------------------------------------------------------
  //----------------------------- Free memory allocated to the existing variables ----------------
  //----------------------------------------------------------------------------------------------

  @override
  void dispose() {
    photoTitleController.dispose();
    fileController.controller.close(); <---------------------
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {}
}

FileController class:
class FileListController {
  final StreamController<List<Document>?> controller = StreamController<List<Document>?>.broadcast();

  Sink<List<Document>?> get inputFileList => controller.sink;
  Stream<List<Document>?> get outputFileList => controller.stream;
}

Add list in fileController:
Future _clickOnValidate() async {
    if(_file == null) return null;

    final defaultName = Path.basename(_file!.path);
    final fileName = photoTitleController.text.trim();
    destination = "instructorDocuments/${user!.uid}/$fileName";

    if(fileName.isEmpty) {
      destination = "instructorDocuments/${user!.uid}/$defaultName";
    }

    document = Document(_file, fileName);
    documents?.add(document);
    fileController.inputFileList.add(documents); <---------------------

    if (documents != null) {
      for(var d in documents!){
        DocumentViewModel.uploadInstructorDocument(destination, d.documentPhoto!);
      }
    }
  }

Add the StreamBuilder
StreamBuilder<List<Document>?>(
            stream: fileController.outputFileList,
            builder: (context, snapshot) {
              if(snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) => DocumentCard(
                    document: snapshot.data![index],
                    extension: extension,
                  ),
                  shrinkWrap: true,
                  physics: const BouncingScrollPhysics(),
                );
              }
              else {
                return const SizedBox(height: 0,);
              }
            },
        ),


text:
Q: Is it possible to type a variadic function in Haskell? Mind the following Haskell term:
callNTimes :: forall a . Int -> (a -> a) -> a -> a
callNTimes n f 0 = x
callNTimes n f x = f (callNTimes (n-1) f x)

firstOf :: ??????
firstOf n = callNTimes n (\ x y -> x)

If we ignore the types and normalize the functions by hand, firstOf is a function that receives an N, then N arguments, discards all but the first and returns it. firstOf 3 10 20 30 returns 3. Is it possible to type that function in GHC 8.0 with the new dependent typing features?

A: I finally managed to get a working version - it's not exactly what you asked for but it demonstrates what I was commenting about and I think it's quite close
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}

module Variadic where

data Z a = Z
data S t a = S (t a)

class Var n where
  type El n :: *
  type Res n :: *
  firstOf :: n -> El n -> Res n

instance Var (Z a) where
  type El (Z a) = a
  type Res (Z a) = a
  firstOf Z a = a

instance (El (n a) ~ a, Var (n a)) => Var (S n a) where
  type El (S n a) = a
  type Res (S n a) = a -> Res (n a)
  firstOf (S n) a _ = firstOf n a

here are a few examples:
λ> firstOf Z 5
5
λ> firstOf (S Z) 5 9
5
λ> firstOf (S (S Z)) 5 8 9
5
λ> firstOf (S (S Z)) "Hi" "World" "Uhu"
"Hi"

if you are interested in how I got there you can check the edit-history

remarks

*

*it uses the S and Z as a poor-mansreplacement* for type-level literals and you can probably get it working with this

*the version firstOf (S (S Z)) which you would expect to want 2 arguments is waiting for 3 - that's because I start with Z = 1 argument

*I just saw that you wanted firstOf 3 10 20 30 = 3 which this will not do (this will give 10) - which is probably doable with type-level literals and an obvious overload too

A: {-# LANGUAGE GADTs, DataKinds, TypeFamilies, TypeOperators #-}

type family Fun as b where
    Fun '[]       b = b
    Fun (a ': as) b = a -> Fun as b

data SL as where
    Sn :: SL '[]
    Sc :: SL as -> SL (a ': as)

constN :: SL as -> b -> Fun as b
constN  Sn    y = y
constN (Sc s) y = \_ -> constN s y

-- 1
main = print $ constN (Sc (Sc (Sc Sn))) 1 "a" [3] True

E.g. Fun [Int, Bool] [Int] = Int -> Bool -> [Int]. SL is a singleton that allows to lift lists to the type level. Pattern matching on SL as reveals that as is either [] or a:as. In the first case the goal has type Fun [] b which is just b. In the second case the goal has type a -> Fun as b, hence the lambda.

And a simple solution with just GADTs:
{-# LANGUAGE GADTs #-}

data T z a where
    Tz :: T z z
    Ts :: T z b -> T z (a -> b)

constN :: T z a -> z -> a
constN  Tz    y = y
constN (Ts s) y = \x -> constN s y

-- 1
main = print $ constN (Ts (Ts (Ts Tz))) 1 "a" [3] True


text:
Q: Why is additivity assumption in additive models unrealistic? Is it more unrealistic than the assumption of Linearity? I have gone through the following questions regarding the assumptions of additive models.
Assumptions of additive model
What does the additive assumption mean?
However, I do not quite get the intuitive understanding of why additive assumptions are regarded as unrealistic.
And how unrealistic is it? (if it's quantifiable)
Is it more unrealistic than the assumption of Linearity ?
Can anybody please demonstrate with a simple real-world example?

A: Suppose our inputs are $x\in\mathbb R^p$ and we are trying to model $y\in\mathbb R$ using a function $f : \mathbb R^p\to\mathbb R$.
An additive model is of the form
$$
f(x) = \beta_0 + \sum_{i=1}^m\beta_ih_i(x_i)
$$
so we're saying that $f$, our potentially complicated function of a $p$-dimensional input, is built out of functions only of each coordinate separately.
Note that if $h_i(x_i) = x_i$ then this reduces to a standard linear model, so additive models generalize linear models.
This is restrictive because we're missing so many possible functions, like if $y = x_1x_2$ we won't be able to exactly capture that. Any function that needs to simultaneously consider multiple coordinates of $x$ at once won't be exactly model-able with an additive function.
Another way to see why this is so restrictive is that once we fix our basis functions $\{h_1,\dots,h_m\}$ we are only considering functions in the span of this set, and that'll be at most an $m$-dimensional subspace of the probably infinite dimension function space that could contain the "true" function, so in that sense we have almost no chance of the true function being in our thin slice through this space that we're considering.


text:
Q: website access through IIS windows authentication and django I am setting up a website through IIS and Django. I would like to secure my IIS site so only the desired people can access it, in particular, I would like to rely on their windows credential within our network for authentication. To do that I have added IIS Windows Authentication and enabled it for the website through. I have also followed the django tutorial on adding REMOTE_USER definitions in settings.py. When I try to access the web site as a user on my network I get the following error:

OperationalError at
attempt to write a readonly database
Request Method:    GET
Request URL:   website address
Django Version:    2.2.3
Exception Type:    OperationalError
Exception Value:
attempt to write a readonly database
Exception Location:    >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383
Python Executable: >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\scripts\python.exe

please help me find the missing piece of the puzzle.
I am pretty new to Django and IIS and would appreciate the help
Python Version: 3.7.2
DJANGO version 2.23
IIS version: 10.0
Windows Server 2016

A: Took me a while to find the answer, and I would like to share in case people need it:
The root cause is that Django wants to add the remote user to django database but the user doesnt have access. You can give access through IIS to the website folder by selecting the "Users" group and select the Write option in the Permissions for Users box. Click Apply then OK, then again Apply and OK.


text:
Q: Laravel: Get the correct value of an enum field on a resource class I'm using PHP8.1 and Laravel 9 for a project in which I've got the following enum:
enum OrderStatuses : string
{
    case New           = 'new';
    case Pending       = 'pending';
    case Canceled      = 'canceled';
    case Paid          = 'paid';
    case PaymentFailed = 'payment-failed';

    public function createOrderStatus(Order $order) : OrderStatus
    {
        return match($this) {
            OrderStatuses::Pending       => new PendingOrderStatus($order),
            OrderStatuses::Canceled      => new CanceledOrderStatus($order),
            OrderStatuses::Paid          => new PaidOrderStatus($order),
            OrderStatuses::PaymentFailed => new PaymentFailedOrderStatus($order),
            default                      => new NewOrderStatus($order)
        };
    }

one of the classes listed in the enum looks like this:
abstract class OrderStatus
{
    public function __construct(protected Order $order)
    {
    }

    /**
     * Determines whether an order can transition from one status into another
     *
     * @return bool
     */
    abstract public function canBeChanged() : bool;
}

class PaidOrderStatus extends OrderStatus
{
    public function canBeChanged(): bool
    {
        return false;
    }
}

all others are basically the same, they just differ on the implementation of the canBeChanged method.
Now, I've got the following resource:
class OrdersResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => (string)$this->id,
            'type' => 'orders',
            'attributes' => [
                'status' => $this->status,
                'payment_type' => $this->payment_type,
                'payment_transaction_no' => $this->payment_transaction_no,
                'subtotal' => $this->subtotal,
                'taxes'  => $this->taxes,
                'total' => $this->total,
                'items' => OrderItemsResource::collection($this->whenLoaded('orderItems')),
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ]
        ];
    }
}

which is called from my controller like this:
return (new OrdersResource($order))
            ->response()->setStatusCode(ResponseAlias::HTTP_OK);

Before implementing the enum my resource was working correctly, it returned the expected data. But after the enum, it's returning [] for the status field.
A sample return is currently looking like this:
"id" => "86b4e2da-76d4-4e66-8016-88a251513050"
  "type" => "orders"
  "attributes" => array:8 [
    "status" => []
    "payment_type" => "card"
    "payment_transaction_no" => "3kaL92f5UwOG"
    "subtotal" => 3005.76
    "taxes" => 0
    "total" => 3005.76
    "created_at" => "2022-08-31T12:47:55.000000Z"
    "updated_at" => "2022-08-31T12:47:55.000000Z"
  ]
]

notice again the value for status.
I've got a casting and a attribute in my Order's model:
protected $casts = [
        'status' => OrderStatuses::class,
    ];

protected function status(): Attribute
    {
        return new Attribute(
            get: fn(string $value) =>
                OrderStatuses::from($value)->createOrderStatus($this),
        );
    }

Furthermore, if I dd the type of $this->status in the toArray method from OrdersResource it says that it is of type Domain\Order\Enums\PaidOrderStatus which is correct.
I tried adding __toString() to PaidOrderStatus class but had no luck. What am I missing?
Update
I've added a test() method to PaidOrderStatus:

class PaidOrderStatus extends OrderStatus
{
    public function canBeChanged(): bool
    {
        return false;
    }

    public function test() : string
    {
        return OrderStatuses::Paid->value;
    }
}

and then did:
public function toArray($request): array
    {
        return [
            'id' => (string)$this->id,
            'type' => 'orders',
            'attributes' => [
                'status' => ($this->status)->test(),
                'payment_type' => $this->payment_type,
                'payment_transaction_no' => $this->payment_transaction_no,
                'subtotal' => $this->subtotal,
                'taxes'  => $this->taxes,
                'total' => $this->total,
                'items' => OrderItemsResource::collection($this->whenLoaded('orderItems')),
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ]
        ];
    }

and that gave me:
[
  "id" => "8a2d6024-a63f-44ba-a145-cede2ecf3aaa"
  "type" => "orders"
  "attributes" => array:8 [
    "status" => "paid"
    "payment_type" => "card"
    "payment_transaction_no" => "kC9upaoGb2Nd"
    "subtotal" => 657.26
    "taxes" => 0
    "total" => 657.26
    "created_at" => "2022-08-31T13:17:25.000000Z"
    "updated_at" => "2022-08-31T13:17:25.000000Z"
  ]

and that worked. But it's a very hacky solution and I'd like to do better.

A: I'm sure you've already solved this as it's been months ago, but first you don't need the Attribute mutator as you have already defined the cast which will correctly map the string value to the right enum case.
Then in the resource, you just get the value from the enum like so.
'status' => $this->status->value,


text:
Q: Firefox cache in C# In my ASP site there's a function for upload images and display upload image in data grid view  but my problem is when we upload image and replace later one it's doesn't appear change in data grid without reload page.but this problem doesn't occured  in google chrome .

A: Your image will likely be getting cached on the browser. try either

*

*forcing it to have a different url every time its updated

*adding a last modified header to your response to the image request, that is the the write time of the file.


text:
Q: Convert htaccess to nginx, seek solution I have this nginx setup on all my websites. If I change this too much, usually the website does not work. The problem now is that I have a website that I bought with an htaccess file. I tried to convert using online converters, but nothing works...
MY NGINX CONFIG
server {
    server_name doutor.pt www.doutor.pt;

    access_log   /var/log/nginx/doutor.pt.access.log;
    error_log    /var/log/nginx/doutor.pt.error.log;

    root /var/www/doutor.pt/htdocs;
    index index.php index.html;

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

    location ~ .php$ {
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
    }

}

HTACCESS:
################################
#         MAIN SETTINGS        #
################################

# Remove index
Options -Indexes

# Set directory indexes
DirectoryIndex index.html index.php under-construction.html parking-place.html

################################
#       APACHE REWRITES        #
################################

RewriteEngine On

# Domain page parser for sitemap
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^sitemap-doctors-([0-9]+).xml$ index.php?page_name=sitemap&category=doctors&page=$1 [L,QSA]

# Domain page parser for sitemap
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^sitemap-doctors.xml$ index.php?page_name=sitemap&category=doctors&page=0 [L,QSA]

# Domain page parser for sitemap
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^sitemap.xml$ index.php?page_name=sitemap [L,QSA]

# Domain page parser for category
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^category/([0-9]+)-([^/]+)$ index.php?page_name=doctors&category=$1 [L,QSA]

# Domain page parser for doctor page
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^medico/([^/]+)$ index.php?page_name=medico&doctor_url=$1 [L,QSA]

# Domain page parser for secondary level pages
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)$ index.php?page_name=$2&page_category=$2 [L,QSA]

# Domain page parser for regular pages
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !sitemap$
RewriteRule ^([^/]+)$ index.php?page_name=$1 [L,QSA]

################################
#            CUSTOM            #
################################

A: Nginx is a beautiful thing and enables almost all the time to use a location block instead of a potentially hard to follow/understand/debug rewrite. This htaccess files converts easily and i've tested a bit of it's output (result) a little while back when i was asked if i could help on some other site.
As Richard's code shows, apache's weird negative logic -d and -f translate easily to a try_files $uri $uri/ in nginx where you check the request uri against web root path.
The directory indexing is disabled by default in nginx so one must enable it to use it... nothing to add is better than (again) apache's weird negative logic. Here's what the index would look like...
index index.php index.html under-construction.html parking-place.html;

Here's what the sitemap rewrite translate to, from my understanding:
 # If the URI is bang on /sitemap.xml
 location = /sitemap.xml {
     try_files $uri $uri/ /index.php?page_name=sitemap;
 }

 # If the URI is bang on /sitemap-doctors.xml
 location = /sitemap-doctors.xml {
     try_files $uri $uri/ /index.php?page_name=sitemap&category=doctors&page=0;
 }

 # Enclosing this in the ~* /sitemap block isn't mandatory but it only
 # helps creating cleaner, readable code while also making sure we contain
 # all /sitemap*s requests thus taking care of the !sitemap directive.

 location ~* /sitemap {
     location ~ ^/sitemap-doctors-([0-9]+).xml {
         try_files $uri $uri/ /index.php?page_name=sitemap&category=doctors&page=$1;
     }
 }

Following the same logic, the next one in line would look something like this:
# It seems we are only using the first capture group ( $1 ) here so the
# regex could be modified for something simpler but to make sure we are
# not catching stuff we don't want, leaving this precision will save troubles

location ^/category/([0-9]+)-([^/]+)$ {
    try_files $uri $uri/ /index.php?page_name=doctors&category=$1;
}

Again, for more of the same...
 # The ^ and $ are regex delimiters for start and end, so you know...

 location ^/medico/([^/]+)$ {
     try_files $uri $uri/ /index.php?page_name=medico&doctor_url=$1;
 }

Now that we got rid of all precise stuff, it's time for some generic uri catching and passing to php...

I'm thinking this htaccess isn't proper... I would love to get an explanation..

This here sends the capture block ( $2 ) twice which in my opinion is really unusual and doesn't make sense. That being said, without seeing it in action or looking at the source code, it's a tricky one...
 RewriteRule ^([^/]+)/([^/]+)$ index.php?page_name=$2&page_category=$2 [L,QSA]

a url of http://hungry.man/delicious/pizza would be seen to php as http://hungry.man/index.php?page_name=pizza&page_category=pizza without any reference to it being delicious...
For what's left i would be tempted to just use a @rewrite and write thoses as they are, without challenging my brain too much about it.
Hope it helps, Mat

A: It seems to me that the .htaccess file is trying to do something like this:
location / {
    try_files $uri $uri/ @rewrite;
}
location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
}
location @rewrite {
    rewrite ^/sitemap-doctors-([0-9]+).xml$ /index.php?page_name=sitemap&category=doctors&page=$1 last;
    rewrite ^/sitemap-doctors.xml$ /index.php?page_name=sitemap&category=doctors&page=0 last;
    rewrite ^/sitemap.xml$ /index.php?page_name=sitemap last;
    rewrite ^/category/([0-9]+)-([^/]+)$ /index.php?page_name=doctors&category=$1 last;
    rewrite ^/medico/([^/]+)$ /index.php?page_name=medico&doctor_url=$1 last;
    rewrite ^/([^/]+)/([^/]+)$ /index.php?page_name=$2&page_category=$2 last;

    rewrite ^/([^/]+)$ /index.php?page_name=$1 last;

    # some default action???
    return 404;
}

The main difference between rewrites in Apache and nginx, is that the latter requires the leading / on URIs. I have not implemented the RewriteCond %{REQUEST_URI} !sitemap$ rule or implemented a final default action. You will need to determine what works: return 404 or rewrite everything to /index.php.


text:
Q: "org.hibernate.PropertyNotFoundException: Could not find setter" for an associated object I have the following method where I want a User object with a few fields i.e. name, address.country and a few more.
I am trying to get the the country data in the list but cannot (only name data appears).
public List<User> getActiveUsers() {
    Criteria userCriteria = getSession().createCriteria(User.class, "user")
    .createAlias("address", "address");

    userCriteria.setProjection(Projections.projectionList().add(Projections.property("name"), "name").add(Projections.property("address.country"), "country"));
    userCriteria.setResultTransformer(Transformers.aliasToBean(User.class));

    return userCriteria.list();
}

snippet of People.hbm.xml file
<class name="model.People" table="PEOPLE">
    <id column="PEOPLE_ID" name="id" type="long">
        <generator class="native" />
    </id>

    ....

    <joined-subclass extends="model.People" name="model.User" table="USER">
        <key column="PEOPLE_ID" />
        <many-to-one class="model.BusinessAddress" column="ADDRESS_ID" name="address" />
    </joined-subclass>
</class>

java pojo's
public class User extends People implements Serializable {
    //other fields
    protected BusinessAddress address = new BusinessAddress();
}

public class BusinessAddress extends Address implements Serializable {
    //other fields
}

public abstract class Address implements Serializable {
    //other fields
    public String country;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Error stacktrace:
org.hibernate.PropertyNotFoundException: Could not find setter for country on class model.User
 at org.hibernate.property.ChainedPropertyAccessor.getSetter(ChainedPropertyAccessor.java:67)
 at org.hibernate.transform.AliasToBeanResultTransformer.initialize(AliasToBeanResultTransformer.java:118)
 at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:81)
 at org.hibernate.loader.criteria.CriteriaLoader.getResultColumnOrRow(CriteriaLoader.java:158)
 at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:647)
 at org.hibernate.loader.Loader.doQuery(Loader.java:745)
 at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270)
 at org.hibernate.loader.Loader.doList(Loader.java:2449)
 at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2192)
 at org.hibernate.loader.Loader.list(Loader.java:2187)
 at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
 at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706)
 at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
 at dao.PeopleDAO.getActiveUsers(PeopleDAO.java:100)
 .....

country is part of address and not User. I cannot get it to find address. Any help would be appreciated.
Also, the hibnernate query when show_sql = true shows the sql to be correct

A: I saw this solution originally
Populate child bean with Transformers.aliasToBean in Hibernate
but it was for Hibernate4 where I am using Hibernate3 so I did not pursue it further.
However I was still looking for a solution so I thought to see if I could recreate hibernate4 classes, which as it turns out you can.
I created AliasToBeanNestedResultTransformer.java from the link
and then this one
https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/transform/AliasedTupleSubsetResultTransformer.java
and then this one
https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/transform/TupleSubsetResultTransformer.java
The classes then compiled and seemed to work fine.
However, my final solution is to actually use Hibernate Search


text:
Q: How do I turn off email notifications when transferring ownership? I am setting up an api and need to change the ownership of some files in my drive from my service account to my non-service account. How do I turn off the email notifications? I've tried via both Python as well as via the docs (at the bottom of the page). The emails are getting really annoying.
new_permission = {'value': 'me@example.com', 'type': 'user', 'role': 'owner', 'sendNotificationEmails':'false'}
self.service.permissions().insert(fileId=self.doc['copied']['id'], body=new_permission, sendNotificationEmails='false').execute()

A: As @Grant mentions in the comment, use the boolean false rather than the string 'false'.
Since you are changing the owner of a documentation, sendNotificationEmails is ignored, as per the documentation:

Whether to send notification emails when sharing to users or groups.
  This parameter is ignored and an email is sent if the role is owner.
  (Default: true)


text:
Q: Custom directive with dynamic field name in ng-repeat I am creating reusable custom directive in angularjs where I am looking to pass fieldName for ng-repeate items as attribute. All my scope is isolated
My part of directive codes as below

       {{item.City}}

In above code I am passing fieldName hard code but I want to pass City (i.e. field name) by attribute
of my custom directive
<custom-select items="deptStations" drop-down-field="City"></custom-select>

in above items are passed by http service from controller
.controller('Ctrl', function($scope, $http) {
  $http.get("http://www.xxxx.com/_api/lists/getbytitle('XXX')/items?$select=Id,City_Code,City&$filter=Active eq 1&$orderby=City asc", {
    headers: {
      Accept : "application/json;odata=verbose"
    }
  }).then(function(resp) {
    $scope.deptStations = resp.data.d.results;
  }, function (err) {
    console.log(err);
  });
});

So idea over here is that I want to pass drop-down-field and I want to pass in my directive. Is it possible, if yes then how ?

A: i think below code will solve your problem
angular.module("module").directive("customSelect", function(){
  return{
    scope : {
      dropDownField : '@',
      items : '='
    };
  };
});

       {{item[dropDownField]}}


text:
Q: Programmatically Creating UILabel I know this should be very simple, but I've been really struggling with creating a UILabel programmatically and getting it to behave the way I would like.
All I want is to be able to create a label, set the maximum attributes as far as height, width and font size, and then have the text get smaller AND/OR just truncate the text to accommodate long strings of text.
Let's say that I want my label to have text that has a maximum width of 380, a maximum height of 20 and a maximum font size of 12.
So here is what I have attempted to do to create such a label:
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, 0, 0)];
fromLabel.text = [self fromSender];
fromLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = YES;
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.size = [fromLabel.text sizeWithFont:fromLabel.font constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
fromLabel.minimumScaleFactor = MIN_SCALE_FACTOR;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

Ok, so the label appears, but the text is larger than 12 and the height always comes out to be 21!? Even if I change the height and text size values to extreme sizes, this code creates a label of some fixed size that can't be adjusted. The only thing I can seem to make smaller is the width.
I must be over looking something basic, but I really can't figure out how to get my desired result, nor do I understand why I'm getting the behavior that I am getting.

A: here is how to create UILabel Programmatically..
1) Write this in .h file of your project.
UILabel *label;

2) Write this in .m file of your project.
label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:@"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice.

A: Does the following work ?
UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.
edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0).
Small change on the baselineAdjustment value too.

A: Swift 3:
let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)

A: UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

A: UILabel *lbl1 = [[UILabel alloc] init];
/*important--------- */lbl1.textColor = [UIColor blackColor];
[lbl1 setFrame:position];
lbl1.backgroundColor=[UIColor clearColor];
lbl1.textColor=[UIColor whiteColor];
lbl1.userInteractionEnabled=NO;
lbl1.text= @"TEST";
[self.view addSubview:lbl1];

A: In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

A: For swift
var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)

A: UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
mycoollabel.text=@"I am cool";

// for multiple lines,if text lenght is long use next line
mycoollabel.numberOfLines=0;
[self.View addSubView:mycoollabel];


text:
Q: UIImageView focus effect Does anybody know how to add focus effect to UIImageView so background will be a little bit blurred. Below is an example image

Image Source: http://cdn-media-2.lifehack.org/wp-content/files/2011/09/focus1.jpg

A: You should UIBlurEffect.
var vEffect = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
vEffect.frame = imageView.bounds
imageView.addSubview(visualEffectView)

A: Found this one in GitHub. "You can use blur effect and it's animation easily to call only two methods."
https://github.com/marty-suzuki/SABlurImageView

A: Hi i just developed one demo project using CLImageEditor in Objective-C. You can download my demo for your use from https://github.com/nitingohel/NGFocusView
RunTime output is:


text:
Q: Vue.js inside Chrome extension Content script I am trying to use Vue.js 3 inside a content script of a chrome extension.
Here I create the element on the rendered webpage (eg. google.com):
content-script.js
let element = document.querySelector('h1#title')
element.insertAdjacentHTML('afterend', '
COUNTER: {{counter}}
');

Here I create the Vue app:
import { createApp } from 'vue'

const CounterApp = {
    data() {
      return {
        counter: 0
      }
    },
    mounted() {
      setInterval(() => {
        this.counter++
      }, 1000)
    }
}

createApp(CounterApp).mount('#counter')
console.log(CounterApp)

but in the webpage it displays COUNTER: {{counter}} without actually filling the content.
In the console:

{template: "↵                    Counter: {{ counter }}↵
", __props: Array(0), __emits: null, data: ƒ, mounted: ƒ}

A: I can't test this in a chrome app context but I think this should solve your problem of getting the Vue variable to render.
The template needs to be with the Vue code, rather than with the content script code. By the time it is inserted into the DOM it is too late for Vue to interpolate your this.counter value.
content-script.js
In the content script just append the empty #counter div
let element = document.querySelector('h1#title')
element.insertAdjacentHTML('afterend', '

');

Vue app
Then in the app code add a .render() function to interpolate the value into your string (and turn it into a VNode with h())
render () {
  return h(tag, props, stuffToRender)
}

So if you wanted to render a
 tag with your interpolated string template COUNTER: {{ this.counter }} in it, try:
import { createApp, h } from 'vue' // <-- don't forget to import h

// If you have local import failure, try import via CDN url, like:
//import { createApp, h  } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'

const CounterApp = {
  data() {
    return {
      counter: 0
    }
  },
  mounted() {
    setInterval(() => {
      this.counter++
    }, 1000)
  },
  render() {
    return h('p', {}, `COUNTER: ${this.counter}`)
  }
}

createApp(CounterApp).mount('#counter')

More information on the render() function: vuejs.org


text:
Q: pymc unexpected model output I'm trying to use PyMC to determine the distribution of ad click through rates (CTRs). Let's say we have 1000 ads and I have measurements for clicks and views for all ads. I assume that underlying distribution of the ad CTRs is a Beta distribution, and I would like to use PyMC to estimate the parameters of this distribution. I will call these parameters in the following snippets unknown_alpha and unknown_beta.
To show my example code, here is how one could generate an example test set:
from scipy.stats import beta
from scipy.stats import geom
from scipy.stats import binom

def generate_example_data(data_size=1000, unknown_alpha=30, unknown_beta=100):
    ctrs = beta.rvs(a=unknown_alpha, b=unknown_beta, size=data_size)

    data_views = geom.rvs(0.001, size=data_size)
    data_clicks = []
    for ctr, views in zip(ctrs, data_views):
        data_clicks.append(binom.rvs(p=ctr, n=views))

    return data_views, data_clicks

And here is the code, how I tried to use PyMC:
import pymc

def model(data_views, data_clicks):
    ctr_prior = pymc.Beta('ctr_prior', alpha=1.0, beta=1.0)
    views = pymc.Geometric('views', 0.01, observed=True, value=data_views)
    clicks = pymc.Binomial('clicks', n=views, p=ctr_prior, observed=True, value=data_clicks)

    model = pymc.Model([ctr_prior, views, clicks])

    mc = pymc.MCMC(model)
    mc.sample(iter=5000, burn=5000)

    return mc.trace('ctr_prior')[:]

views, clicks = generate_example_data()
model(views, clicks)

Output:
array([ 0.])
I know that the model is not finished, yet, to infer about unknown_alpha and unknown_beta, but I don't know why I just get array([ 0.]). I expected to get a trace with 5k elements.
Can anybody explain me where I went wrong?
Cheers!

A: My guess would be the mc.sample(iter=5000, burn=5000) line. You sample for 5000, and throw away the first 5000. To keep 5000, you want mc.sample(iter=10000, burn=5000)


text:
Q: Display mysql data for Current Week in 7 day calendar I need a guiding hand, how do I display the " current week" starting on Monday , in a 7-day calendar by a 7-room grid, for a small theatre I volunteer at, various voluntary town groups use the rooms.
My database name=rooms, table=roomdiary, it has 7 fields (field_1 to Field_7).
I can populate each day with data from the dbase using the "Select" query & php isset code where required.
But I am stumped on how to correctly display only " current week " data in the right room on right day.
>
////// Mon... Tues . Wed .. Thu .. Fri . Sat .. Sun
room 1 data . data . data . data . data  data . data
room 2 data . data . data . data . data  data . data
room 3 data . data . data . data . data  data . data
room 4 data . data . data . data . data  data . data
room 5 data . data . data . data . data  data . data
room 6 data . data . data . data . data  data . data
room 7 data . data . data . data . data  data . data

I apologise for having not posted any code, as I thought any generic advice would be more than helpful and help me learn. Any guidance would be appreciated.

A: I recommend you split this problem in two

*

*Calculate start of display period (="Which date is the current Monday")

*Select and display your records

The first point is quite easy using PHP's date() or getdate() functions, the second can be achieved by SELECT ... WHERE datecolumn BETWEEN monday_date AND sunday_date.
This helps modularize your program: What if you want to add future display options? What if your theater decides not to play on mondays?
Additionally I recommend against harcoding your 7 rooms into 7 fields: A relational approach would have a "rooms" table (currently with 7 rows) and a "performances" table linking a room and a date. If you add a "programs" table and also link it to the "performances" table, you already get the program data for free.

A: *

*Redesign Your database, make table rooms (room_id, room_name) and table schedule (room_id, date, data, week_nr, year)

*Always write with date also week_nr to database - date('W', timestamp)

*If you don't want to store week_nr in database, then try strtotime('Last monday', timestamp) and strtotime('Next sunday', timestamp) and select range from database dates


text:
Q: How to getting file from FTP server and convert into a file for attachments? The scenario is getting a file from ftp server and sending as attachment in email.
I want to getting files from FTP server using "org.apache.commons.net.ftp.FTPClient"
about connection,filename success. but i don't know how to convert into File correctly.
here's my code :
FTPClient ftp = new FTPClient();
byte bytes[]=new byte[1024];
int read = 0;

//connection,filename --success

 StringBuffer str = new StringBuffer("MyFiles");
      str.append("-XYZ-");
      str.append(new SimpleDateFormat("ddMMyyyy").format(new Date()));
      str.append(".pdf");
      System.out.println("getting file --> "+str.toString());
 System.out.println("getting stream ftp -->"+ ftp.retrieveFileStream(str.toString()));

InputStream input = ftp.retrieveFileStream(str.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((read = input.read(bytes)) != -1) { --> null pointer line 503
   out.write(bytes,0,read);
 }
File temp = null;
temp = new File(str.toString());
Utils.convertByteArrayToFile(temp, out.toByteArray());

public static void convertByteArrayToFile(File outputFile, byte[] inputArray) throws IOException{
    BufferedOutputStream bos=null;
    try{
        FileOutputStream fos=new FileOutputStream(outputFile);
        bos=new BufferedOutputStream(fos);
        bos.write(inputArray);
    }finally{
        if(bos!=null){
            try{
                bos.flush();
                bos.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

And the result is..
getting file --> MyFiles-XYZ-17012013.pdf
getting stream ftp --> org.apache.commons.net.io.SocketInputStream@409db838
java.lang.NullPointerException
    at com.java.EmailForm.sendEmail(EmailForm.java:503)
Any ideas ?
Thanks
MRizq

A: Better you can use method RetrieveFile.
File localFile = new File("/path/XYZ-17012013.pdf");
FileOutputStream fout = new FileOutputStream(localFile);

boolean success = fTPClient.retrieveFile(ftpServerFilePath, fout);

if (success) {
    fout.flush();
    fout.close();
} else {
    System.out.println("Retrieve failure");
}

A: Looks like you are getting an input stream back from the FTPClient, so that can't be the cause of the null pointer. My guess is you've forgotten to initialize the byte array bytes and it's null.
Also, unless you need to store it elsewhere, you might not need to actually dump the contents of the input stream to a file before using it as an attachment. You can probably create it directly from the binary data in memory.


text:
Q: Nested routing with nested modules I am working on an Angular 2 app for the first time.
I have routing similar to this -
/home
/projects/
/projects/:id/members
/projects/:id/members/:id/tasks

From all the references, tutorials and articles I could find on the internet. I only found approach similar to this -
[
  {
    path: "home", component: HomeComponent
  },
  {
    path: "", redirectTo: "home", pathMatch: "full"
  },
  {
    path: 'projects',
    component: ProjectComponent,
    children: [
      {
        path: ':id',
        component: ProjectDetailsComponent,
        children: [
          {
            path: 'members',
            component: MemberComponent,
            children : [
              {
                path: ':id',
                component : MemberDetailsComponent,
                children : [
                  {
                    path: 'tasks',
                    component : TasksComponent
                  }
                ]
              }
            ]
          },
        ]
      }
    ]
  }
]

This works well. However, I feel, this is sort of strictly typed approach and can create when there are a lot of components in place.
I have created feature modules called ProjectModule, MemberModule, TaskModule. There will be several more modules under ProjectModule too..
What is the best way to have nested routes in place in such scenario? The lazy loading sort of works but url appears like http://localhost/members/ instead of http://localhost/projects/12/members even though members is under loadChildren.

A: try below,
Check this Plunker
App Routes
 const appRoutes: Routes = [
  { path: '',   redirectTo: '/home', pathMatch: 'full' },
  { path: 'home',  component: HomeComponent },
  {
    path: 'projects',
    loadChildren: 'app/project.module#ProjectModule'
  }
];

Project Module Routes
const projectRoutes: Routes = [
  {
     path: '',
     component: ProjectComponent ,
      children: [
      {
        path: ':id',
        component: ProjectDetailsComponent,
        children:[
           {
            path: 'members',
            loadChildren: 'app/member.module#MemberModule'
           }
        ]
      }
    ]
  }
];

Member Module Routes
const memberRoutes: Routes = [
  {
     path: '',
     component: MemberComponent,
      children: [
      {
        path: ':id',
        component: MemberDetailsComponent
      }
    ]
  }
];

Hope this helps!!


text:
Q: Add an array field to a user database in Rails I have an app that has a search box where you input a Twitter username and it returns the recent mentions of that user. https://hurrier-app.herokuapp.com/
Some tweets have an image associated with them. I need to be able to "favourite" an image and then be able to view all of them on a separate page.
I am very new to Rails so I was thinking of adding an array fav_pics to the user model and appending each photo's url to it upon favouriting it. not sure where to start.
here's my user.rb
class User < ActiveRecord::Base
  def self.from_omniauth(auth)
    user = where(provider: auth.provider, uid: auth.uid).first || create_from_omniauth(auth)
    user.oauth_token = auth["credentials"]["token"]
    user.oauth_secret = auth["credentials"]["secret"]
    user.save!
    user
  end

  def self.create_from_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["nickname"]
    end
  end

  def twitter
    if provider == "twitter"
      @twitter ||= Twitter::Client.new(oauth_token: oauth_token, oauth_token_secret: oauth_secret)
    end
  end

  has_many :fav_pics
  has_many :pics_favorited,
    class_name: 'Pic',
    through: :fav_pics

end

class FavPic < ActiveRecord::Base
  belongs_to :user
  belongs_to :pic
end

class Pic < ActiveRecord::Base
  has_many :fav_pics
  has_many :fav_users,
    class_name: 'User',
    through: :fav_pics
end

now how do I actually handle the "favourite" event? I have experience with Meteor (javascript) but I am not sure how to handle events in Rails. Any resource links would be much appreciated.

A: That's the right idea. What you're describing is a join relationship, where to models are related by a third that pairs them.
For example:
class User
  has_many :fav_pics
  has_many :pics_favorited,
    class_name: 'Pic',
    through: :fav_pics
end

class FavPic
  belongs_to :user
  belongs_to :pic
end

class Pic
  has_many :fav_pics
  has_many :fav_users,
    class_name: 'User',
    through: :fav_pics
end

That's generally the key here. Normally the middle table has a compound index on user_id and pic_id with a UNIQUE constraint so people can't favorite twice.
Using array-type columns, especially when they're not natively supported by your database, becomes extremely expensive and difficult to work with. Manipulating them requires re-writing the entire user record, so as people favorite more images the cost of an update increases. Likewise, finding all users that have favourited an image is computationally expensive to reverse.
If you're using an RDBMS, structuring it with conventional tables is usually the best plan.