text:
Q: Return value of path of excel file in PyGtk I cannot store value returned from the function to .connect button widget in a variable to used it in my main program.
I am using PyGtk 3+ in Python 3.4
I need returned value from these program to load other values and perform calculations.
   button = Gtk.Button("Brwose File")
   button.connect("clicked",self.test2)
   def test2(self,widget,mylist1,clicked):
        dialog = Gtk.FileChooserDialog("Please choose a file", None,
                                   Gtk.FileChooserAction.OPEN,
                                   (Gtk.STOCK_CANCEL,
                                    Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
       response = dialog.run()
       if response == Gtk.ResponseType.OK:
           print("Open clicked")
           a = dialog.get_filename()

       wb = xlrd.open_workbook(a)
       sheet = wb.sheet_by_index(0)
       ncols = sheet.ncols
       print(ncols)
       nrows = sheet.nrows
       print(nrows)
       clicked.append(1)
       print(clicked)
       mylist = []
       for i in range(sheet.nrows):
           data = sheet.row_values(i)
           mylist1.append(data)
       return (mylist1)

A: This is not possible because of the way how an event loop works. But since you're working with a class you can just use an instance variable. Simplified:
class MyApp:
    def __init__(self):
        ...
        self.my_var = None
        button = Gtk.Button()
        button.connect("clicked", self.on_button_clicked)

    def on_button_clicked(self, widget):
        ...
        self.my_var = "something"

At that point use self.my_var anywhere else in the class.

A: Thanks! These is better solution. Here is my updated code:
def on_browse_clicked(self, widget):
    """Creates dialogue box to choose file for loading data when browse button is clicked"""

    dialog = Gtk.FileChooserDialog("Please choose a file", None,
                                   Gtk.FileChooserAction.OPEN,
                                   (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print("Open clicked")
        global file
        file = dialog.get_filename()
        dialog.destroy()
        self.browse_entry.set_text(file)
        wb = xlrd.open_workbook(file)
        sheet = wb.sheet_by_index(0)
        for i in range(1, sheet.nrows):
            data = sheet.row_values(i)
            print(data)
            self.production_data_list_store.append(data)

    else:
        dialog.destroy()


text:
Q: Swiftui Mapping Nested JSON to Flat Model I need to access the data in the nested dictionary of the Memodel struct. From both the music and image dictionary. Please any help is needed to map out correctly, i have tried using AzampSharp's example https://www.youtube.com/watch?v=b5wVIQNrI6k but i believe i am doing something wrong. Thanks.
import SwiftUI

    struct MemodelAPIResult: Codable {
        let data: [Memodel]

        enum CodingKeys: String, CodingKey {
            case data = "results"
        }
    }

    struct Memodel: Identifiable, Codable {
        var id: String
        var followers: String
        var following: String
        let music: [MemodelMusic]
        let images: [MemodelImages]

    }

    struct MemodelMusic: Identifiable, Codable, Hashable {
        var id: String
        var musicfile: URL
        var musicname: String
        var musicartistname: String
        var musicgenre: String
    }

    struct MemodelImages: Identifiable, Codable, Hashable {
        var id: String
        var albumimages: URL
        var abumlikes: String
        var albumviews: String
    }

Below is my ObservableObject in my View Model
import Foundation
import SwiftUI
import Combine
import CryptoKit

class MeViewmodel: ObservableObject {
    @Published var me: [Memodel]? = nil

    init() {
            self.fetchme()
    }

    func fetchme() {

        let url = ""

        let session = URLSession(configuration: .default)

        session.dataTask(with: URL(string: url)!) { (data, _, err) in

            if let error = err{
                print(error.localizedDescription)
                return
            }

            guard let APIData = data else {
                print("No Data found")
                return
            }

            do {
                let new = try JSONDecoder().decode(MemodelAPIResult.self, from: APIData)

                DispatchQueue.main.async {
                       self.me = new.data
                }
            }
            catch{
                print(error)
            }
    }
        .resume()
    }

}

And then the item view
struct MeMusicItemView: View {
    //E-MARK: - Properties
    var me: Memodel
    //E-MARK: - Body
    var body: some View {
            HStack {
                    VStack(alignment: .leading, spacing: 5) {
                        Text(me.music[0].musicname)
                            .font(.callout)
                            .fontWeight(.medium)
                            .foregroundColor(.white)
                        Text(me.music[0].musicartistname)
                            .font(.caption2)
                            .fontWeight(.light)
                            .foregroundColor(.white)

                        Text(me.music[0].musicgenre)
                            .font(.system(size: 8))
                            .fontWeight(.light)
                            .foregroundColor(.gray)
                    }
                }
    }
}

And also the ForEach in the parent View....
if let meMusicData = meMusicData.mememe {
                    ForEach(meMusicData) { music in
                        MeMusicItemView(memusic: music)
                    }
                    } else {
                        ProgressView()
                            .padding(.top, 20)
                    }

A: There is not enough info for me to really understand what you are doing, but
here is some code you can have a look at and recycle for your purpose:
struct ContentView: View {
    @StateObject var viewModel = MeViewmodel() // <-- here your model

    var body: some View {
        List {
            ForEach(viewModel.me) { memod in  // <-- loop over the Memodel array
                ForEach(memod.music) { music in  // <-- loop over the MemodelMusic array
                    MeMusicItemView(memusic: music) // <-- display 1 MemodelMusic
                }
            }
        }
    }
}

struct MeMusicItemView: View {
    //E-MARK: - Properties
    @State var memusic: MemodelMusic // <-- here
    //E-MARK: - Body
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 5) {
                Text(memusic.musicname)
                    .font(.callout)
                    .fontWeight(.medium)
                    .foregroundColor(.pink)
                Text(memusic.musicartistname)
                    .font(.caption2)
                    .fontWeight(.light)
                    .foregroundColor(.green)

                Text(memusic.musicgenre)
                    .font(.system(size: 8))
                    .fontWeight(.light)
                    .foregroundColor(.blue)
            }
        }
    }
}

class MeViewmodel: ObservableObject {
    @Published var me: [Memodel] = [] // <--- here no optional, it is easier to deal with

    init() {
        self.fetchme()
    }
    func fetchme() {
        //  ......
    }
}

struct Memodel: Identifiable, Codable {
    var id: String
    var followers: String
    var following: String
    let music: [MemodelMusic]
    let images: [MemodelImages]
}

struct MemodelMusic: Identifiable, Codable, Hashable {
    var id: String
    var musicfile: URL
    var musicname: String
    var musicartistname: String
    var musicgenre: String
}

struct MemodelImages: Identifiable, Codable, Hashable {
    var id: String
    var albumimages: URL
    var abumlikes: String
    var albumviews: String
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hidden input when selecting radio button <input type="radio" name="pay" value="banktransfer"> Bank Transfer

<input type="radio" name="pay" value="paypal"> PayPal

Owner: <input id="id_account_owner" maxlength="250" name="account_owner" type="text" />

Number: <input id="id_account_number" maxlength="50" name="account_number" type="text" />

How to create if I select paypal in radio button then field account_number and account_owner will be hidden?

A: You can use .change events:
$("input[type='radio']").change(function() {
    //Check the value for "paypal", also verify that the radio is checked
    if (this.value == "paypal" && this.checked) {
        $("#account_number, #account_owner").hide();
    } else {
        //I figured you would want to unhide these if paypal isnt checked, here's the else
        $("#account_number, #account_owner").show();
    }
});

A: Like this?
$("#id_account_number, #id_account_owner").prev('label').andSelf().hide(); //hide them initially if you don't have anything checked by default.

$("input[name='pay']").change(function () {
   var elems = $("#id_account_number, #id_account_owner").prev('label').andSelf().show(); //Get the inputs and their labels
    if (this.value == "paypal")  //check for the value of the radio button selected
        elems.hide(); //hide them

});

Fiddle


text:
Q: Seven circles inscribed in a circle problem This is the detail given, Diameter of inner circle is 50. I need to find out middle circle and outer circle radius
The answer is given at the end of the book but I want to learn how to do the calculation. I know that outer circle is 126,6 and smaller middle cirles are 38.3 .
I have tried solving it this way: Having the equilateral triangle, the height of it is 43.3. Doubling that is 86,6. Equilateral height line doubled in dark red.
Having the equilateral triangle, the height of it is 43.3. Doubling that is 86,6. Equilateral height line doubled in dark red. I have been stuck at this for hours, so I need tips what to do next.

A: Let $O$ be inner circle center, and $A$ and $B$ be two adjacent middle circles centers. Then we know $\angle AOB = 2\pi/7$ as there are $7$ middle circles around and all their adjacent center's angles on $O$ will be same. We know inner circle's radius is $50$, let r be the middle circle's radius. Then the triangle given in here  will have sides $50+r, 50+r$ and $2r$ (not an equilateral triangle as in your question) We can draw the angle bisector of $\angle AOB$, and applying $\sin(\pi/7) = \frac{r}{50+r}$ in the right angled triangle which will form, we get $r=\frac{50\sin(\pi/7)}{1-\sin(\pi/7)}\approx 38.32108$. Now radius of outer circle is just $50 + 2r \approx 126.64216 $

A: It is enough to consider the triangle $\triangle {OAB}$ involving the inner circle of radius $50$ and two of the searched seven circles of unknown radius $r$. Since  angle $\angle{BOC}=\dfrac{\pi}{7}$ we have the equation $$\frac{r}{50+r}=\sin\left(\dfrac{\pi}{7}\right)=0.433883739$$ so $r=38.32108076$. From which the radius of the outer circle is equal to $126.64216153$


text:
Q: Can we decrease the value of $g$ (gravitational pull) without gaining height? The value of $g$ on earth surface is $9.8\ \text{m/s}^2$ and when we gain height, then the value of $g$ decreases.  Pilots experience same phenomena in air, but can we decrease the value of $g$ by staying on ground?

A: The effective value of $g$ decreases as you move away from Earth's surface because of Newton's Shell Theorem.  The decrease goes like the square of the distance from the center of the Earth, but like all smooth functions you can approximate it as a linear decrease over small changes in height.  From sea level to the top of the atmosphere counts as a "small" change in height for these purposes (100 km / 6000 km = 2% of total, for a 4%-ish change in the strength of gravity between sea level and space).
tmwilson claims in a comment that $g$ decreases as you tunnel into the Earth.  This would be true if the Earth were a sphere of uniform density, also due to the shell theorem, since there is zero gravitational force on the inside of a spherical shell and zero gravitational force at the exact center of the Earth.  However the Earth is a sphere which is denser at the core than at the surface, which makes the question more complicated.
You clarify in a comment that you're interested in changing $g$ with altitude; that goes only one way, with gravity getting weaker at high altitude.

A:
Can we decrease the value of g (gravitational pull) without gaining height?

No.

Implicit in your question is that:

*

*You have a fixed position on the surface of the planet Earth.

*You do not have the ability to move planet-sized masses around.

*You want to decrease the gravitational pull by more than could be achieved by:

*

*levelling nearby mountains or by

*transporting yourself to another place on the Earth's surface (e.g. from equator to pole).

Note that, for short periods of time, you can simulate the effect of reduced gravity by introducing other accellerations. This is easier inside an actual aircraft - but that may defeat the purpose of your question. Maybe you could arrange something using a rocket sled and a railway track over a suitably re-contoured mountain?


text:
Q: How to copy the conditional formatting without copying the rules from a Conditional Formatted cell? I have a row of data with conditional formatting in it.
I need to copy this row to another row. This new row must be identical (values, formats), but static, i.e. without the rules. If I copy and paste the row and clear the rules, the formatting from the CF rule vanishes.
Is it possible?

A: Just discovered an easy way: Copy the table to MS Word and copy it back to excel :D

It worked perfectly for me.

A: You can do it using the "Office Clipboard" Pane ...
Copy the formatted region, then go to the "paste" page and open the Office Clipboard Pane, it is the small button in the right lower corner here:
Office Clipboard pane
Then click on the "copied" content and it will paste it with formats and without conditional formatting. Very hidden, and not intuitive at all
Source

A: I found a dead easy solution to this problem.

*

*Copy the cells with the results of conditional formatting that you want to duplicate in another place.

*Paste into an OpenOffice Calc spreadsheet (I used build 4.1.5) as Formatted - RTF. The formatting is still there, but OpenOffice apparently discards the conditions that created the formatting in the first place.

*Now simply copy and paste into Excel.

*Crack open the champagne.
This works with Excel files thousands of lines long.

A: Copy and paste to Google Sheets, then copy and paste back into Excel.
(I had to resort to this because the copy/paste to Word didn't work for me)

A: First copy then look for "paste all" option. It worked for me.

A: The Excel copy / Word paste/ copy/ Excel paste again is the only quick way of doing this.

A: I found an easy solution for this! Once you have added your conditional formatting, simply add Filtering to your table, then click the filter (down arrow) on any of the Header columns > click Filter by Color > choose color > select all > choose same background color as background > Remove Filtering.  Then you will go back to Conditional Formatting, remove the rule and you will still have the colors on the cells that the conditional formatting did, just without all of the extra load of actually having the Conditional Formatting rule set.  I hope that helps and isn't too confusing. I forgot to mention that this specific example was related to background colors, but you can also filter on text colors as well.

A: *

*Press CTRL+C on the cell(s) you want to copy.

*Press ALT > E > S > U on the cell(s) you want the value(s) to be pasted.

The value(s) and the formatting will be pasted, but not the conditional formatting rule(s).


text:
Q: Getting json data from Spoonacular in Android Studio trying to get to an Android App random recipes from Spoonacular. For some reason, I'm not getting the data from the json. I know how to do this in Javascript, but that's no use to me in Java.
My repository file:
public class RecipeRepository {

    private static final String API_KEY = "472f31ce4a5e4e5792ca9ab6d1833e51";
    private static final String URL = "https://api.spoonacular.com/recipes/random?apiKey=%s";
    private final Application application;
    private final MutableLiveData<ArrayList<Recipe>> recipeLiveData;
    private final ArrayList<Recipe> arrayList = new ArrayList<>();

    public RecipeRepository(Application application) {
        this.application = application;
        recipeLiveData = new MutableLiveData<>();
    }
    public void getDayRecipe() {
        Ion.with(application)
                .load(String.format(URL,API_KEY)).asJsonObject()
                .setCallback((e, result) -> {
                    Log.i( "getRandomRecipe",result.getAsJsonPrimitive().toString());
                    parseResults(result);
                });
    }
    public String removeAbles(String text) {return text.substring(1,text.length()-1); }

    private void parseResults(JsonObject result) {
        JsonObject randomRecipe = (JsonObject) result.getAsJsonArray("recipes").get(0);

        String title = String.valueOf(randomRecipe.get("title"));
        String instructions = String.valueOf(randomRecipe.get("Instructions"));
        //ingredients
        //image
        recipeLiveData.setValue(arrayList);
    }
    public MutableLiveData<ArrayList<Recipe>> getRecipeLiveData() {
        return recipeLiveData;
    }
}

I get a 'variable is never used' with title, instructions and removeAbles


text:
Q: Little envelope next to method's name in class designer (Visual Studio) I am curious. What is the meaning of a little envelope next to a method's name? I am using the class designer of Visual Studio 2010.

A: The link bzlm posted in his comment does contain the envelope:

 | Internal. Accessible only from this component.

It is one of the signal icons:

The following signal icons apply to all the previous icons and indicate their accessibility.

So, the QBar method is internal.


text:
Q: can not show messages received in console with pusher and websocket for project i used pusher to create realtime chat using laravel 9 . i can send message from front end to backend with api but can not received messages from backend
chat channel created but won't show up anything
for example when an event called backend completely received that but could not send anything or can not connect to channel
js :
Echo.channel('chat').listen('.MyMessage', (e) => {
    console.log(e)
})

could anyone help me ?


text:
Q: Cardinality violation: 1222 The used SELECT statements have a different number of columns Why am i gettin this error  Cardinality violation: 1222 The used SELECT statements have a different number of columns
$query = "
SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id
FROM students as s,
courses as c, users as u, studentgrade as sg
WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
UNION ALL
SELECT SUM(sg.assignmentpoints) as sum
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid
 ";

A: (
        SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id
        FROM students as s,
        courses as c, users as u, studentgrade as sg
        WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
)

- Query A.
(
SELECT SUM(sg.assignmentpoints) as sum
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid
)

- Query B.
Query A should return the same number of columns as the request B.
So In your case:
SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id
FROM students as s,
courses as c, users as u, studentgrade as sg
WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')
UNION ALL
SELECT SUM(sg.assignmentpoints) as sum, '', '', '', '', '', '', '', '', ''
           FROM assignments as sg
           WHERE sg.courseid = 185
           GROUP BY sg.courseid

I think you need Join, not Union.
SELECT DISTINCT s.studentid, s.fname, s.lname, s.studentcode, s.courseid, u.id
    FROM students as s,
    courses as c, users as u, studentgrade as sg
    LEFT JOIN
    (SELECT *
    FROM assignments
    GROUP BY courseid
    ) as asg on asg.courseid=s.courseid
    WHERE s.courseid = '$id' and u.id = (SELECT id FROM courses WHERE courseid = '$id') and u.id = (SELECT id FROM users WHERE username = '$nombre')


text:
Q: Version C and Fortran90 : optimization for filling subarrays before MPI_Gather I have coded a little MPI program that computes with an iterative scheme on a 2D domain : I apply a filter for each cell values (5 points stencil).
In my code, I split global domain into multiple subdomains depending of number of processes. I take xcell and ycell the size of each subdomain.
Once computation reaches the convergence wanted, I store values for each subdomains into 1D array (see below xtemp array) and after, I use MPI_Gather to collect all these subdomains into 1D final array (xfinal array). In the assignement below (into loop) x0 array represents the 2D subdomain that I want to copy into xtemp 1D array.
Now, I want to know if I apply good coding rules and optimizations (I mean the way to get the best performances from a runtime point of view) with the filling of "xtemp" array in each version (Language C and Fortran90). me is the rank of current MPI process and xs,xe,ys,ye the coordinates of each subdomain. We also have to notice that we take for arrays the convention (i,j) = (rows,columns) in Language C and Fortran90 versions.
I did :
Language C :
   /* Fill all 1D xtemp array before MPI_Gather all subdomains :
      inner loop on columns index (second index)
      to optimize since C is row major */
   j=1;
   for (i=xs[me];i<=xe[me];i++) {
      for (k=0;k<ycell;k++)
         xtemp[(j-1)*ycell+k] = x0[i][ys[me]+k];
      j=j+1;
   }

As you can see, I think the inner index must be on columns (ys[me]+k) because C language is row major.
Fortran90:
   ! Fill all 1D xtemp array before MPI_Gather all subdomains :
   ! inner loop on rows index (first index)
   ! to optimize since F90 is column major
   i = 1
   do j=ys(me),ye(me)
     xtemp((i-1)*xcell+1:i*xcell) = x0(xs(me):xe(me),j)
     i = i+1
   end do

Here, I think the inner assignment must be on rows (xs(me):xe(me)) because F90 language is column major.
Do you agree with these 2 versions of xtemp array filling, i.e from an optimization point of view (to get a minimal runtime for both versions, F90 and C language)?
Update 1
Following the different comments I received, I give more information:
1. Language C version :
For the language C version of filling xtemp 1D array : I use contiguous x0 2D array (taking convention [i,j]=[row,column]) :
double **x0;
x0 = malloc(size_total_x*sizeof(*x0));
x0[0] = malloc(size_total_x*size_total_y*sizeof(**x0));
for (i=1;i<size_total_x;i++) {
   x0[i] = x0[0] + i*size_total_y;
}

From what you have indicated, the following block is valid to fill correctly the xtemp 1D array :
j=1;
   for (i=xs[me];i<=xe[me];i++) {
      for (k=0;k<ycell;k++)
         xtemp[(j-1)*ycell+k] = x0[i][ys[me]+k];
      j=j+1;
   }

It seems that you confirm it, doesn't it ?
2. Fortran F90 version :
For the F90 version of filling xtemp 1D array : I use also contiguous x0 2D array (taking convention [i,j]=[row,column]) :
double precision, allocatable :: x0(:,:)
allocate(x0(0:size_total_x-1,0:size_total_y-1))

About this block above, is it a right way to allocate 2D contiguous array in Fortran90 ?
Finally, I didn't see a comment on the filling of xtemp 1D array with Fortran90 version, i.e :
 i = 1
   do j=ys(me),ye(me)
     xtemp((i-1)*xcell+1:i*xcell) = x0(xs(me):xe(me),j)
     i = i+1
   end do

Is it better to do (like since the beginning, from a right optimization point of view):
  j = 1
       do i=xs(me),xe(me)
         xtemp((j-1)*ycell+1:j*ycell) = x0(i,ys(me):ye(me))
         j = j+1
       end do

or not?
I realize that, between these 2 solutions, the output xtemp will be filled differently (by blocks of xcell for the first one and ycell for the second one) but I don't mind it : I just want to use the most optimized way.

A: Here is a summary of the various comments on this question
In Fortran, or if your array is a C contiguous array, an other option is to use derived datatype so there is no need to "pack/unpack" the data to/from a temporary buffer. Since the data is very regular (e.g. a subset of a 2D array), MPI libraries should handle this quite efficiently.
In Fortran,
i = 1
do j=ys(me),ye(me)
  xtemp((i-1)*xcell+1:i*xcell) = x0(xs(me):xe(me),j)
  i = i+1
end do

is likely the most effective way to pack the x0 array into the xtemp temporary buffer. The array assignment syntax can be seen as an implicit loop that iterates on the first index (e.g. column in Fortran) which is optimal.
On the other hand, in C,
j=1;
for (i=xs[me];i<=xe[me];i++) {
  for (k=0;k<ycell;k++)
    xtemp[(j-1)*ycell+k] = x0[i][ys[me]+k];
  j=j+1;
}

is likely optimal since the (explicit) innermost loop iterates on the second index (e.g. row) which is optimal in C.
Note the x0 array is declared as a jagged array, and thought is is manually built as a contiguous array, the compiler is not aware of it.
Declaring x0 as a 2D array (e.g. double x0[xcell][ycell];) should lead to better performances.
If your application is hybrid MPI+OpenMP, then you can get an extra boost by using OpenMP when packing/unpacking x0 to/from xtemp. In that case, it might be faster than using derived datatype since dealing with derived datatypes is a serial operation in most MPI implementations.

A: Awhile ago I wrote some preprocessor code to arbitrarily allocate pointer based 2D and 3D arrays of things. I did this to avoid the implicit multiplication required to access members. Note that you can access the array members linearly as well as dimensionally with this method. I hope it helps:
// allocate a 2D array: 'var' is the variable it will be assigned to, 'type' is like float, double, char *, etc
// your var should be declared as type **
// array contents are calloc()ed
// you can linearly address members by &a[0][0];
#define new2DArray(var,type,xDim,yDim) \
do { \
      type *arrayPtr; \
      type **x;      \
      int i; \
      type *p; \
\
      arrayPtr=(type *)calloc(xDim*yDim,sizeof(type)); \
\
      if(arrayPtr==NULL) \
      {  \
         var=NULL; \
         break; \
      }  \
\
      x=(type **)malloc(xDim*sizeof(type **)); \
\
      if(x==NULL)  \
      {  \
        free(arrayPtr);  \
         var=NULL; \
         break;  \
      }  \
\
      for(i=0,p=arrayPtr;i<xDim;i++,p+=yDim) \
         x[i]=p;  \
\
      var=x; \
} while(0)

#define free2DArray(array) do \
{  \
  if(array!=NULL) \
  {  \
    if(array[0]!=NULL) \
      free(array[0]);  \
   free(array);  \
  }  \
} while(0)

#define free3DArray(array) do\
{ \
   if(array!=NULL) \
   {  \
      if(array[0]!=NULL)  \
         free2DArray(array[0]); \
      free(array); \
   } \
} while(0)

// allocate a 3d array: 'var' is the variable it will be assigned to, 'type' is a valid C variable type
// your var should be declared as type ***
// array contents are calloc()ed
// you can linearly address members by &a[0][0][0];
#define new3DArray(var,type,xDim,yDim,zDim) do\
{ \
   type *arrayPtr; \
   type ***xy;  \
   int x,y;  \
   type *p;  \
\
   arrayPtr=(type *)calloc(xDim*yDim*zDim,sizeof(type)); \
   if(arrayPtr==NULL) \
      break; \
   new2DArray(xy,type *,xDim,yDim);  \
   if(xy==NULL)  \
   {  \
      free(arrayPtr);  \
      var=NULL; \
      break; \
   }  \
   p=arrayPtr;  \
   for(x=0;x<xDim;x++) \
      for(y=0;y<yDim;y++,p+=zDim) \
         xy[x][y]=p; \
\
   var=xy; \
} while(0)


text:
Q: Hypersphere packings from hypercubic graphs? Consider a $D$-dimensional hypercubic lattice, i.e. a graph $H$ embedded in ${\mathbb R}^D$ where the vertices have integer coordinates $ (x_1,...,x_D) \in {\mathbb Z}^D$ and edges are between all pairs $ \{ (x_1,...,x_i,...,x_D), (x_1,...,x_i+1,...,x_D)\}$.
From this graph $H$, build a second graph $S$ the following way.

*

*consider the family of vertices of $H$, embedded in the $D-1$-dimensional hyperplanes $S_t$ defined by $\sum_{i=1}^D x_i = t$ with $t \in {\mathbb Z}$

*consider that there is an edge between two vertices in $S_t$ if, in $H$,  those two vertices have a common neighbour in $S_{t+1}$ or/and $S_{t-1}$.
Obviously $S = \cup_t S_t$ is a disconnected graph with each $S_t$ being a $D-1$ dimensional layer.
I remarked that for $D = 2, 3$, and apparently also for $D=4$, the $S_t$ are actually $D-1$-hypersphere packing contact graphs.
My question is, for what values of $D$ does this hold?


text:
Q: Dotnet iText7 generate PDF locally in Windows but did not generate after publish on Ubuntu Server I have tried pdf generate with iText7. I was achieve that on locally with Windows OS. Then I have sent with mail as attachment and that is work pretty good.
I am using Ubuntu server. I have published, then I was got internal server error 500.   So I was try to handle with try catch bloc and I got system exception. There was not any detail.
How can I achieve this?
I have already tried memory stream before save to disk, same result.
File creation was okay but that is it. No information in file.
Package Information: iText7 v7.2 with Dotnet 6
Thrown Exception After I Have Made Try Catch
   "targetSite": null,
"message": "Exception of type 'System.Exception' was thrown.",
"data": {},
"innerException": null,
"helpLink": null,
"source": null,
"hResult": -2146233088,
"stackTrace": null

My Pdf Generator
using iText.IO.Font;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
using MyProject.Models;

namespace MyProject.Helpers.PdfService
{
    public class PdfManager : IPdfService
    {
        private readonly MyContext _context;
        private static PdfFont font;
        public PdfManager(MyContext context)
        {
            _context = context;

        }
        public string GenerateOrdersPdf(List<Order> orders, List<Customer> customers)
        {

        try
        {

        font = PdfFontFactory.CreateFont("/var/www/fonts/roboto/Roboto-Regular.ttf", "Windows-1254");
        orders = orders.OrderByDescending(o => o.CustomerId).ToList();
        string pdfPath = "/var/www/Paketler.pdf";

        FileInfo file = new (pdfPath);
        PdfWriter pdfWriter = new(pdfPath);
        PdfDocument pdf = new(pdfWriter);
        Document document = new(pdf);

        OwnInformation ownInformation = _context.OwnInformations.First();
        Paragraph header = new Paragraph(ownInformation.CompanyName)
                .SetTextAlignment(TextAlignment.CENTER)
                .SetFont(font)
                .SetFontSize(13)
                .SetBold();
        document.Add(header);
        document.Add(new LineSeparator(new SolidLine()));
        Paragraph date = new Paragraph(DateTime.Now.ToShortDateString())
        .SetTextAlignment(TextAlignment.RIGHT)
         .SetFontSize(11);
        document.Add(date);
        Table table = new(new float[] { 4, 1, 3, 4, 3, 3, 3, 3, 1 });
        GenerateOrderHeader(table);
        table.SetWidth(UnitValue.CreatePercentValue(100));
        int counter = 0;
        int piece;
        foreach (Order order in orders)
        {
            counter++;
            piece = _context.OrderDetails.Where(od => od.OrderId == order.Id).ToList().Count;
            GenerateOrderHeaderInformation(customers, table, counter, order, piece);
        }
        table.SetTextAlignment(TextAlignment.CENTER);
            table.SetFont(font);
            document.Add(table);
            GeneratePdfFooterTotalsField(orders, document, font);
        document.Close();
        return pdfPath;
        }
        catch (Exception e)
        {

            return e.ToString();
        }
    }}

Pdf File Created But Not Exactly, It Is Workless


text:
Q: M-M relationship in MVC and Entity Framework works only in debugger mode I am doing some project for school and have encountered a strange thing. Situation is like this:
In my SQL Server db I have 3 tables: Product, Ingredient and ProductIngredient. The last one is PJT between the first two.
I have this in a controller:
public ActionResult Index()
        {
            List<Product> products;
            using (FastfoodConnection conn = new FastfoodConnection())
            {
                products = conn.Products.ToList();

            }
            TestModel tM = new TestModel();
            tM.Products = products;
            return View(tM);
        }

and here is my view:

@foreach (var product in Model.Products)
{

         @product.Name
         @product.Description

        Ingredients

           @foreach (var ingredient in product.Ingredients)
           {

@ingredient.IngredientName

           }

}

Now - when I set the breakpoint in controller and debug the code, step by step, everything works fine and result shows as I want it to. However, when I try to run the code (without debugging) I get ObjectDisposedException with description "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection." Apparently this regards to
product.Ingredients list which is null.
My question is: What could be the problem and how can it be solved?

A: You need to eager load the Ingredients. EF won't try to fetch those from the database until you need them, which is called Lazy Loading. Because you try to access them after you disposed your context, EF can't query the database for the Ingredients and you get an exception.
Eager loading tells EF it should also fetch those entities in the same run when it gets the Products. It's always a good idea to use eager loading when you know beforehand you will need the entities. This avoids multiple db calls since everything gets fetched in one query. It can be invoked through the Include(...) method:
public ActionResult Index()
    {
        List<Product> products;
        using (FastfoodConnection conn = new FastfoodConnection())
        {
            products = conn.Products.Include(p => p.Ingredients).ToList();

        }
        TestModel tM = new TestModel();
        tM.Products = products;
        return View(tM);
    }

This should resolve your problem. Also make sure you have the collection of Ingredients marked as virtual in your product model, which enables lazy/eager loading, but since it works in debugging mode I guess that will be alright.


text:
Q: Combining two distance matrices for clustering I'm looking to see if I can cluster geographic regions by a variable, such as losses.
For example, I have 5 regions with the following amount of losses:
Region 1 with \$500,000 in losses.
Region 2 with \$400,000 in losses.
Region 3 with \$200,000 in losses.
Region 4 with \$200,000 in losses.
Region 5 with \$300,000 in losses.
Ideally I'd like to cluster them based on similar losses (for example, clustering region 3 and 4 together since they share the same amount of total losses). However, I need to ensure that the regions are spatially adjacent to each other. So if region 3 is not right next to region 4, I would not allow them to be clustered together.
I have a shapefile of all the regions, which includes the centroid latitude and longitude of each region.
My idea for doing this is taking a distance matrix (derived by the latitude and longitude coordinates) and combining it with another distance matrix (derived from losses). Would this sort of approach work?If so, what would the R code look like for this sort of merge?
If not, what sort of approach would be recommended?

A: The following article (link found here: https://arxiv.org/pdf/1707.03897.pdf) provides a way to cluster with spatial constraints. In particular, one could specify strict neighborhood boundaries for the clusters.


text:
Q: django create row on user creation class Student(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    dob = models.DateField(blank=True, null=True)
    student_rank = models.OneToOneField(
        StudentRankSignoff, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.user.username`

When a Student signs up, i want to have the StudentRankSignoff table contain a blank row.  How do I go about doing this?


text:
Q: Can I add a second function export to module.exports without changing the way it's called? I have a logging module that I use in many of my projects, which generally exports a single Winston logger, so all I did was define a logger and it's transports, then export it:
module.exports = logger;

when importing using const logger = require('mylogger.js') I then use the various levels built in (logger.info logger.debug etc).
I've now decided that I want to create a second logging function that will write logs to a different file, so I need to create and export a new transport. Thing is, if I switch to module.exports = {logger, mynewlogger}, that will change the way I import and call the functions, and I have that in many places.
Besides creating second file and importing both, is there any other way to add a second export without having to change my code everywhere else?

A: It's either new module that re-exports both:
logger-and-mynewlogger.js
module.exports = {logger, mynewlogger}

Or a separate module:
mynewlogger.js
module.exports = mynewlogger

Or using existing function as module object:
logger.mynewlogger = ...

module.exports = logger;

The first two options are preferable because they result in reasonably designed modules, while the last one is a quick and dirty fix.

A: Yes, you can define multiple transports for a single exported logger.  When creating your Winston log, the 'transports' property is an array which allows you to define multiple outputs.
Here's an example of one I have that has two transports.  Firstly, console and the second a daily rotating log.
const winston = require('winston');
const Rotate = require('winston-daily-rotate-file');
const tsFormat = () => (new Date()).toLocaleTimeString();

const logger = new (winston.Logger)({
    transports: [
        // colorize the output to the console
        new (winston.transports.Console)({
            timestamp: tsFormat,
            colorize: true,
            level: 'info',
        }),
        new (Rotate)({
            filename: `${logDir}/${logName}-app.log`,
            timestamp: tsFormat,
            datePattern: 'YYYY-MM-DD',
            prepend: true,
            level: env === 'development' ? 'verbose' : 'info',
        }),
    ],
});

module.exports = logger;


text:
Q: Wicket 7 - Web Sockets - EAP 6.3 I'm trying to implement Websockets in Wicket 7 (EAP 6.3 environment) following this mini-tutorial.
Everything is working as expected, except for the websocket is automatically closed after 60 seconds of inactivity. I've read in different places that I have to change the idle timeout for keeping the websocket open, but I can't find where to set the timeout in the Wicket implementation.
Another solution would be to send an empty message for keeping the connection alive, but I don't want this approach.
Did anyone find this problem working with websockets in Wicket 7?
Any suggestions would be appreciated.
Thank you!

A: I haven't tried it but maybe you can use 'ping' message to keep the connection aliveRemoteEndpoint#sendPing()
At the moment Wicket doesn't expose this API but if you confirm that it does the job then please create a ticket at Apache JIRA and we will add it.


text:
Q: How do I notify in Android the ViewModel when a background job has finished creating a new record using LiveData? I have an application which from one activity triggers a background job using JobScheduler. This job inserts in a database using Room once it's done. To notify the ViewModel I'm using LiveData. I have set up a main activity which uses ViewModel and everything is injected with Dagger 2.
The problem is as follows: when I launch the main activity the list is populated as expected. However when from other activity I schedule a job and said job is finished and a new record has been inserted in the database the main activity does not update.
Moreover, if I update a record from the main activity (without using a job) the view refreshes as expected, which makes me believe that the problem has to do with the ViewModel not detecting when a record is inserted using a job.
If I'm using LiveData, isn't it supposed to catch all the new insertions? How could I manually notify the ViewModel of the new record?
Edit:
Repository:
@Singleton
class DebtsRepository @Inject constructor(
        var debtDao: DebtDao
) {

    fun insertDebt(debt: Debt) {
        debtDao.insert(debt)
        Log.e("DebtsRepository", "debt inserted")
    }

    fun getAllDebts(): LiveData<List<Debt>> {
        return debtDao.findAll()
    }

    fun getAllDebtsWithInformation(): LiveData<List<DebtWithDebtorCreditorAndProduct>> {
        return debtDao.findAllWithProductDebtorAndCreditor()
    }

    fun payDebt(debtId: Long) {
        val paidDebt = debtDao.findOne(debtId)
        debtDao.update(paidDebt.copy(paid = true))
    }

    fun getUnpaidDebts(debts: List<DebtWithDebtorCreditorAndProduct>): List<DebtWithDebtorCreditorAndProduct> = debts.filter { !it.debt.paid }

}

Here is the ViewModel:
@Singleton
class DebtsListViewModel @Inject constructor(var debtsRepository: DebtsRepository) : ViewModel() {

    private var debts: LiveData<List<Debt>> = MutableLiveData()
    private var formattedDebts: LiveData<List<DebtWithDebtorCreditorAndProduct>> = MutableLiveData()

    init {
        debts = debtsRepository.getAllDebts()
        formattedDebts = Transformations.switchMap(debts) {
            Log.e("DebtsListViewModel", "change triggered")
            debtsRepository.getAllDebtsWithInformation()
        }
    }

    fun getFormattedDebts() = formattedDebts

    fun payDebt(debtId: Long) {
        debtsRepository.payDebt(debtId)
    }

    fun getUnpaidDebts(): List<DebtWithDebtorCreditorAndProduct> =
            if (formattedDebts.value != null)
                debtsRepository.getUnpaidDebts(formattedDebts.value!!)
            else
                emptyList()

}

This is the job:
class GenerateDebtJobService : JobService() {

    @Inject
    lateinit var debtsRepository: DebtsRepository

    @Inject
    lateinit var productDao: ProductDao

    @Inject
    lateinit var productsDebtorsDao: ProductDebtorDao

    @Inject
    lateinit var productCreditorsDao: ProductCreditorDao

    override fun onStartJob(params: JobParameters): Boolean {
        DaggerGraphBuilder.build(applicationContext as FineApplication).inject(this)
        val productId = params.extras.getLong("id")
        val product = productDao.findOne(productId)
        val productCreditor = productCreditorsDao.findOneByProduct(productId)
        val debtors = productsDebtorsDao.findAllByProduct(productId)

        // When the bill day is reached for a given product the debtors list associated with that product is looped through and a new debt is created
        debtors.forEach {
            debtsRepository.insertDebt(Debt(productId = it.productProductId, debtorId = it.productDebtorId, quantity = product.recurringCost, date = DateTime().toString(), creditorId = productCreditor.productCreditorId))
        }

        return false
    }

    override fun onStopJob(params: JobParameters): Boolean {
        Log.e("GenerateDebtJob", "job finished")
        return false
    }

    companion object {
        fun build(application: Application, productId: Long, periodicity: Days, startDay: Days) {
            val serviceComponent = ComponentName(application, GenerateDebtJobService::class.java)
            val bundle = PersistableBundle()
            bundle.putLong("id", productId)

            val builder = JobInfo.Builder(productId.toInt(), serviceComponent)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//                    .setPeriodic(TimeUnit.DAYS.toMillis(periodicity.days.toLong()))
                    .setOverrideDeadline(1_000)
                    .setExtras(bundle)

            (application.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(builder.build())
        }
    }

}

More edits:
I found out that the instance of the repository on the App is different that the instance of the repository on the background job. This makes the LiveData unable to trigger new changes when there are new records inserted in the DB.
So my guess is that somehow I have to check if the app is on the foreground and if so inject the current instance of the repository into the job.
If not, then the dependency graph must be created and as the job executes without the app running.
Here are the relevant parts of DI configuration:
AppComponent:
@Singleton
@Component(modules = [
    AppModule::class,
    AndroidInjectionModule::class,
    DebtsListViewModelModule::class,
    DebtsListModule::class,
    AddProductModule::class
])
interface AppComponent {

    fun inject(application: FineApplication)
    fun inject(generateDebtJobService: GenerateDebtJobService)

}

AppModule:
@Singleton
@Module
class AppModule(private val application: Application) {

    @Provides
    fun provideApplicationContext(): Context = application

    @Provides
    fun provideAppDatabase(context: Context): AppDatabase =
            Room
                    .databaseBuilder<AppDatabase>(context, AppDatabase::class.java, AppDatabase.DB_NAME)
                    .allowMainThreadQueries()
                    .build()

    @Provides
    fun provideDebtDao(database: AppDatabase): DebtDao = database.debtDao()

    @Provides
    fun provideDebtorDao(database: AppDatabase): DebtorDao = database.debtorDao()

    @Provides
    fun provideCreditorDao(database: AppDatabase): CreditorDao = database.creditorDao()

    @Provides
    fun provideProductDao(database: AppDatabase): ProductDao = database.productDao()

    @Provides
    fun provideProductDebtorDao(database: AppDatabase): ProductDebtorDao = database.productDebtorDao()

    @Provides
    fun provideProductCreditorDao(database: AppDatabase): ProductCreditorDao = database.productCreditorDao()

}

Application:
class FineApplication : Application(), HasActivityInjector {

    @Inject
    lateinit var dispatchingActivityInjector: DispatchingAndroidInjector<Activity>

    private val component by lazy {
        DaggerAppComponent
                .builder()
                .appModule(AppModule(this))
                .build()
    }

    override fun onCreate() {
        super.onCreate()
        component.inject(this)
        Stetho.initializeWithDefaults(this)
        JodaTimeAndroid.init(this)
    }

    override fun activityInjector(): AndroidInjector<Activity> = dispatchingActivityInjector

}

If there is anything else needed just let me know.


text:
Q: Using asyncio ioloop with pyzmq I want to create a tcp server with zmq sockets. The following code creates the tcp server with use of zmq sockets using python's asyncio's ioloop.
In the following code, I am creating the zmq socket to listen to the incoming connections. The coroutine  recv_and_process creates a socket to listen the connection and have a while loop to respond the incoming connection.
My question is how to eliminate the while loop and instead use the exsiting asyncio event loop ?
import asyncio
import zmq
import zmq.asyncio

zmq.asyncio.install()
ctx = zmq.asyncio.Context()

@asyncio.coroutine
def recv_and_process():
    sock = ctx.socket(zmq.PULL)
    sock.bind('tcp://127.0.0.1:8888')
    while True:
        msg = yield from sock.recv_multipart() # waits for msg to be ready
        print(msg)

if __name__ == '__main__':

    loop = asyncio.get_event_loop()
    loop.run_until_complete(recv_and_process())

A: I'm not sure I understood what you want, but here some thoughts: when we say "asyncio event loop" we mean some global object that executes coroutines in your script. You're already using this event loop by running it until coroutine recv_and_process done with line loop.run_until_complete(recv_and_process()).
Running asyncio event loop to execute coroutines doesn't mean that your program shouldn't have plain while loop statements. While loops can be used for same purpose as always - to do something repeatedly, for example, including awaiting of some coroutine as is in your case.


text:
Q: IP address detection in string (C++) I have interesting problem with IP address detection in C++. I used inet_pton function and sockaddr_in structure. If string is valid IPv4 or IPv6, function will return AF_INET or AF_INET6. Otherwise zero is returned.
Code below does not work. SIGSEGV in condition with IPv6 detection when input is valid IPv6 address (IPv4 address and invalid address are OK). Same problem is after removal of IPv4 condition.
#include <string>
#include <iostream>
#include <arpa/inet.h>

using namespace std;

int isIP(string);

int main(int argc, char *argv[]){
        string s = "::1";
        int test = isIP(s);
        return 0;
}

int isIP(string addr){
        struct sockaddr_in sa;
        if((inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr))))
                return AF_INET;
        if((inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr))))
                return AF_INET6;
        return 0;
}

But when is function IsIP changed like codes below, everything is OK.
int isIP(string addr){
        struct sockaddr_in sa;
        cout << addr + "\n";
        if(inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr)))
                return AF_INET;
        if(inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr)))
                return AF_INET6;
        return 0;
}

or
int isIP(string addr){
        struct sockaddr_in sa, sa2;
        if((inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr))))
                return AF_INET;
        if((inet_pton(AF_INET6, addr.c_str(), &(sa2.sin_addr))))
                return AF_INET6;
        return 0;
}

or
int isIP(string addr){
        struct sockaddr_in sa;
        int r1 = inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr));
        int r2 = inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr));

        if(r1)
                return AF_INET;
        if(r2)
                return AF_INET6;
        return 0;
}

What is that problem in first implementation of isIP function?

A: You have to pass pointer to struct in6_addr in case of ipv6 test.

A: struct sockaddr_in sa;

This is the structure for IPv4; it does not have enough space for IPv6 addresses, so you are going out of bounds in those cases.
Adding more code to your function just so happens to have made more memory available to the function — either by declaring another variable, or by triggering some arbitrary, implementation-defined constructs about which we cannot rationalise — so that, when you overflow sa, you're overflowing into memory owned by the process and therefore do not trigger an access violation error. However, it's still very wrong.
IPv6 addresses are to be read into a struct in6_addr; one is contained within struct sockaddr_in6 so, e.g.:
bool isIPv6(const string& addr)
{
   struct sockaddr_in6 sa;
   if (inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr)))
       return true;
   return false;
}


text:
Q: In Arrival (2016) — how come she has "visions" early in the film? In the third act of the movie we find out that...

 the main character can "see" into the future, or, with her mind, travel fourth dimensionally, and that's the explanation for a lot of the visions she has which the audience was led to believe were in fact flashbacks.

We know that she can do this because..

 learning the alien language makes your mind think the way they do, which gives that pseudo-time-travel ability

But how is it that she has "flashbacks" early on in the movie, before she learns the language? Please provide as in-depth an explanation as you can muster, plugging any logic or plot holes that someone might raise (this is a problem that someone I know has with the movie, and I'd like to counter-argue).

A: ref: Arrival Explained
That first scene we see, if you pay attention to the narration, Louise is recollecting the events from their Arrival. It's not like she's dreaming or seeing those visuals.

The punchline in the movie or the revelation in the climax is that the
  scenes where Louise Banks (Amy) is shown with her daughter, is not the
  past. Those are her visions of her own future. Yes, they are. You can
  hear Louise narrating this as a recollection. She is recollecting the
  events of the "arrival".

She's narrating at a point in time clearly after her learning of the language. After the scenes with her daughter, the story begins with the day of the arrival when Lousie was a single teacher.
The Narrative goes as follows:
I used to think this was the beginning of your story. Memory is a strange thing.
It does not work like I thought it did. We are so bound by time. By its order. And now Im not so sure I believe in beginnings and endings. There are days that define your story beyond your life. Like the day they arrived.

A: First things first: there is no time travel.  Learning the alien language alters the way you perceive time, allowing you to experience "memories" of future events.  It's as much time travel as remembering your birthday party from last year is "time travelling" into the past.
Secondly, we need to separate Louise-the-Narrator from Louise-on-screen.  Louise-the-Narrator is speaking from a specific moment in time, presumably AFTER everything we see on screen has happened.  At least, that's how it usually goes for movies that have a character narrating stuff in voice-over.
The first thing Louise says is "I used to think of this as the start of your story" (or words to that effect):

 Referring to her daughter's birth.  We then see a series of excerpts from her daughter's life, where she progressively gets older and eventually gets sick and dies.

After those scenes are over, she says something about realizing that the story of a person's life need not be restricted to the time that they're alive.  That a person's existence can influence things outside their own lifespan.

 The implication being that her daughter's story should include the events which are then told over the course of the rest of the film.  On first viewing, we naturally assume that Louise means her daughter's life and early death will somehow influence what happens between her and the aliens, because at this point in the movie we're assuming her daughter's life happened before the aliens arrived.

However:

 Louise-as-Narrator is actually stepping back to events which occured before her daughter's life.  As we realize later in the film, Louise's daughter hasn't been born yet, and that what she actually meant was that her daughter's story began before she was born.

All of this is over and done with by the time Louise-as-Narrator begins speaking.  The part about the Chinese ambassador meeting her at the book signing might still be in the future, but by the end of the movie she can remember her whole life, so that's not much of a limitation on her abilities as a narrator.

 This might even be something she's telling to her daughter, as she lies dying in the hospital bed.  Explaining why she did the things she did - how she met Hannah's father, why they divorced, etc.  This part is, of course, pure hypothesis on my part.

TLDR; Louise-the-Narrator is the one telling this story, from a specific moment in time for her character.  All the scenes in the movie are shown to us in the order she chooses to recount them.  The movie doesn't really specify when Louise-the-Narrator is speaking from, but as long as it's some point after she gained the ability to "remember" the future, it doesn't matter.  She can then recount any event that has happened - or will happen - in her life. *
* Subject to her ability to remember them.  We know memories of our past are not perfect, and it stands to reason her memories of the future will have similar flaws or gaps.  But obviously she remembers everything she tells us in the movie - at least, she never gives us any reason to think she's an unreliable narrator.


text:
Q: Failure sending email My test case is getting failed at assert.fail(), I am not having any clue what wrong it is going and where it is getting failed. Any idea to make this test case pass
Below is the test case
  <Test()> _
 Public Sub SendFtpFailureEmailShouldPassWithProcessingInfosAndSendEmail()
  Dim em As EmailNotification = New EmailNotification()
    Try
            Dim pfis As ProcessingFileInfos = New ProcessingFileInfos(New                FileInfo(AppSettingsReader.SchemaLocation), "Ftp")
            Dim pfi1 As ProcessingFileInfo = New ProcessingFileInfo(New   FileInfo("Test1.xml"))
            pfi1.ContainsErrors = True
            pfi1.Message = "File Failed"
            pfi1.FileProcessStatus = "F"
            pfi1.Channel = "Ftp"
            pfis.Add(pfi1)

            Dim pfi2 As ProcessingFileInfo = New ProcessingFileInfo(New FileInfo("Test2.xml"))
            pfi2.ContainsErrors = True
            pfi2.Message = "File Failed on Bad Data"
            pfi2.FileProcessStatus = "F"
            pfi2.Channel = "Ftp"
            pfis.Add(pfi2)

            Dim result As String = em.CreateFtpFailureEmail(pfis)
            Assert.IsNotEmpty(result, "result is invalid")

            Dim emailDetails As Email = New Email() With {.Body = result, _
                                           .FromEmail = AppSettingsReader.TPLFromEmail, _
                                           .FromEmailName = AppSettingsReader.TPLFromEmailName, _
                                           .SmtpHost = AppSettingsReader.SmtpHost, _
                                           .Subject = "FTP Failure Report", _
                                           .ToEmail = "runu.ali@cdsglobal.co.uk"}
            em.SendEmail(emailDetails)

        Catch ex As Exception
            Assert.Fail(ex.Message)
        End Try
    End Sub

sending mail code below:
  Public Sub SendEmail(ByVal emailObj As Email)

        Try
            If emailObj Is Nothing Then
                Throw New ArgumentNullException("emailObj", "emailObj cannot be null or empty")
            End If

            Dim em As New Net.Mail.MailMessage()

            em.From = New MailAddress(emailObj.FromEmail, emailObj.FromEmailName)
            em.To.Add(New MailAddress(emailObj.ToEmail))
            em.Subject = emailObj.Subject
            em.Body = emailObj.Body
            em.IsBodyHtml = True

            Dim SmTP As SmtpClient = New SmtpClient()
            SmTP.Host = emailObj.SmtpHost
            SmTP.Send(em)
        Catch ex As SmtpException
            Throw
        Catch ex As FormatException
            Throw

        End Try
    End Sub


text:
Q: JQuery hide table columns with rowspan I want to hide a table column, but using jQuery .hide() or .toggle() on columns with rowspan attribute seems to "pass" that attribute to the previous row and mess up the table.
$('#toggle').click(function(){
    $('#tbl td:last-child').toggle();
});

Look at the simple example at:
http://jsfiddle.net/SEwVP/
Any ideas?

A: The last td might be of a different column, so that's normal.
In this case where only the last column hold rowspans, you could use the child index :
$('#toggle').click(function(){
    $('#tbl td:nth-child(5)').toggle();
});

If you want a solution valid if you have rowspan in any column, then you'll probably have to precompute for each cell its real column index. It's doable but more it would probably be more rational to use simpler solutions, like having a class depending on the data. It thus would depend on the semantic and production process of your table.

A: Thanks to the @dystroy for his input.
Based on his answer, here's the simple solution:
var lastChilds = $('#tbl td:last-child');
lastChilds.each(function(i){
    var rowSpan = $(this).attr('rowspan');
    if(rowSpan !== undefined){
      lastChilds.splice(i+1, rowSpan-1);
    }
    $(this).hide();
  });


text:
Q: Embeding shiny app in pdf latex (R knitr) I know that it's impossible to put shiny app in pdf latex directly, but I've heard (How to embed an interactive shiny plot in a pdf / presentation? (via knitR maybe) HubertL's answer) it's possible to bind it via link. Can someone help me with that? I haven't found anything about this. I'm using beamer Madrid (Idk if it's important).

A: You have to publish the Shiny app first. Once you have got the URL to the online app, you can use knitr::include_url() to include an automatic screenshot of the app in non-HTML output formats. See https://bookdown.org/yihui/bookdown/web-pages-and-shiny-apps.html for more information.
Note that this feature currently requires the webshot package and PhantomJS:
install.packages("webshot")
webshot::install_phantomjs()


text:
Q: Creating models in JS with Async calls to an API I'm familiar with creating models in a synchronous environment like PHP or Ruby, but doing this in JS is pretty different.
Here's a model I've just started on and am stumped on how I'm going to return my value.
var Activity =  {
    get: function(params) {
        if (params.id) {
            return Activity.getById(params.id);
        }
    },

    getById: function(id) {
        $.get('/activities', {id: id})
            .success(function(activity) {
                return activity[0];
            });
    }
};

In .success() I want to return my result back to getById, but since it's in a callback, I'm not really sure where it goes.
Anyway, when I run this in the console I just get undefined.
What can I do here to return in this async style?

A: Indeed you cannot just return here.
One way would be to call a handler function with a corresponding parameter:
getById: function(id) {
    $.get('/activities', {id: id})
        .success(function(activity) {
            successFunction(activity[0]);
        });
}

A: You may add a callback:
getById: function(id, callback) {
    $.get('/activities', {id: id})
        .success(function(activity) {
            callback(activity[0]);
        });
}

In async programming, callbacks is how you "wait" for it to come back.

A: Don't use callback, use promises or Deferred if you want "kind of" sync code. (meaning it looks sync using return even though it is async behind the scene)
You basically just missed a return in your code:
var Activity =  {
    get: function(params) {
        if (params.id) {
            return Activity.getById(params.id).then(function(activity){
              console.log(activity)
            });
        }
    },

    getById: function(id) {
        return $.get('/activities', {id: id})// You need to return this!
            .success(function(activity) {
                return activity[0];
            });
    }
};

You can now just call it like that:
Activity.get({id: 5}).then(function(activity){JSON.stringify(activity)})

This would log two versions, the object one and then the stringified.

See the last example from there: https://api.jquery.com/deferred.then/
var request = $.ajax( url, { dataType: "json" } ),
  chained = request.then(function( data ) {
    return $.ajax( url2, { data: { user: data.userId } } );
  });

chained.done(function( data ) {
  // data retrieved from url2 as provided by the first request
});

You can use then or done, but if you use done then you won't be able to do anything else afterwards, while using then allows you to chain as much as you want to.


text:
Q: The total of rows fetched by Django's ORM filter is_null=True and is_null=False differs from the total of all rows. Why? Without going into details of my project, I think I am just not seeing something very simple here and need some fresh minds to look at it.
So, look at the following queries:
>>> p = MartProduct.objects.filter(source_id=2, eans__isnull=True).count()
100
>>> p = MartProduct.objects.filter(source_id=2, eans__isnull=False).count()
50
>>> p = MartProduct.objects.filter(source_id=2).count()
125

It is of course not important to know what the model and their fields represent. It is just a matter that the sum of the is_null=True and is_null=False should match the total number of rows. In other words I would expect the result of the last query to be 150 not 125! If it was the other way around (total number of objects > than the sum of the is_null=True and is_null=False then I could think of reasons for it but this is just weird).
What can be a cause for this? I can't think of any.
Thanks to anyone who will join this puzzle :)


text:
Q: Stream.io Chat API - Member state omitted from queryChannels response When I do the following:
      const queryChannelsResponse = await this.client.queryChannels(
        { id: channelId },
        { last_updated_at: -1 },
        { state: true },

This does not include the members. How am I able to get the member information?
I am writing a webhook and I want it to send a push notification (I am currently sending these myself via expo) to all offline users.
I am migrating from pusher chatkit which is now being discontinued. They had a new_message_users_offline hook for this purpose.
In the message.new webhook payload in the documentation the members are present but they are not present in the request body:
{
    "type": "message.new",
    "cid": "messaging:394f36fd-d512-4f2b-a785-ab8dfe82af49",
    "message": {
        "id": "f73ee1a8-f6fd-450b-bc64-0840b4df8fd9-2b4908ad-e267-4c48-8f41-8c26c8f769ce",
        "text": "Ffddf",
        "html": "
Ffddf
\n",
        "type": "regular",
        "user": {
            "id": "f73ee1a8-f6fd-450b-bc64-0840b4df8fd9",
            "role": "user",
            "created_at": "2020-04-06T14:06:37.979584Z",
            "updated_at": "2020-04-06T19:45:39.556842Z",
            "last_active": "2020-04-06T19:45:39.54939Z",
            "banned": false,
            "online": true,
            "name": "Mark Everett",
            "image": "https://8dc-user-files-dev.s3.eu-west-1.amazonaws.com/MEMBER_PROFILE_IMAGE-f73ee1a8-f6fd-450b-bc64-0840b4df8fd9.png?v=6"
        },
        "attachments": [],
        "latest_reactions": [],
        "own_reactions": [],
        "reaction_counts": null,
        "reaction_scores": {},
        "reply_count": 0,
        "created_at": "2020-04-06T19:51:14.114803Z",
        "updated_at": "2020-04-06T19:51:14.114803Z",
        "mentioned_users": []
    },
    "user": {
        "id": "f73ee1a8-f6fd-450b-bc64-0840b4df8fd9",
        "role": "user",
        "created_at": "2020-04-06T14:06:37.979584Z",
        "updated_at": "2020-04-06T19:45:39.556842Z",
        "last_active": "2020-04-06T19:45:39.54939Z",
        "banned": false,
        "online": true,
        "channel_unread_count": 0,
        "channel_last_read_at": "1970-01-01T00:00:00Z",
        "total_unread_count": 0,
        "unread_channels": 0,
        "unread_count": 0,
        "image": "https://8dc-user-files-dev.s3.eu-west-1.amazonaws.com/MEMBER_PROFILE_IMAGE-f73ee1a8-f6fd-450b-bc64-0840b4df8fd9.png?v=6",
        "name": "Mark Everett"
    },
    "watcher_count": 1,
    "created_at": "2020-04-06T19:51:14.121213459Z",
    "channel_type": "messaging",
    "channel_id": "394f36fd-d512-4f2b-a785-ab8dfe82af49"
}

My plan is do do something like this:
  public async getOfflineUserIds(channelId: string): Promise<string[]> {
    try {
      // Get the channel
      const queryChannelsResponse = await this.client.queryChannels(
        { id: channelId },
        { last_updated_at: -1 },
        { message_limit: 0, limit: 1, state: true},
      )
      const channel = queryChannelsResponse[0]

      console.log('channel: ', channel)

      // Get the channels members
      const userIds: string[] = []
      // tslint:disable-next-line: forin
      for (const index in channel.state.members) {
        userIds.push(channel.state.members[index].user_id)
      }
      console.log('userIds:', userIds)

      const queryUsersResponse = await this.client.queryUsers(
        { id: { $in: userIds } },
        { last_active: -1 },
        {},
      )

      console.log('queryUsersResponse:', queryUsersResponse)

      // Work out who is offline/online
      const offlineUserIds = queryUsersResponse.users
        .filter(u => !u.online)
        .map(u => u.id)

      return offlineUserIds
    } catch (err) {
      throw new InternalServerErrorException(
        'Error getting offline users for channel.',
        err,
      )
    }
  }

A: This is now resolved.
I did not add the members to the channel with channel.addMembers. I create and add members on the server as this works perfectly for my use case.
If it helps anyone I ended up with these two methods:
  public async getChannelUserIds(channelId: string): Promise<string[]> {
    try {
      const queryChannelsResponse = await this.client.queryChannels(
        { id: channelId },
        { last_updated_at: -1 },
        { message_limit: 0, limit: 1, state: true },
      )
      const channel = queryChannelsResponse[0]

      const userIds = Object.keys(channel.state.members)
      console.log('userIds:', userIds)

      return userIds
    } catch (err) {
      throw new InternalServerErrorException(
        `Error getting user ids for channel ('${channelId}').`,
        err,
      )
    }
  }

  public async getOfflineUserIds(userIds: string[]): Promise<string[]> {
    try {
      const queryUsersResponse = await this.client.queryUsers(
        { id: { $in: userIds } },
        { last_active: -1 },
        {},
      )

      console.log('queryUsersResponse:', queryUsersResponse)

      const offlineUserIds = queryUsersResponse.users
        .filter(u => !u.online)
        .map(u => u.user_id)

      return offlineUserIds
    } catch (err) {
      throw new InternalServerErrorException(
        `Error getting offline user ids from ('${JSON.stringify(
          userIds,
          null,
          2,
        )}').`,
        err,
      )
    }
  }

And then in my webhook I:
@Post('stream/messages')
  public async onReceive(
    @Req() req: Request,
    @Headers('x-signature') signature: string,
    @Body() body: any,
  ) {
    try {
      console.debug('webhooks-stream.messages.onReceive')
      this.chatService.verifyWebhook((req as any).rawBody, signature)

      console.log('DEBUG WEBHOOK BODY', JSON.stringify(body, null, 2))

      switch (body.type) {
        case 'message.new': {
          const offlineMemberIds = await this.chatService.getOfflineUserIds(
            body.members.map(member => member.user_id),
          )

      ...


text:
Q: Cucumber+Devise routing error having trouble with testing devise sign up on Cucumber. After "Sign Up" click
it shows
uninitialized constant User::ArticlesController (ActionController::RoutingError)
I suppose that's because right after Sign up, devise redirects logged user to Articles page and but it's not under namespace User. Because I test user it put everything under this namespace.

A: This Devise howto says you can route to something not under the User namespace by naming a user_route path:
match 'my/dashboard' => 'my/dashboard#index', :as => 'user_root'

So it sounds like you can do something like:
match 'articles' => 'articles#index', :as => 'user_root'


text:
Q: how to compile and run android application using a batch file and not IDE? How can i compile and run android application using a batch file and not any other IDE? is it  possible to do? and if it is possible, can you teach me how to make a batch file? I don't have any idea to it, I only know how to run id using eclipse ide.  thank you.

A: From android doc, i'll just add debug mode:
Debug mode

For immediate application testing and debugging, you can build your
  application in debug mode and immediately install it on an emulator.
  In debug mode, the build tools automatically sign your application
  with a debug key and optimize the package with zipalign.
To build in debug mode:
Open a command-line and navigate to the root of your project
  directory.
Use Ant to compile your project in debug mode: ant debug
  This creates your debug .apk file inside the project bin/ directory,
  named -debug.apk. The file is already signed with
  the debug key and has been aligned with zipalign. Each time you change
  a source file or resource, you must run Ant again in order to package
  up the latest version of the application.
To install and run your application on an emulator, see the following
  section about Running on the Emulator.

How to run

Before you can run your application on a device, you must perform some
  basic setup for your device:
Enable USB debugging on your device. On most devices running Android
  3.2 or older, you can find the option under Settings > Applications > Development. On Android 4.0 and newer, it's in Settings > Developer
  options.
Note: On Android 4.2 and newer, Developer options is hidden
  by default.
To make it available, go to Settings > About phone and tap
  Build number seven times.
  Return to the previous screen to find
  Developer options.
Ensure that your development computer can detect
  your device when connected via USB Read Setting up a Device for
  Development for more information.
Once your device is set up and connected via USB, navigate to your
  SDK's platform-tools/ directory and install the .apk on the device:
adb -d install path/to/your/app.apk
The -d flag specifies that you
  want to use the attached device (in case you also have an emulator
  running).

A simple batch for debug mode could be:
set PROJECT_ROOT="Your_project_root"
set ADB_LOCATION="Your ADB Location"
set PROJECT_NAME="Your project name"
cd %PROJECT_ROOT%
ant debug
cd %ADB_LOCATION%
adb -d install %PROJECT_ROOT%/bin/%PROJECT_NAME%-debug.apk

Compile in release mode is a bit more longer, so i would say read the documentation.


text:
Q: save upload file to dynamic directory and get the path for store in db I'm uploading a file and additionally some data like file's id and file's title to the server. I have the view below to handle the request and I want to save the file to a dynamic path like upload/user_id/thefile.txt.
With code the below the file will be saved in and upload folder directly and also my product_video table will create a new record with the related id and the title.
Now I don't have any idea how can I save the file in a dynamically generated directory like: upload/user_id/thefile.txt and how to save the produced path to the database table column video_path?
view class:
class FileView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, *args, **kwargs):
        if request.method == 'POST' and request.FILES['file']:
            myfile = request.FILES['file']
            serilizer = VideoSerializer(data=request.data)
            if serilizer.is_valid():
                serilizer.save()

            fs = FileSystemStorage()
            fs.save(myfile.name, myfile)

            return Response("ok")

        return Response("bad")

and serializer clas:
class VideoSerializer(ModelSerializer):
    class Meta:
        model = Product_Video
        fields = [
            'p_id',
            'title',
            'video_length',
            'is_free',
        ]

and related model class:
def user_directory_path(instance, filename):
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class Product_Video(models.Model):
    p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_video')
    title = models.CharField(max_length=120, null=True,blank=True)
    video_path = models.FileField(null=True, upload_to=user_directory_path,storage=FileSystemStorage)
    video_length = models.CharField(max_length=20, null=True, blank=True)
    is_free = models.BooleanField(default=False)

A: You put the cart before the horse. Start from the beginning, first things first. And the first thing is the user story, then the model layer.
There are Products and a Product can have many ProductVideos. A Product has an Author (the Author can have many Products). When you upload a ProductVideo for a particular Product, you want to save it in a directory which contains the Author ID.
Therefore we specify a callable for the FileField which should dynamically find out the id of the Author:
def user_directory_path(instance, filename):
    # get the id of the author
    # first get the Product, then get its author's id
    user_id = str(instance.p_id.author.id)
    # little bit cosmetics
    # should the filename be in uppercase
    filename = filename.lower()
    return 'user_{0}/{1}'.format(user_id, filename)

When saving an instance of Product_Video the uploaded file should be stored in a directory with a dynamically created pathname based on the author's ID.
Further I'd suggest you to follow established coding conventions:

*

*don't use snake_case for class names, especially don't mix it with capital letters. Use PascalCase, preferably singular nouns, for class names: ProductVideo

*if your model class is ProductVideo, keep that name in all subsequent classes: ProductVideoSerializer for the model serializer and ProductVideoAPIView for the generic view.

*use verbs for methods and standalone functions, get_user_directory or upload_to_custom_path is better than user_directory_path.

*also avoid suffixing the foreign key fields with _id. Use rather product instead of p_id. Django will allow you to access the related object by calling product and get the id of the object by calling product_id. Using the name p_id means you'll access the id of the related object by calling p_id_id which looks very weird and confusing.


text:
Q: Get values from Subclasses Java I am making a computer pricing program in Java. I am trying to figure out a way to generate subclasses determined by the user output. Heres my code so far. I realize I am running the same methods multiple times but I dont know any other way to get the variable in order to test the output.  For some reason when the b.getScreenPrice(screenPrice) isn't executed when 2 is picked. Any answers if of help. thanks
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Computer {
    InputStreamReader in = new InputStreamReader(System.in);

    BufferedReader keyboard = new BufferedReader(in);

    public Computer() {

    }

    public String pickComputer() {
        String comp = null;
        System.out.println("Select a number for desired computer:");
        System.out.println("1. Desktop");
        System.out.println("2. Laptop");
        try {
            comp = keyboard.readLine();
            if (comp.equals("1")) {
                comp = "Desktop";
            }
            if (comp.equals("2")) {
                comp = "Laptop";
            }
        } catch (IOException e) {
            pickComputer();
        }
        return comp;
    }

    public class Notebook extends Computer {
        public String getScreenSize() {
            String size = null;
            System.out.println("Select a number for the desired screen size:");
            System.out.println("1. 19 inch ($200)");
            System.out.println("2. 17 inch ($150)");
            System.out.println("3. 15 inch ($100)");
            try {
                size = keyboard.readLine();

                if (size.equals("1")) {
                    size = "19";
                }
                if (size.equals("2")) {
                    size = "17";
                }
                if (size.equals("3")) {
                    size = "15";
                }

            } catch (IOException e) {
                getScreenSize();
            }
            return size;

        }

        public int getScreenPrice(String screen) {
            int sPrice = 0;
            if (screen.equals("19")) {
                sPrice = 200;
            }
            if (screen.equals("17")) {
                sPrice = 150;
            }
            if (screen.equals("15")) {
                sPrice = 100;
            }
            return sPrice;

        }

        public void calculatePrice(int screeen) {
            System.out.println(screeen);
        }

    }

    public class ComputerTester {
        public static void main(String[] args) {

            Computer a = new Computer();
            Notebook b = new Notebook();
            String screenSize = b.getScreenSize();
            String newComputer = a.pickComputer();

            if (newComputer.equals("Desktop")) {
                System.out.println("Test Worked");
            }
            if (newComputer.equals("Laptop")) {
                b.getScreenPrice(screenSize);
            }
        }
    }
}

Output:
Select a number for the desired screen size:
1. 19 inch ($200)
2. 17 inch ($150)
3. 15 inch ($100)
1
Select a number for desired computer:
1. Desktop
2. Laptop
2

A: Try changing your code to use
size = keyboard.readLine().trim();

This will trim any trailing and leading whitespace. If you were print out your size, I bet it would have a new line character on the end of it cause by pressing enter.

A: In your getScreenPrice(String) method, you are returning an int value but in your main method you are just calling the method.  You are not setting an int value or anything.  So what is happening is your code is working fine if nothing happens when you choose 2 because at the end of your program "nothing" is suppose to happen.
Try changing this:
        if (newComputer.equals("Laptop")) {
            b.getScreenPrice(screenSize);
        }

in this:
        if (newComputer.equals("Laptop")) {
           int price = b.getScreenPrice(screenSize);
           System.out.println(price.toString());
        }

I think what youre looking for will appear


text:
Q: Почему увеличивается количество проходов по куску кода? Есть код со структурой Выбрали Х->Выбрали У->Выбрали З->Подгружаем Ajax (Прошу обратить внимание на console.log(response); в Ajaxe)
jQuery(document).ready(function(){

$('input:radio[name="item01_radio"]').change(function() {

    $('input:radio[name="item11_radio"]').change(function() {

        $('input:radio[name="radio_service"]').change(function() {

            var service = $('input:radio[name="radio_service"]:checked').val();
            var day_ajax = $('input:radio[name="item11_radio"]:checked').val();
            var user_name = document.getElementById("user_name").value;

            document.getElementById('item4').innerHTML = "";
            var elem = document.getElementById('item4');

            $.ajax({
                type: "POST",
                url: 'php/array_master_time.php',
                data: {
                    "master": user_name, "date_name_general": day_ajax, "service": service
                },

                success: function(response)
                {
                    var response = JSON.parse(response);

                    console.log(response);
                },
                error: function(jqXHR, exception)
                {
                    if (jqXHR.status === 0) {
                        alert('НЕ подключен к интернету!');
                    } else if (jqXHR.status == 404) {
                        alert('НЕ найдена страница запроса [404])');
                    } else if (jqXHR.status == 500) {
                        alert('НЕ найден домен в запросе [500].');
                    } else if (exception === 'parsererror') {
                        alert("Ошибка в коде: \n"+jqXHR.responseText);
                    } else if (exception === 'timeout') {
                        alert('Не ответил на запрос.');
                    } else if (exception === 'abort') {
                        alert('Прерван запрос Ajax.');
                    } else {
                        alert('Неизвестная ошибка:\n' + jqXHR.responseText);
                    }
                }
            });
        });
    });
});

});
В итоге на выходе я получаю такую закономерность: если я выбираю Х,У,З (выводится console.log(response); 1 раз), после меняю выбор предположим У и дальше выбираю также З, то console.log(response); выводится уже два раза (в общей сумме в консоли я уже имею три вывода), и тд с увеличением на единицу. Если в показанной мною структуре нет ошибки и такого быть не должно, то после я отредактирую вопрос и выложу полный код.

A: Все нормально, кода достаточно.
Давайте расскажем человеческим языком, что здесь происходит.
$('input:radio[name="item01_radio"]').change(function() {

    $('input:radio[name="item11_radio"]').change(function() {

        $('input:radio[name="radio_service"]').change(function() {

            ...

На событие изменения выбранной радиокнопки с именем item01_radio назначается (но не выполняется) обработчик события изменения выбранной радиокнопки с именем item11_radio. Если Вы теперь еще раз измените выбранную радиокнопку с именем item01_radio, радиокнопкам item11_radio назначится еще один такой же обработчик - таких обработчков будет прикреплено к кнопкам item11_radio уже два. Если теперь Вы измените выбранную радиокнопку с именем item11_radio, выполнятся оба эти обработчика. Дальше в этой цепочке происходит то же самое, только на уровень глубже.
Простое правило - избегайте навешивать обработчики событий внутри других обработчков событий. Исключение - событие $(document).ready.

$('input:radio[name="item01_radio"], input:radio[name="item11_radio"], input:radio[name="radio_service"]').change(function() {

    var service = $('input:radio[name="radio_service"]:checked').val();
    var day_ajax = $('input:radio[name="item11_radio"]:checked').val();
    var item01 = $('input:radio[name="item01_radio"]:checked').val();

    if (service == '' || day_ajax == '' || item01 == '')
        return;

    ...


text:
Q: Dynamically building a Boolean expression I'm writing some code that increments the number at the end of a filename until it's no longer overwriting an existing file. I'm creating several files, all with the same base filename but different extensions, none of which I want to overwrite.
Naive version:
prefix = 'hello0'
while os.path.exists(prefix + '.abc') or os.path.exists(prefix + '.def') or os.path.exists(prefix + '.ghi'):
    n = int(prefix[-1])
    prefix = prefix[:-1] + str(n + 1)  # I know this doesn't work when n reaches two digits; my full code involves a regular expression

The condition could obviously get very long and ugly when there are more than a couple of extensions. I abstracted this into a for loop.
My version:
prefix = 'hello0'
extensions = ('.abc', '.def', '.ghi')  # there could be even more than this
condition = True
while condition:
    condition = False
    # if any of the paths still exist, set the condition back to True
    for extension in extensions:
        if os.path.exists(prefix + extension):
            condition = True

    n = int(prefix[-1])
    prefix = prefix[:-1] + str(n + 1)

I still feel this to be a little bit clunky: it's not entirely clear what the while loop is actually testing. Is it possible to build a Boolean expression dynamically, rather than setting a Boolean value?
I think the following might work (I haven't tested it, I only thought of it while writing this!) but I don't think I should have to resort to eval:
prefix = 'hello0'
extensions = ('.abc', '.def', '.ghi')

test = 'False'
for extension in extensions:
    test += " or os.path.exists(prefix + '" + extension + "')"
while eval(test):
    n = int(prefix[-1])
    prefix = prefix[:-1] + str(n + 1)

A: You might want to use the any() built-in with a generator:
while any(os.path.exists(prefix + extension) for extension in extensions):

    # then increment prefix and try again, as in your example code

This computes the True or False that you need with a simpler syntax.
In general, if I ever feel the temptation to use eval() in a dynamic language like Python, then it means that there is an important language feature that I need to learn about. Dynamic languages are supposed to make code beautiful without the disaster of trying to write and maintain code-that-writes-more-code — so you have done exactly the right thing here by asking about your approach.


text:
Q: Finding a bug using Xcode - attempt to insert nil value I am getting a random bug in my app, which is causing it to crash. The problem I am facing is XCode doesn't tell me where the crash is happening only the below information. Can someone tell me how I can find out where I might be able to find the problem within the code? It must be crashing at the same point as when the app does crash it always shows the below.

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary
  setObject:forKey:]: attempt to insert nil value (key: 0)'
  * First throw call stack: (0x381e48bf 0x37d301e5 0x381e47b9 0x381e47db 0x381516bb 0x9237b 0x91121 0x8f0c5 0x8abc1 0x37b9d 0x8b68f
  0x3550850f 0x381b0577 0x3813c0cf 0x3547c3fb 0x3547dc2b 0x8d005
  0x3814322b 0x34495 0x32e31 0x3372d 0x30a59 0x3813e435 0x7b1df 0x7b88d
  0x79e25 0x31ca650f 0x31ca5f01 0x31c8c4ed 0x31c8bd2d 0x37f12df3
  0x381b8553 0x381b84f5 0x381b7343 0x3813a4dd 0x3813a3a5 0x37f11fcd
  0x31cba743 0x89e8b 0x24a4) terminate called throwing an
  exception(lldb)

A: Have you turned on exception breakpoints? Click the + at the bottom left of the Breakpoint Navigator, then select Add Exception Breakpont.

You can right click the breakpoint to edit it…

This will cause the code to stop at the point where the error occurs.

A: There is a solution that I usually use on my projects, setting up some special breakpoint.
To do that:

*

*Open XCode

*Goes to "View -> Navigators -> Show Breakpoint Navigators"

Now add some new breakpoints clicking the "+" button:

*

*Add exception breakpoint

*Add Symbolic breakpoint with symbol [NSException raise]

*Add Symbolic breakpoint with symbol objc_exception_throw
Run again your project, application will stop on the line that is causing your problems.

A: error is evident enough. in any of your line, where you are setting some object for dictionary, you key is nill, which is not allowed

A: your problem is that you are using setObject: forKey Method to NSDictionary just make it NSMutableDictionary then try this method you can't assign value for NSDictionary like you are trying it's only for NSMutableDictionary.
i hope you will get my point what i am try to say.

A: Try this:
if([myDictionary objectForKey:@"string"]!= nil && [myDictionary objectForKey:@"string"]!= Nil) { }


text:
Q: Understanding secondary constructor in Kotlin I don't understand the use of this and how the object is created or constructor is called and what's happening in the below code.
class Person {
    var children: MutableList<Person> = mutableListOf<Person>();
    constructor(parent: Person) {
        parent.children.add(this)
    }
}

class Person(val name: String) {
    var children: MutableList<Person> = mutableListOf<Person>();
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

source : https://kotlinlang.org/docs/reference/classes.html

A: : this(...) call means call to another constructor, so each object was constructed with the primary constructor too.
class Person /* a */ (val name: String) {
    var children: MutableList<Person> = mutableListOf<Person>();
    /* b */ constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

In this example, there is primary constructor after a, and secondary one after b, so there are two ways to instantiate this class.

*

*Call the primary constructor: Person("abc").

*Call the secondary constructor: Person("abc", Person("dfg")), and it is guaranteed that both primary and secondary constructor will be called.