text:
Q: Every second customer converts better. Can this be by chance? At a bank customers are applying for a loan and then the customer gets a loan-offer which they can choose to accept or not. This bank has been running for 11 weeks and by coincidence a developer saw that odd applications-ids in average generate higher accepted amounts than even application-ids, every week. Application-id is just an incrementing number in the database, so has nothing to do with real world. There is no reason for why this would happen, so the question is, how likely is this to happen by chance? Someone said this can happen because splitting on odd/even application-id is not purely random. But isn't it random enough?
In the image you see the data:

*

*Column 1: week

*Column 2: group (even/odd application-id)

*Column 3: number of applications

*Column 4: number of accepted offers

*Column 5: sum of accepted amount

*Column 6: a flag if the accepted amount is bigger for odd application-ids (which it is for all 11 weeks)

*Column 7: A calculation by how much the accepted amount is bigger for odd application-ids.

A: With just the  data you've posted, you can analyze it as a binomial distribution with each week being at trial. That would give a p-value of $2^{-11}$, or about $0.05\%$. You could also do a paired test, which would give you a binomial distribution with each pair of ids being a trial. Then there's a t-test on the total accepted amounts over odd ids and evens, but there's the issue of whether the underlying distribution is sufficiently normal.
Choosing what statistical test to do is problematic when you've already seen the data, as you'll be tailoring the test to match the pattern that you've already seen. However, there are different standards for when you're making a conclusion, versus when you're looking at whether something warrants further study. A p-value of $0.02\%$, even if it may be the result of p-hacking, justifies further investigation.
The data you've presented is very summary. You should get a more detailed look at the data. For instance, create a scatter plot with date of loan on one axis, size of loan (or perhaps log of size, if they are distributed over many orders of magnitude) on another, and different colors for odd or even ids.

A: There are a number of statistical test you could use to answer a question like this, but the simplest is the 2×2 chi-square contingency test (example here).

A: Just add up all the accepted applications with odd and even IDs across all the dates so that you have two numbers: $N_{odd}, N_{even}$. Call your random variable $X \in \{0,1\}$ where 0 means even and 1 means odd. The ex-ante probability of $X=0$ (given that odd/even is random) is $p=0.5$. You've got $N=N_{odd}+N_{even}$ trials and you want to know the probability that $N_{even}$ of them are even given $p=0.5$. So, the distribution you want is the Binomial distribution, and thus $X\sim Binomial(N,p)$.
If $P(X=1\mid N,p)<x$ where $x$ is something suitably small, then you have a problem. If not then you could say it was chance.

A: At face value you have 11 samples in every case with B bigger than A.  There are 2048 choices that could have happened (2^11) - viewing the choices as 11 binary bits makes it easy to visualise (assume bit is 0 for A>B and 1 for A<B).  There is only one way B could always be bigger - the bit sequence 11111111111.  But you had no a priori reason to think B would be bigger, so the equally extreme sequence 00000000000 is also equally valid.  That would lead to a 1 in 1024 chance of the observed effect, highly significant (P~=0.001)
BUT as people have noted, you've only asked because you've seen an extreme pattern.  So maybe 1023 other banks never asked.
AND look 2/3 of the way down your table.  "B is bigger" seems to be untrue for 533 vs 527 (it is untrue for the ratios as well).  So we've back to a lower probability, as any of the 11 could be 'reversed' and be just as extreme as your data.  So that's another 22 cases that are just as extreme.  So that's 24 of 2048, which is no longer significant at p=0.01.
Bottom line however - you're a new bank, it is quite an extreme pattern.  I'd believe it was a true effect until I saw contradictory data.  I don't know what programming language you're using but I'd suspect a reuse of a variable is causing the problem (or less likely a memory leak)
There is more information available in the actual ratios than in just saying whether A>B, but this is already enough of a smoking gun to look at the code - anything could happen statistically, it's not proof, the proof will be finding what's wrong with the code.


text:
Q: Writing a generic with chaining instead of columns of grid I have some columns in my script like following :
  <script>
  $("#grid").kendoGrid({
              height: 400,
              columns: [
                 "ProductName",
                 { field: "UnitPrice", format: "{0:c}", width: "150px" },
                 { field: "UnitsInStock", width: "150px" },
                 { field: "Discontinued", width: "100px" },
                 { command: "destroy", title: "Delete", width: "110px" }
              ]
  });
  </script>

I want to write extension method using generic and chaining I need something like this in c# :
   <% Page.Grid<Product>()
     .Columns.Add(c=> {
       c.add("ProductName").Title("Product Name");
       c.add("UnitPrice").Title("Unit Price").Width("150px");
     }).Render(); %>

how I can write c# method extension for it I need to use this method in asp.net form.

A: I finally found out my own answer:
Kend._2013.Extension.KendoGrid<string>.Name("KendoGrid1")
                                          .Columns(c => new Kend._2013.Extension.Column[]
                                          {
                                                c.Add("ProductID").Title("ID").Width(100),
                                                c.Add("ProductName").Title("Name").Width(150),
                                                c.Add("UnitPrice").Title("Price").Width(150),
                                                c.Add("Discontinued").Title("Amount").Width(150),
                                                c.Add("UnitsInStock").Title("Units In").Width(150),
                                          });

    namespace Kend._2013.Extension
{
    public class Column
    {
        private string fieldName;
        private string title;
        private int width;
        private int height;

        private readonly Column previous;
    private Column(Column previous)
    {
        this.previous = previous;
    }

    public Column Add(string name)
    {
        this.fieldName = name;
        return new Column(this);
    }

    public Column Title(string t)
    {
        this.title = t;
        return new Column(this);
    }

    public Column Width(int w)
    {
        this.width = w;
        return new Column(this);
    }

    public Column Height(int h)
    {
        this.height = h;
        return new Column(this);
    }
}

public class KendoGridDataSource
{
}

public class KendoGrid<T>
{
    private readonly T target;
    private readonly KendoGrid<T> previous;

    private KendoGrid(T target, KendoGrid<T> previous)
    {
        this.target = target;
        this.previous = previous;
    }

    public static KendoGrid<T> Name(T target)
    {
        return new KendoGrid<T>(target, null);
    }

    private bool isFitInPage;
    private int height;
    private int width;
    private Column columns;
    private bool pageable;
    private bool sortable;
    private bool filterable;
    private bool editable;
    private string uICulture;
    private bool showContextMenu;
    private bool showFilterMenu;
    private bool showGroupArea;
    private bool showToolbars;
    private KendoGridDataSource DataSource;
    private bool DataBatching;

    private void FitToPage(bool b)
    {
        this.isFitInPage = b;
    }
    public KendoGrid<T> Height(int h)
    {
        this.height = h;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> Width(int w)
    {
        this.width = w;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> Pageable(bool pageable)
    {
        this.pageable = pageable;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> Sortable(bool sortable)
    {
        this.sortable = sortable;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> Filterable(bool filterable)
    {
        this.filterable = filterable;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> Editable(bool editable)
    {
        this.editable = editable;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> ShowContextMenu(bool show)
    {
        this.showContextMenu = show;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> ShowFilterMenu(bool show)
    {
        this.showFilterMenu = show;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> ShowGroupArea(bool show)
    {
        this.showGroupArea = show;
        return new KendoGrid<T>(target, this);
    }
    public KendoGrid<T> ShowToolbars(bool show)
    {
        this.showToolbars = show;
        return new KendoGrid<T>(target, this);
    }

    public KendoGrid<T> Columns(Expression<Func<Column, Column>> col)
    {
        var a = col.Compile();
        Column c = new Column();
        a(c);
        return new KendoGrid<T>(target, this);
    }
    public void Render(){ // write html }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What problems can I solve using recursion in this code? BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::customers()

My Service class:
namespace App;

use Illuminate\Database\Eloquent\Model;

class Service extends Model
{
         protected $fillable = [
        'title', 'type','link','description','customer_id','user_id'
    ];
        public $timestamps = false;

        public function customers(){
        return $this->belongsTo('App\Customer');

    }
        public function user(){
        return $this->belongsTo('App\User');

    }
}

My ServiceController  class:
class ServiceController extends Controller
{
        public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:customers|max:255',
            'type' => 'required',
            'link' => 'required',
            'description' => 'required',

        ]);

        $services = new Service();
        $services->title = $request['title'];
        $services->type = $request['type'];
        $services->link = $request['link'];
        $services->description = $request['description'];
        $services->customer_id = Customer::customers()->id;
        $services->save();

        return redirect('/services');
    }


text:
Q: Use cases of bootstrapping maven I've seen some companies using maven bootstrap binary, instead of the one You get by the package manager.
What are the typical use cases of bootstrapping maven?

A: It is useful when you want to use different Maven versions on different projects. Besides that it requires less setup on new environment, because the required version is encapsulated and under configuration control. Also, it can be the case of using a newer version that the one provided by the package manager.
maven-wrapper is a tool that simplifies this pattern.

A: When you willing Docker as containers to build your app in clouds for example.


text:
Q: Global instances of a class in Objective C I was wondering how to pass objects as parameters in objective C. As you can see, in my code, Obj1 * myObj1 is out of scope for the btnIncrementObj1 method. How do I put it in scope? I'm thinking that there is a way to make instances of a class as static.
As you can see, I only want myObj1 to be instantiated on a button press, not when a view is loaded.
Is there a way to make Obj1 static, or give it a global scope?
- (IBAction)btnCreateObj1:(UIButton *)sender
{
    Obj1 * myObj1 = [[Obj1 alloc] init];

    int intVal = [self.textField.text intValue];

    [myObj1 increment:intVal];

    [myObj1 restring:@"orig string 1"];

    NSString * newLabel = [self.labelObject1.text stringByAppendingFormat:@"value:%d string:%@",myObj1.value,myObj1.someString];

    self.labelObject1.text = newLabel;
}

- (IBAction)btnIncrementObj1:(UIButton *)sender
{
    //-I want to increment myObj1.value by [self.textField.text intValue]
}

A: If you want to access a variable throughout the class, then make it as a class member.

A: OK, here's my answer.  This expands on the one given by Lanc.
Firstly, you need to decide what the scope  of myObj1 should be.  Do you want one per instance of the class or only one for the whole application.  If it's per instance of the class, make an instance variable and have a property that creates it on demand. e.g.
@interface MyViewController : UIViewController

@property (nonatomic, readonly, retain) Obj1* myObj1;

// other stuff

@end

@implementation MyViewController
{
@private
    Obj1* myObj1;
}

-(Obj1*) myObj1
{
    @synchronized(self) // if you know you are single threaded you can omit the @synchronized block
    {
        if (myObj1 == nil)
        {
            myObj1 = [[Obj1 alloc] init];
        }
    }
    return myObj1;
}

- (IBAction)btnCreateObj1:(UIButton *)sender
{
    [[self myObj1] increment:intVal];

    [[self myObj1] restring:@"orig string 1"];

    NSString * newLabel = [self.labelObject1.text stringByAppendingFormat:@"value:%d string:%@",myObj1.value,myObj1.someString];

    self.labelObject1.text = newLabel;
}

- (IBAction)btnIncrementObj1:(UIButton *)sender
{
    [[self myObj1] increment: [self.textField.text intValue]];
}

If you need a singleton (i.e. only one object per program), you can use a static variable as per wizH's answer but I prefer using a method to access it.  So the following will work:
@interface MyViewController : UIViewController

@property (nonatomic, readonly, retain) Obj1* myObj1;

// other stuff

@end

@implementation MyViewController

-(Obj1*) myObj1
{
    static Obj1* myObj1 = nil; // instance var moved to be a static variable
    @synchronized([MyViewController class) // if you know you are single threaded you can omit the @synchronized block
    {
        if (myObj1 == nil)
        {
            myObj1 = [[Obj1 alloc] init];
        }
    }
    return myObj1;
}

- (IBAction)btnCreateObj1:(UIButton *)sender
{
    [[self myObj1] increment:intVal];

    [[self myObj1] restring:@"orig string 1"];

    NSString * newLabel = [self.labelObject1.text stringByAppendingFormat:@"value:%d string:%@",myObj1.value,myObj1.someString];

    self.labelObject1.text = newLabel;
}

- (IBAction)btnIncrementObj1:(UIButton *)sender
{
    [[self myObj1] increment: [self.textField.text intValue]];
}

Notice how the only thing that has changed is the way the API for the class is satisfied.  No code that uses the API has to change.

A: You should create your object right after the
@implementation

Here you can create it as a static object:
static Obj1* _myObj1 = nil;

From here on you can access it from other classes like this:
[Obj1 myObj1].property

A: Your .h file should import the object you want to keep and create a member of the object in that class.
It would look something like this.
#import "Obj1.h";

@interface MyViewController : UIViewController{
    Obj1 * myObj1;
}

I wouldn't init a class variable in a IBAction method, but you can do it.
In the button that creates you can keep the same code. But in your other method, just check if the myObj1 is created.
- (IBAction)btnIncrementObj1:(UIButton *)sender
{
    if(myObj1){
        //Handle the increment.
    }else{
        //Handle what to do if you haven't clicked the other button before this one.
    }
}

And for good memory managment you should release the object in dealloc
-(void) dealloc{
    if(myObj1){
        [myObj1 release];
    }
    [super dealloc];
}


text:
Q: Why am I not getting the desired output even though no errors? Program to find the next palindrome to the inputted number
When compiling, only the first part asking input value compiles. After that nothing happens
#include<stdio.h>

void main()
{
    int n,revNum = 0,remainder,d,revD = 0;

    printf("Enter an non palindromic number:");
    scanf("%d",&n);

    d = n;

    while (d != revD)
    {
         n += 1;
         d = n;

          while (n != 0)
          {
            remainder = n%10;
            revNum = (revNum * 10) + remainder;
            n = n/10;
          }
         n = d;
         revD = revNum;
    }
    printf("\nThe nearest palindrome is %d",d);
}

Is there something wrong in the way I approached the problem?

A: You forgot to re-initilize revNum to 0 in the outer loop.
And of course, as the other answers already point out, the issue is related to a logical mistake. That's why the compiler did not complain at all.
For instance I figured it out by adding prints inside the inner loop. After some tests I found out that it was working great with immediate predecessors of palindrom numbers (e.g. 43, 98, 100) but it was diverging with other numbers. By printing the internal variables I understood the purpose of revNum and that it was supposed to be re-initialized at every iteration of the outer while loop.
...
while (d != revD)
{
     n += 1;
     d = n;
     revNum = 0; //ADD THIS

     while (n != 0)
     {
        ...
     }
}
...


text:
Q: Installation issue with numba library on python 3 I am trying to install numba in python however it gives me this error down below, how would I be able to fix it. I am using a 64 bit windows 10 system and using python 3.9. It gives me a wheel error even though I have installed wheel using pip.
CMD Error:
  Building wheel for numba (setup.py) ... error
  ERROR: Command errored out with exit status 1:
command: 'c:\python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\maste\\AppData\\Local\\Temp\\pip-install-4uo3q6pv\\numba_24f4c114cf4a4628ab2eab71e4fa46a4\\setup.py'"'"'; __file__='"'"'C:\\Users\\maste\\AppData\\Local\\Temp\\pip-install-4uo3q6pv\\numba_24f4c114cf4a4628ab2eab71e4fa46a4\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\maste\AppData\Local\Temp\pip-wheel-ttxzbc1n'
       cwd: C:\Users\maste\AppData\Local\Temp\pip-install-4uo3q6pv\numba_24f4c114cf4a4628ab2eab71e4fa46a4\
  Running setup.py clean for numba
  Building wheel for llvmlite (setup.py) ... error
  Running setup.py clean for llvmlite
Failed to build numba llvmlite
Installing collected packages: llvmlite, numba
    Running setup.py install for llvmlite ... error

A: You can download numba whl file form here for python3.9.
Then use pip install path/numba-0.51.2-cp39-cp39-win_amd64.whl.


text:
Q: Hibernate: how to have two collection fields pointing to same objects I'm trying to map two ordered collection one-to-many fields to the same values. The fields have different filtering requirements. So one field will have items that are filtered out of the other.
Here's the relevant part of the entity.
public class OptionValueSet extends ConfigurationDomainObject {
    ...

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = OPTION_VALUE_SET_ID_COLUMN, nullable = false)
    @IndexColumn(name = "option_index", nullable = false)
    @Where(clause = OBSOLETE_FILTER)
    private final List<OptionValue> allOptions = new java.util.ArrayList<OptionValue>();

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = OPTION_VALUE_SET_ID_COLUMN, nullable = false, insertable = false, updatable = false)
    @IndexColumn(name = "option_index", nullable = false)
    @Where(clause = OBSOLETE_FILTER + " AND disabled = '0'")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @Immutable
    private final List<OptionValue> options = new java.util.ArrayList<OptionValue>();

    ...
}

And the exception

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.casenet.domain.configuration.screen.OptionValue column: option_value_set_id (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:670)
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:692)
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:714)
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:468)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1135)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    ... 137 more

For the curious, I'm in the process of disentangling two use cases that are using the same hibernate field. Currently, the filter is turned on in one to hide disabled OptionValues, left on in the other to edit them. However, the @Filter annotation is interfering with caching. I must fix this without changing the underlying DB schema. We're too late in the release cycle to be doing anything more radical.

A: Since those collections are eagerly fetched anyway, why don't you simply add a getOptions() method that returns a filtered view (or copy) of allOptions?
public List<OptionValue> getOptions() {
    List<OptionValue> result = new ArrayList<OptionValue>(allOptions.size());
    for (OptionValue o : allOptions) {
        if (!o.isDisabled()) {
            result.add(o);
        }
    }
    return result;
}

A: In the idea of hibernate you have mapped the same field two times (in this case a child list; you'll get the same error message if you map a simple property two times). Hibernate can't handle it because after update or insert the state might be invalid (what should hibernate do if the object, which is mapped two times, got different values for update in the Java code?).
You can map a field two times if one of the two fields only is for reading. In case of simple properties the error message already tells you how to do (insert="false" update="false"). In your case of a child list probably you also have to set cascade to none for the read-only property.


text:
Q: Read a file or read a standard user input I was having a problem when writing a bash script. I was required to write a script that can be called in 2 ways, read a file or read a standard input. However, when I used a while-read, I can no longer make it read standard input. Here is my code:
#!/bin/bash
FILE=$1
while read LINE;
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done < $FILE

A: The problem comes from the fact that you always give $FILE as input to your read.
You could try redirecting the file to channel 0 when you have an argument and leave it to stdin otherwise.
#!/bin/bash
FILE=$1
if [ ! -z "$FILE" ]
then
  exec 0< "$FILE"
fi
while read LINE
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done

exec 0< "$FILE" tells the shell to use $FILE as input for channel 0. Reminder: by default read listens to channel 0.
0< is the key here, where 0 indicates channel 0 and < indicates this is an input. When there is no argument, exec 0< "$FILE" will not be called, in this case channel 0 will use stdin.

A: UNIX tools by convention use the special filename - to indicate that input comes from stdin. You can adapt that:
file="${1}"
if [ "${file}" = "-" ] ; then
    file=/dev/stdin # special device for stdin
fi

while read -r line ; do
    do something
done < "${file}"

You can now call the tool like this
tool -             # reads from terminal
cmd | tool -       # used in a pipe
tool /path/to/file # reads from file


text:
Q: z-index for child elements higher than that of the parent div I have a parent div which has its position as fixed. What i'm trying to do is to get the child div1 to stand out when I blur the page but the entire parent div stands out. After having read a lot of posts which said that the parent div overrides the z-index and the child's z-index has no meaning, I'm stuck here not knowing how to make this work.
If not getting this to work, can anyone help me with a solution for this?

A: This is easily achievable when you don't actually contain the intended children in the parent element, but instead fake hierarchy visually while keeping the DOM layout flat. A sample is built below:
http://jsfiddle.net/4KLRU/1/
HTML:

Something

Something else

Something else entirely

Notice that the parent element isn't actually around the so-called children elements.
CSS:
#container {
    position: fixed;
    padding: 10px;
}

#parent {
    background: orange;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
}

.child {
    position: relative;
    background: red;
    margin: 5px;
    z-index: 2;
}

.behind_parent {
    z-index: 0;
}

A: Without knowing exactly what your markup looks like, you could try the following approach:
#parent {
  position: fixed;
  ...
}

#child {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  ...
}


text:
Q: How to get a list of numbers in a for statement I am currently trying to figure how to get numbers organized.
def convert(temp_celsius):
    return temp_celsius * 1.8 + 32

def table(b):
    print('C        F')
    for x in b:
        print('{:10}'.format(convert(x)))

table(range(-30, 50, 10))

I need a list of numbers that ranges from -30 to 40 in steps of 10. So I have 2 columns. One with Farhenheit and one with Celsius. I currently only have the columns with the converted Farhenheit.

A: It's really just a matter of formatting two numbers instead of one:
print('{:10} {:10}'.format(x, convert(x)))

Of course, you'll need to fix up the alignments but that's something you can do yourself.

A: With two format statements:
for x in b:
    print('{:10} {:10}'.format(x, convert(x)))

Certainly, you just forgot to add the other output.


text:
Q: How to modify List Data in SwiftUI I want to change the value of a object associated to an item in a List when the user tap in that item and I get the next error "Cannot assign to property: 'student' is a 'let' constant". How do I prevente this to happened?
Here is my code:
import SwiftUI

var students: [Student] = load("studentsData.json")

struct StudentsListView: View {
    @EnvironmentObject var viewRouter:ViewRouter

    var body: some View {
        NavigationView{
            List(students){student in
                Button(action: {
                    student.isInClass = true
                }){
                    StudentItemListView(student: student)
                }
            }
        }
    }
}

struct StudentsListView_Previews: PreviewProvider {
    static var previews: some View {
        StudentsListView().environmentObject(ViewRouter())
    }
}

struct StudentItemListView: View {
    var student:Student

    var body: some View {
        HStack {
            Image("profile")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width:50, height:50)
                .clipShape(Circle())
            VStack(alignment: .leading){
                Text(student.firstName + " " + student.lastName)
                    .font(.headline)
                if(student.isInClass == true){
                    Text("Asistió")
                    .font(.subheadline)
                    .foregroundColor(.green)
                } else {
                    Text("Faltó")
                    .font(.subheadline)
                    .foregroundColor(.red)
                }
            }
            Spacer()
        }.padding()
    }
}

A: As @koen mentioned in the comment, you should be using @State or @EnvironmentObject for accessing/mutating variables and state in your SwiftUI views.
Unlike UIKit, you might notice how SwiftUI relies on the heavy usage of structs. Structs are immutable by default, this means that you cannot modify any part of a struct without clearly telling the compiler that the struct is mutable (using var keyword, etc.) The way to manage state in SwiftUI is with the use of the Combine framework and the use of @State properties, etc. From a brief look at your code, it looks like all you need to do is add @State var student: Student to your StudentItemListView.
If this at all sounds confusing or you are unaware of what @State might be, I highly recommend either watching the 2019 WWDC videos and look at the Apple provided SwiftUI tutorial.


text:
Q: Why does useEffect React Hook not work properly with dependency? I'm working at a React Web App with Fullcalendar. I think one does not need to know Fullcalendar in order to answer this question. It's rather a matter of React understanding.
Long story short, Fullcalendar has an api that refetches any events from a given source.
In my case, my source is state.events, iniated with useState. I only want to refetch, when my state changes. All good so far. However, at the first initial render, Fullcalendar is not able to fetch anything.
const OverviewPage: React.FunctionComponent<IOverviewPageProps> = (props) => {
    const calendarRef = useRef<any>();
    const [sourceAPI, setSourceAPI] = useState<any>(undefined);
    const [state, setState] = useState<State>({
        externalEvents: [],
        events: []
    });

useEffect(() => {
         if (calendarRef.current !== undefined) {
            let calendarApi = calendarRef.current.getApi();

            if (sourceAPI === undefined) {
                const source = calendarApi.addEventSource(state.events);
                source.refetch()
                setSourceAPI(source);
            } else {
                sourceAPI.refetch();
            }
        }
    }, [state])
return (

           <FullCalendar
               ref={calendarRef}
               //other props
           />

)
;

Now, as you can see, as long as I don't have the reference of the calendar, I can't iniate the calendarApi. And as long as I don't have that api, I can't refetch.
I do have to mention, when I take away the useEffect dependency (state), I no longer face an issue with fetching the events (even on the initial render). However, that causes other issues in my code that I wasn't able to fix, so I rather prefer to fix it with useEffect.
Update
It was requested to explain more in depth, what is happening in the code.
Fullcalendar needs a source of events (calendar tasks). To provide this source, one has to iniate it before render, which I'm doing here in useEffect
Checking, if the reference to the element Fullcalendar already exists to prevent a render error
if (calendarRef.current !== undefined) {//...}

Checking, if a source was already added. If no, iniate a source by using Fullcalendar's api. .addEventSource adds a source that contains an array of objects (events) - in this case state.events - and returns a Fullcalendar Source so that I can interact with it later (e.g. refetch).
.refetch() simply takes the content of the source and (re-)renders them on the calendar (so in other words the content of state.events).
I then store this Fullcalendar Source in a React State so that I can interact with the same source later again, without having to reiniate it again.
 if (sourceAPI === undefined) {
                const source = calendarApi.addEventSource(state.events);
                source.refetch()
                setSourceAPI(source);
            }

If a Fullcalendar Source is already existing, apply the refetch call again.
else {
        sourceAPI.refetch();
}

There's really not more to say about Fullcalendar. I was suspecting the issue in React State management and that I'm doing something wrong there (with useEffect).

A: After trying out multiple different approaches, I finally managed that Fullcalendar also renders events on the first initial render.
This might be helpful for people in the future, facing the same issue with React and Fullcalendar
const OverviewPage: React.FunctionComponent<IOverviewPageProps> = (props) => {
    const calendarRef = useRef<any>();
    const [sourceAPI, setSourceAPI] = useState<any>(undefined);
    const [state, setState] = useState<State>({
        externalEvents: [],
        events: []
    });
useEffect(() => {
        if (sourceAPI === undefined && calendarRef.current !== undefined) {
            const calendarApi = calendarRef.current.getApi();
            const source = calendarApi.addEventSource(state.events);
            setSourceAPI(source);
        }
    });

useEffect(() => {
        if (sourceAPI !== undefined) {
            sourceAPI.refetch();
        }
    }, [state]);

return (

           <FullCalendar
               ref={calendarRef}
               //other props
           />

)
;

Pay attention that the first useEffect is triggered every time while the second one is only triggered when there was a change in regards of its dependency. This way, the source is initiated for sure, which it appeared to be the main problem with the privious code (calendarRef.current was always undefined on initial start/render)


text:
Q: how can I filter placemarks within a polygon and create a list with them in google earth? I have a kml with around 1200 placemarks distributed in a very tight area. I want to create a small area and filter out the placemarks in this area.

A: The best way is to use Regions
To quote the documentation on Regions -

Data is loaded and drawn only when it falls within the user's view and
  occupies a certain portion of the screen

That way you can only show a few major Placemarks when the user is zoomed a long way out, but as they start zooming in, more and more of your Placemarks become visible to them


text:
Q: Why does it seem like this interface provides implementation? I followed a tutorial and built a back end with EF Core and implemented the Repository Pattern.
First, I created a Repository Interface, and a Repository Base class that provides basic CRUD methods. I then created separate interfaces and repositories for each of my entities for any custom methods I needed to interact with data on these particular classes.
Second, I created an interface and a concrete class called IRepositoryWrapper and RepositoryWrapper. To define the repositories to return and a save method, and then an implementation of retrieving the repositories and the save changes method.
Lastly, I created a controller and injected IRepositoryWrapper into the controller's constructor.
My question is: Why did injecting the interface into the controller actually work? Since the Interface only provides definition, why did the actual implementation seem to come with it? I feel like I should be injecting the concrete class RepositoryWrapper instead.
https://code-maze.com/net-core-web-development-part4/#repository
This works properly, I am just asking an OOP question.
public interface IRepositoryWrapper
{
    IScenarioRepository Scenario { get; }
    IConditionRepository Condition { get; }

    void Save();
}

public class RepositoryWrapper : IRepositoryWrapper
{
    private EvaluatorContext _evaluatorContext;
    private IConditionRepository _condition;
    private IScenarioRepository _scenario;

    public RepositoryWrapper(EvaluatorContext evaluatorContext)
    {
        this._evaluatorContext = evaluatorContext;
    }

    public IScenarioRepository Scenario
    {
        get
        {
            if (_scenario == null)
            {
                _scenario = new ScenarioRepository(_evaluatorContext);
            }

            return _scenario;
        }
    }

    public IConditionRepository Condition
    {
        get
        {
            if (_condition == null)
            {
                _condition = new ConditionRepository(_evaluatorContext);
            }

            return _condition;
        }
    }

    public void Save()
    {
        _evaluatorContext.SaveChanges();
    }
}

Controller Class:

[Route("api/[controller]")]
[ApiController]
public class ScenariosController : ControllerBase
    {

        private IRepositoryWrapper _repositoryWrapper;

        //What I am calling injecting this interface into the constructor
        public ScenariosController(IRepositoryWrapper repositoryWrapper)
        {
            this._repositoryWrapper = repositoryWrapper;
        }

        [HttpGet]
        public IEnumerable<Scenario> FindAll()
        {

            return this._repositoryWrapper.Scenario.FindAllWithIncludes();
        }

    }

A:
Why did injecting the interface into the controller actually work? Since the Interface only provides definition, why did the actual implementation seem to come with it?

The interface defines the signatures, so it can be implemented in any number of ways.
When you pass a class with a concrete implementation to the Controller Constructors Interface argument it knows all the methods are available if the class inherits the interface. This is how it knows what comes with it.

 I feel like I should be injecting the concrete class RepositoryWrapper instead.

That's right, when you wire up the DI you hook in the class with the implementation. The Interface argument will accept any class that implements the interface methods.
Why? The main point is seperation of concerns. Using Interfaces allows you to mock implementations and these significantly ease Unit Testing.
They also allow flexibility, say if in USA tax numbers are 11digits and Australia they're 8 digits. Well you could wire up a class with 11digit functionality for USA and 8 digits for Oz. If you didn't have an Interface you could only pass in 11 or 8 - likely forcing you to have two classes that operate the same way with slightly different behaviour. Using Interfaces gives you implementation flexibility.
It's part of the SOLID principles,  Interface Segregation Principle: low coupling, and high cohesion and Dependency Inversion Principle: Abstractions should not depend upon details.


text:
Q: Check if schedule overlaps with startDay, endDay, startTime and endTime I am trying to figure out a pattern that would allow me to keep track of scheduled day ranges and time ranges during a week to make sure that they don't overlap one another when entering into an interface.  I was wondering if anyone has ever come across this and has any ideas?  Remembering that this does not deal with any datetime values, only DayOfWeek and Timespan. For example, the following schedules are added:
Monday-Saturday: 12:00 AM to 8:00 AM
Monday-Thursday, 8:00 AM to 12:00 PM and 1:00 PM to 6:00 PM
Monday-Thursday, 12:00 PM to 1:00 PM
Monday-Thursday, 1:00 PM to 5:00 PM (this one causes it to error)

My thoughts have been that I could step through the day ranges from the start day to the end day and through the time ranges using some combination of these values that make it unique to add to a dictionary so that if a replication occurs the dictionary throws an exception.
I have to think that something like this has been done before and was wondering if anyone can point me in a direction.  I appreciate any comments on this.
James


text:
Q: Changing order of data in database with js and php I am not sure if the title is 100% accurate, but here's my problem.
I have a website where n user can upload images, I want to enable the user to order the images he has uploaded and save them in that order and later preview them in the exact order.
The ordering can be done same time as the upload or later on.
 I am using plupload. My idea is to save the source of every image in the database with an additional column that would represent order number and use ORDER BY when getting the images.
But for every new image I have to check the number of images I already have and that many SQL request will be too slow. And with the adding of new images and rearranging them come a lot of UPDATE statements that also slows the database.
And this means that I will also have to check the old place and new of every image and change it if I have to, which meant more SQL statements.
All of this didn't seem like a good approach so I was wondering if I could get some pointers on a different approach or optimization. But I would like to keep plupload if possible.

A: Normally an ORDER BY $order is sufficient using values like 0,1,2,3  with default 0 and where lowest is first.
If you really not want to make any changes to your own DB you can consider writing a code so that it uses the local storage on the client's side.
But this would result in that when the users makes access from another computer, that data will not be available.
So whatever option is going to be given, still the best is to use your own db for it.
When your code is written well, there should not be any problem at all to run these queries.


text:
Q: Unable to submit forms using PhantomJS Webdriver and Java I'm in the middle of writing a program in java. One of the functions is to log in to a website with a username and password. I originally wrote this basic function to log in to a page using the ChromeDriver.
    public void Login() {
        System.out.println("Logging In");
        driver.get(url);
        ScreenShot("/Users/Adam/Documents/Screens/1.jpg");
        WebElement login = driver.findElement(By.xpath("//*[@id=\"username\"]"));
        login.sendKeys(username + Keys.TAB + password);
        ScreenShot("/Users/Adam/Documents/Screens/2.jpg");
    }

The function above works in Chromedriver, however when I run the same function in phantomjs the result isn't the same. Here's the error output.
Exception in thread "main" org.openqa.selenium.WebDriverException: {"errorMessage":"'undefined' is not an object (evaluating 'c.name=this.name')","request":{"headers":{"Accept":"application/json, image/png","Connection":"Keep-Alive","Content-Length":"63","Content-Type":"application/json; charset=utf-8","Host":"localhost:48788"},"httpVersion":"1.1","method":"POST","post":"{\"id\":\":wdc:1421947793877\",\"value\":[\"usernamepassword\"]}","url":"/value","urlParsed":{"anchor":"","query":"","file":"value","directory":"/","path":"/value","relative":"/value","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/value","queryKey":{},"chunks":["value"]},"urlOriginal":"/session/4562eec0-a25c-11e4-a2af-d1362c6e21bf/element/%3Awdc%3A1421947793877/value"}}
Command duration or timeout: 811 milliseconds
By looking at the error above, it looks like the information is being submitted to the form but some but the page is throwing an error.
I've also tried another approach, although it still doesn't work, it doesn't give me an error either...
    public void Login() {
        System.out.println("Logging In");
        driver.get(url);
        ScreenShot("/Users/Adam/Documents/Screens/1.jpg");
        WebElement login = driver.findElement(By.xpath("//*[@id=\"login\"]"));
        login.sendKeys(Keys.TAB + username + Keys.TAB + password + Keys.ENTER);
        ScreenShot("/Users/Adam/Documents/Screens/2.jpg");
    }

Instead of locating the username field, the function above finds the form itself and tried to enter the data. The result is the username and password being filled in but the form doesn't get submitted.
Any possible solutions or ideas on where to look for help would be greatly appreciated. Thanks

A: The answer was pretty simple actually... After this driving me crazy for a few days I though, why not update Ghostdriver... So I did and now everything is working perfectly. Probably the first thing I should have tried, but hey ho...
The issue was with Phantomjs 1.9.7. Problem was fixed after updating to version 1.9.8.


text:
Q: GWT showing low disk space I am new to GWT. Iam using eclipse Indigo along with GWT. The moment I open eclipse and start running a simple program I have created , my system shows low disk space. I can understand it is something related to cache. But dont know how to proceed. The system becomes very slow and not allowing me to work. Again If I close my eclipse and browser , things become normal. Before starting my eclipse I have 2 GB in C. But after some time it become 100 mb and forcing me to clean or close.
What I need to do?

A: This is a known issue of the Google Plugin for Eclipse.
Workaround:

*

*avoid relaunching the DevMode too much (you can launch it once and then reload the app at will)

*clean your temporary directory regularly


text:
Q: Flutter show api data using POST Hi need help to show my API data into Text.
I already get the response but I don't know how to turn it into text which it will show at the screen.. now the data are shows at the terminal.
This is my codes:
    class carList extends StatefulWidget {
      const carList({Key? key}) : super(key: key);

      @override
      State<carList> createState() => _carListState();
    }

    class _carListState extends State<carList> {

      var userController = TextEditingController();
      var apiController = TextEditingController();
      final pref = Pref();

      @override
      void initState() {
        MySharedPreferences().getUserId().then((value) {
          setState(() {
            userController.text = value.toString();
          });
        });
        MySharedPreferences().getUserToken().then((value) {
          setState(() {
            apiController.text = value.toString();
          });
        });
        //TODO: IMPLEMENT INITSTATE
      }

this is where I want to show my API data
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: ListView(
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: TextField(
                      controller: userController,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        suffixIcon: Icon(Icons.email),
                        labelText: 'User ID',
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: TextField(
                      controller: apiController,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        suffixIcon: Icon(Icons.email),
                        labelText: 'Token',
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.all(25),
                    child: TextButton(
                      child: Text('Show Car List',
                        style: TextStyle(fontSize: 20.0,
                            color: Colors.blueAccent,
                            backgroundColor: Colors.white),
                      ),
                      onPressed: () {
                        list();
                      },
                    ),
                  )
                ]
            )
        );
      }

this is my API response
void list() async {
        {
          var response = await http.post(
              Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
              body: ({
                'user_id': userController.text,
                'token': apiController.text,
                'device': "Android",
              }));
          if (response.statusCode == 200) {
            final body = jsonDecode(response.body);
            print(apiController.text);
            print(body.toString());
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text("Successfully Login")));
          }
        }
      }
    }

This page that I want to show my data.
this is my log response
{
    "Status": "OK",
    "Message": "Senarai maklumat kereta.",
    "Details": [
      {
        "car_id": 184,
        "user_id": 141,
        "manufacturer_id": 21,
        "name": "Akma",
        "registration_no": "ws 3345",
        "model_name": "Bezza",
        "production_year": 2022,
        "notes": null,
        "date_purchased": "2022-08-10",
        "image":
            " http://servisjer.me-tech.com.my/admin/storage/app/media/userplugin/7PyVIp8iwb.png"
      }
    ]
  }

A: assuming this is valid response :
{
       "Status":"OK",
       "Message":"Sena.",
       "Details":[
          {
             "car_id":184,
             "user_id":141,
             "manufacturer_id":21,
             "name":"Akma",
             "registration_no":"ws 3345",
             "model_name":"Bezza",
             "production_year":2022,
             "notes":null,
             "date_purchased":"2022-08-10",
             "image":"http://servisjer.me-tech.com.my/admin/storage/app/media/userplugin/7PyVIp8iwb.png"
          }
                 ]
}

then to get save the details is a list so you have to loop through the list i.e
if(body["Status"]=="OK")
{
      List<Detail> allRecord;
      final parsed = json.decode(body).cast<Map<String, dynamic>>();
      allRecord = parsed .map<Detail>((json) => Detail.fromJson(json)).toList();
}

here is your model :
// To parse this JSON data, do
//
//     final responseModel = responseModelFromJson(jsonString);

import 'dart:convert';

ResponseModel responseModelFromJson(String str) => ResponseModel.fromJson(json.decode(str));

String responseModelToJson(ResponseModel data) => json.encode(data.toJson());

class ResponseModel {
    ResponseModel({
        this.status,
        this.message,
        this.details,
    });

    String status;
    String message;
    List<Detail> details;

    factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
        status: json["Status"],
        message: json["Message"],
        details: List<Detail>.from(json["Details"].map((x) => Detail.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "Status": status,
        "Message": message,
        "Details": List<dynamic>.from(details.map((x) => x.toJson())),
    };
}

class Detail {
    Detail({
        this.carId,
        this.userId,
        this.manufacturerId,
        this.name,
        this.registrationNo,
        this.modelName,
        this.productionYear,
        this.notes,
        this.datePurchased,
        this.image,
    });

    int carId;
    int userId;
    int manufacturerId;
    String name;
    String registrationNo;
    String modelName;
    int productionYear;
    dynamic notes;
    DateTime datePurchased;
    String image;

    factory Detail.fromJson(Map<String, dynamic> json) => Detail(
        carId: json["car_id"],
        userId: json["user_id"],
        manufacturerId: json["manufacturer_id"],
        name: json["name"],
        registrationNo: json["registration_no"],
        modelName: json["model_name"],
        productionYear: json["production_year"],
        notes: json["notes"],
        datePurchased: DateTime.parse(json["date_purchased"]),
        image: json["image"],
    );

    Map<String, dynamic> toJson() => {
        "car_id": carId,
        "user_id": userId,
        "manufacturer_id": manufacturerId,
        "name": name,
        "registration_no": registrationNo,
        "model_name": modelName,
        "production_year": productionYear,
        "notes": notes,
        "date_purchased": "${datePurchased.year.toString().padLeft(4, '0')}-${datePurchased.month.toString().padLeft(2, '0')}-${datePurchased.day.toString().padLeft(2, '0')}",
        "image": image,
    };
}

Worst Approach : use a for each to loop through if you are sure the Details array has only one object i.e
for (var data in details)
{

  debugPrint(data.model_name);
  debugPrint(data.registration_no);
 //and many more

 }

A: First of all you have to crate a model class of your response.
    import 'dart:convert';

CarDetailResponse carDetailResponseFromJson(String str) => CarDetailResponse.fromJson(json.decode(str));

String carDetailResponseToJson(CarDetailResponse data) => json.encode(data.toJson());

class CarDetailResponse {
  CarDetailResponse({
    this.status,
    this.message,
    this.details,
  });

  String? status;
  String? message;
  List<Detail>? details;

  factory CarDetailResponse.fromJson(Map<String, dynamic> json) => CarDetailResponse(
    status: json["Status"],
    message: json["Message"],
    details: List<Detail>.from(json["Details"].map((x) => Detail.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "Status": status,
    "Message": message,
    "Details": List<dynamic>.from(details!.map((x) => x.toJson())),
  };
}

class Detail {
  Detail({
    this.carId,
    this.userId,
    this.manufacturerId,
    this.name,
    this.registrationNo,
    this.modelName,
    this.productionYear,
    this.notes,
    this.datePurchased,
    this.image,
  });

  int? carId;
  int? userId;
  int? manufacturerId;
  String? name;
  String? registrationNo;
  String? modelName;
  int? productionYear;
  dynamic notes;
  DateTime? datePurchased;
  String? image;

  factory Detail.fromJson(Map<String, dynamic> json) => Detail(
    carId: json["car_id"],
    userId: json["user_id"],
    manufacturerId: json["manufacturer_id"],
    name: json["name"],
    registrationNo: json["registration_no"],
    modelName: json["model_name"],
    productionYear: json["production_year"],
    notes: json["notes"],
    datePurchased: DateTime.parse(json["date_purchased"]),
    image: json["image"],
  );

  Map<String, dynamic> toJson() => {
    "car_id": carId,
    "user_id": userId,
    "manufacturer_id": manufacturerId,
    "name": name,
    "registration_no": registrationNo,
    "model_name": modelName,
    "production_year": productionYear,
    "notes": notes,
    "date_purchased": "${datePurchased!.year.toString().padLeft(4, '0')}-${datePurchased!.month.toString().padLeft(2, '0')}-${datePurchased!.day.toString().padLeft(2, '0')}",
    "image": image,
  };
}

you can make this model class with the help of app.quicktype.io
then after getting response, assign the response.body to this model class object
    void list() async {
        {
          var response = await http.post(
              Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
              body: ({
                'user_id': userController.text,
                'token': apiController.text,
                'device': "Android",
              }));
          if (response.statusCode == 200) {
            final body = jsonDecode(response.body);
setState(() {
            carDetailResponse =
            carDetailResponseFromJson(body);
          });

            print(apiController.text);
            print(body.toString());
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text("Successfully Login")));
          }
        }
      }
    }

then at UI use this model class to show data. Like -
    class CarDetailScreen extends StatefulWidget {
  const CarDetailScreen({Key? key}) : super(key: key);

  @override
  State<CarDetailScreen> createState() => _CarDetailScreenState();
}

class _CarDetailScreenState extends State<CarDetailScreen> {
  CarDetailResponse? carDetailResponse;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(children: <Widget>[
      Container(
        padding: const EdgeInsets.all(10),
        child: TextField(
          controller: userController,
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
            suffixIcon: Icon(Icons.email),
            labelText: 'User ID',
          ),
        ),
      ),
      Container(
        padding: const EdgeInsets.all(10),
        child: TextField(
          controller: apiController,
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
            suffixIcon: Icon(Icons.email),
            labelText: 'Token',
          ),
        ),
      ),
      Container(
        margin: EdgeInsets.all(25),
        child: TextButton(
          child: Text(
            'Show Car List',
            style: TextStyle(fontSize: 20.0, color: Colors.blueAccent, backgroundColor: Colors.white),
          ),
          onPressed: () {
            list();
          },
        ),
      ),
      carDetailResponse != null
          ? Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                physics: const ClampingScrollPhysics(),
                itemCount: carDetailResponse!.details!.length,
                itemBuilder: (context, index) {
                  var car = carDetailResponse!.details![index];
                  return Text(car.name ?? '');
                },
              ),
            )
          : const SizedBox()
    ]));
  }

}

A: Best way to use API response data is to create model from https://app.quicktype.io/ (copy your response and paste on this link and select language dart) and use as per your requirement.
I create model with name "GetUserCarModel" from your API response and use like this way.
Future<void> list() async {
  {
    var response = await http.post(
        Uri.parse("http://servisjer.me-tech.com.my/api/Car/GetUserCar"),
        body: ({
          'user_id': userController.text,
          'token': apiController.text,
          'device': "Android",
        })
    );

    if (response.statusCode == 200) {
      final body = jsonDecode(response.body);
      GetUserCarModel getUserCarModel = GetUserCarModel.fromJson(body);
      print("getUserCarModel ===> ${getUserCarModel.toString()}");
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Successfully Login")));
    }
  }
}


text:
Q: Conjecture about : $\sum_{cyc}\frac{214x^4}{133x^3 + 81y^3}\ge\frac{x+y+z}{12}+\sum_{cyc}\frac{13x^4}{8x^3+5y^3}-0.25(x-\frac{2yx}{2y+x})\ge x+y+z$ Hi it's a conjecture  refinement in the simple case of Prove that $\sum_{\mathrm{cyc}} \frac{214x^4}{133x^3 + 81y^3} \ge x + y + z$ for $x, y, z > 0$ .
Conjecture :
Let $x,y,z>0$ such that $x\geq y \ge z$ then it seems we have :

$$\sum_{cyc}\left(\frac{214x^4}{133x^3 + 81y^3}\right)\geq \frac{x+y+z}{12}+\sum_{cyc}\left(\frac{13x^4}{8x^3+5y^3}-\frac{1}{4}\left(x-\frac{2yx}{2y+x}\right)\right)\geq x+y+z$$

My attempt :

I can show the RHS  because the function $f(x)=\frac{13}{8+5x^{3}}-0.25\left(1-\frac{2x}{2x+1}\right)-\frac{214}{133+81x^{3}}$ is concave on $(0,\infty)$ also we can use Jensen's inequality .
For the LHS  I have tried Buffalo's way without success .
Edit 08/04/2022 :
Using  again Jensen inequality I can show :
Let :
$$h\left(x\right)=\frac{2}{1+x^{3}}+\frac{x^{3}+x}{\frac{4}{3}+x^{3}}+\frac{\frac{1}{3}x}{x+2}$$
And :
$$g\left(x\right)=\frac{13}{8+5x^{3}}$$
We have :
$$g''(x)-h''(x)>0$$
So we get a lower bound for the inequality due to user HN_NH (see Olympiad Inequality $\sum\limits_{cyc} \frac{x^4}{8x^3+5y^3} \geqslant \frac{x+y+z}{13}$ )
Next it seems  we have for $x,y,z>0$ and $x\geq y\geq z$ :
$$\frac{x}{x+y+z}h\left(\frac{y}{x}\right)+\frac{y}{x+y+z}h\left(\frac{z}{y}\right)+\frac{z}{x+y+z}h\left(\frac{x}{z}\right)-1+g\left(1\right)-h\left(1\right)\ge0$$
I think it's not sufficient to show the conjecture anyway it provides a half solution for HN_NH's inequality .

My question :

How to deal with it or in other word how to show the inequality/Conjecture ?
Thanks a lot .


text:
Q: Unable to Share Folder in Network I am attempting to create a folder share on a Windows Server 2012 R2 two-node cluster Hyper-V volume in the network and I'm getting these error messages:
An error occurred while trying to share FolderA.  The resources must be online on the same node for this operation.
The shared resource was not created at this time.
Can someone please help me resolve this?
Thank you!

A: In my case the reason was that the clustered disk was not assigned to any clustered role. There was actually no role in Roles node in Failover Cluster Manager.
I needed to click Configure Role, select File Server role, (File Server for general use), name it somehow, and then select the clustered disk as the actual storage for this clustered role.
Now when I click newly created role, I can see the disk where I wanted to create shared folder within Storage. The shared folder is then available in network as "\clustered_role_name\folder_name"


text:
Q: UFW not allowing ssh even though i have allowed it Struggling a bit with UFW on ubuntu, i have internal and external adapters and on this particular server i only want public access to port 22 which is the adapter "eno1"
To acomplish this i first blocked everything:

ufw deny in on eno1 from any

After i then allowed port 22 for ssh:

ufw allow in on eno1 to any port 22

My rules now look like this:
To                         Action      From
--                         ------      ----
Anywhere on eno1           DENY        Anywhere
22 on eno1                 ALLOW       Anywhere
Anywhere (v6) on eno1      DENY        Anywhere (v6)
22 (v6) on eno1            ALLOW       Anywhere (v6)

However i now cannot ssh into the server from outside, even though it clearly shows ALLOW on port 22. (i will need to put the server in recovery mode and delete the rules to get back in)

A: The order of the rules matter as the first terminating rule to match the packet determines its destiny.
In your case ssh packet arrives and it matches the first rule which results in a DROP. The packet never gets a chance to hit the ALLOW rule which comes next.
The rule of thumb: the more specific the rule is the sooner it should appear in the chain. Less specific rules (like matching all packets) should be specified last.


text:
Q: Why "vsprintf" is getting stuck when calling a function from a macro using __VA_ARGS__? I have the following macro:
#define TRACE__LOW(str, col, ...)\
        TR_Trace("\r\e[" COLOR(col) "%s :: %s():%d; LOW - " str "\e[0m\r\n",\
        ##__VA_ARGS__);

And the function TR_Trace looks like this:
void TR_Trace(const char *const string, ...)
{
   va_list aptr;
   size_t stringSize = 0;
   char tempString[250];

   va_start(aptr, string);
   vsprintf(tempString, string, aptr);
   va_end(aptr);
}

And I'm using it like this:
TRACE__LOW("Led[%d] toggled every %d milliseconds (%5d)", GREEN
            init_parameters.led, delay_time, counter++);

The problem here is that once the execution gets to vsprintf(tempString, string, aptr); it gets stuck there.
Do anybody know what is happening or if I'm not using correctly the VA_ARGS?
Regards.

A: You adding %s :: %s():%d; to format string, but don't adding extra arguments to fill these patterns.
I suppose it meant to be
#define TRACE__LOW(str, col, ...)\
        TR_Trace("\r\e[" COLOR(col) "%s :: %s():%d; LOW - " str "\e[0m\r\n",\
        __FILE__, __func__, __LINE__,\
        ##__VA_ARGS__);

A: Random thoughts:
Your use of __VA_ARGS__ appears to be correct.
The TRACE__LOW macro adds a superfluous semi-colon to the output (could cause problems for conditional statements that don't have curly braces).
I don't know what COLOR(GREEN) expands to, so that may be the source of the problem.
Suggestion:
Your compiler should have an option to output the results from the preprocessor. On the compiler I'm using that option is -E. If you have the compiler output the results from the preprocessor, you can see precisely what your macro expands to.
For example, compiling the following code with -E
#include <stdio.h>

#define TRACE__LOW(str, col, ...)\
TR_Trace("\r\e[" COLOR(col) "%s :: %s():%d; LOW - " str "\e[0m\r\n",\
##__VA_ARGS__);

int main( void )
{
    TRACE__LOW( "test", 3, a, b, c );
}

produces this output (after about 5 million other lines ;) )
int main( void )
{
    TR_Trace("\r\e[" COLOR(3) "%s :: %s():%d; LOW - " "test" "\e[0m\r\n", a, b, c);;
}


text:
Q: How can menu items be displayed from bottom up using CSS I have my menu working the way I want with the exception that menu elements are displayed from the top down as supposed to bottom up. I tried changing the CSS properties, but still can't get it working. I need my DIV container to be align on the bottom of the parent container. I used 'bottom: 0' CSS property but that doesn't have any affect using both 'position: absolute' and 'position: relative'.
How can I align all the elements within the parent DIV be displayed at bottom: 0 (bottom up)?
Then click on the Projects bottom link (refresh if you need to reset the menu items). I need that same behaviour I already have, just the menu items should start from the bottom up and be aligned all the way to the bottom.
Any suggestions?
Thanks,
Partizan

A: The best way to accomplish this is to either put the divs inside the sought after parent element. Ergo the <li> you want to associate these links with. Give the parent <li> a style of position:relative. The on hover set the position of the child div or li to abosulte and left:0;top:0;. Then from there you can style it closer or farther with margin.

A: Try using padding-top to push them down with an id or class on each sub menu.
Then if that fails, try using min-height: auto; on each parent.


text:
Q: Given $A + B + C = \pi $, find $ \frac{\cos A}{\sin B\sin C} + \frac{\cos B}{\sin C\sin A} + \frac{\cos C}{\sin A\sin B} $
Given
  $$ A + B + C = \pi $$
  Find
  $$ \frac{\cos A}{\sin B\sin C} + \frac{\cos B}{\sin C\sin A} + \frac{\cos C}{\sin A\sin B} $$

A: Rewrite,
$$A= \frac{\cos A}{\sin B \sin C} + \frac{\cos B}{\sin A \sin C} + \frac{\cos C}{\sin A \sin B} =\frac{\sin 2A + \sin 2B + \sin 2C}{2\sin A \sin B \sin C}
$$
and reexpress the numerator,
$$\sin 2A + \sin 2B + \sin 2C$$
$$= 2\sin(A+B)\cos(A-B) + 2\sin C \cos C$$
$$= 2\sin C \cos(A-B) - 2\sin C \cos (A+B)$$
$$=2\sin C \left[\cos(A-B)-\cos (A+B)\right]$$
$$=4\sin A \sin B \sin C$$
which cancels the denominator. Thus,
$$A = 2$$

A: Hint: Use the formulas
$$\cos(\alpha)=\frac{b^2+c^2-a^2}{2bc}$$ and so on and
$$\frac{\sin(\alpha)}{\sin(\beta)}=\frac{a}{b}$$ and so on.
Doing so you will get
$$\frac{4R^2(a+b+c)(-a+b+c)(a-b+c)(a+b-c)}{2a^2b^2c^2}$$
the use $$A=\sqrt{s(s-a)(s-b)(s-c)}$$ and $$A=\frac{abc}{4R}$$
where $R$ is the circumradius and $$s=\frac{a+b+c}{2}$$.
I got $2$ as the searched result!

A: Hint. Use:
$$ tan A + tan B + tan C = tan A \cdot tan B \cdot tan C $$


text:
Q: GlassFish Security Realm, Active Directory and Referral I've setup up a Security Realm in Glassfish to authenticate against an Active Directory server. The configuration of the realm is as follows:
Class Name: com.sun.enterprise.security.auth.realm.ldap.LDAPRealm
JAAS context:  ldapRealm
Directory: ldap://172.16.76.10:389/
Base DN:  dc=smallbusiness,dc=local
search-filter: (&(objectClass=user)(sAMAccountName=%s))
group-search-filter: (&(objectClass=group)(member=%d))
search-bind-dn: cN=Administrator,CN=Users,dc=smallbusiness,dc=local
search-bind-password: abcd1234!

The realm is functional and I can log-in, but when ever I log in I get the following error in the log:
SEC1106: Error during LDAP search with filter [(&(objectClass=group)(member=CN=Administrator,CN=Users,dc=smallbusiness,dc=local))].
SEC1000: Caught exception.
    javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name 'dc=smallbusiness,dc=local'
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2820)
        ....
        ....
ldaplm.searcherror

While searching for a solution I found that it was recommended to add java.naming.referral=follow to the properties of the realm. However, after I add this it takes 20 minutes for GlassFish to authenticate against Active Directory. I suspect it is a DNS problem on the Active Directory server. The Active Directory server is a vanilla Windows Server 2003 setup in a Virtual Machine.
Any help/recommendation is highly appreciated!

A: This is the configuration I use in my domain.xml file, it might be of some interrest to you :
<auth-realm classname="com.sun.enterprise.security.auth.realm.ldap.LDAPRealm" name="ldapRealm">
      <property name="search-bind-password" value="Demodemo01"/>
      <property name="search-bind-dn" value="Administrator"/>
      <property name="search-filter" value="(&(objectClass=user)(sAMAccountName=%s)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"/>
      <property name="group-search-filter" value="(&(objectClass=group)(member=%d))"/>
      <property name="jaas-context" value="ldapRealm"/>
      <property name="base-dn" value="CN=Users,DC=saierp,DC=net"/>
      <property name="directory" value="ldap://192.168.1.38:389"/>
</auth-realm>

Specially, make sure to add the userAccountControl to your filter, otherwise, disabled accounts in AD will be allowed to connect.

A: Hopefully, you've resolved this, but just in case:

*

*I used 'objectCategory' in place of 'objectClass' as I read the former are indexed, hence faster.

*I had to add this property:
property name="assign-groups" value="Domain Users"
where "Domain Users" is the group in AD that all of our users are placed into.  This must match the value in sun-web.xml for security-role-mapping.
Later, I was able to create a specific group for this application and make the appropriate changes.

A: This was maddening trying to solve this... Glassfish 3.0.1 trying to connect with Windows, and getting the above error.
I'm not a Windows or LDAP whiz at all... but finally found this:
http://forum.springsource.org/showthread.php?t=87673
And the very last line is the key: use the "Global Catalog Port" - instead of 389, it is 3268 by default. And the exception disappears.
Why?
Who cares?
(well, ok, I'm going to read about it now.)


text:
Q: sem_wait() failed to wake up on linux I have a real-time application that uses a shared FIFO. There are several writer processes and one reader process. Data is periodically written into the FIFO and constantly drained. Theoretically the FIFO should never overflow because the reading speed is faster than all writers combined.  However, the FIFO does overflow.
I tried to reproduce the problem and finally worked out the following (simplified) code:
#include <stdint.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <pthread.h>
#include <semaphore.h>
#include <sys/time.h>
#include <unistd.h>

class Fifo
{
public:
    Fifo() : _deq(0), _wptr(0), _rptr(0), _lock(0)
    {
        memset(_data, 0, sizeof(_data));
        sem_init(&_data_avail, 1, 0);
    }

    ~Fifo()
    {
        sem_destroy(&_data_avail);
    }

    void Enqueue()
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        uint64_t enq = tv.tv_usec + tv.tv_sec * 1000000;
        while (__sync_lock_test_and_set(&_lock, 1))
            sched_yield();
        uint8_t wptr = _wptr;
        uint8_t next_wptr = (wptr + 1) % c_entries;
        int retry = 0;
        while (next_wptr == _rptr)      // will become full
        {
            printf("retry=%u enq=%lu deq=%lu count=%d\n", retry, enq, _deq, Count());
            for (uint8_t i = _rptr; i != _wptr; i = (i+1)%c_entries)
                printf("%u: %lu\n", i, _data[i]);
            assert(retry++ < 2);
            usleep(500);
        }
        assert(__sync_bool_compare_and_swap(&_wptr, wptr, next_wptr));
        _data[wptr] = enq;
        __sync_lock_release(&_lock);
        sem_post(&_data_avail);
    }

    int Dequeue()
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        uint64_t deq = tv.tv_usec + tv.tv_sec * 1000000;
        _deq = deq;
        uint8_t rptr = _rptr, wptr = _wptr;
        uint8_t next_rptr = (rptr + 1) % c_entries;
        bool empty = Count() == 0;
        assert(!sem_wait(&_data_avail));// bug in sem_wait?
        _deq = 0;
        uint64_t enq = _data[rptr];     // enqueue time
        assert(__sync_bool_compare_and_swap(&_rptr, rptr, next_rptr));
        int latency = deq - enq;        // latency from enqueue to dequeue
        if (empty && latency < -500)
        {
            printf("before dequeue: w=%u r=%u; after dequeue: w=%u r=%u; %d\n", wptr, rptr, _wptr, _rptr, latency);
        }
        return latency;
    }

    int Count()
    {
        int count = 0;
        assert(!sem_getvalue(&_data_avail, &count));
        return count;
    }

    static const unsigned c_entries = 16;

private:
    sem_t _data_avail;
    uint64_t _data[c_entries];
    volatile uint64_t _deq;     // non-0 indicates when dequeue happened
    volatile uint8_t _wptr, _rptr;      // write, read pointers
    volatile uint8_t _lock;     // write lock
};

static const unsigned c_total = 10000000;
static const unsigned c_writers = 3;

static Fifo s_fifo;

// writer thread
void* Writer(void* arg)
{
    for (unsigned i = 0; i < c_total; i++)
    {
        int t = rand() % 200 + 200;     // [200, 399]
        usleep(t);
        s_fifo.Enqueue();
    }
    return NULL;
}

int main()
{
    pthread_t thread[c_writers];
    for (unsigned i = 0; i < c_writers; i++)
        pthread_create(&thread[i], NULL, Writer, NULL);

    for (unsigned total = 0; total < c_total*c_writers; total++)
        s_fifo.Dequeue();
}

When Enqueue() overflows, the debug print indicates that Dequeue() is stuck (because _deq is not 0). The only place where Dequeue() can get stuck is sem_wait(). However, since the fifo is full (also confirmed by sem_getvalue()), I don't understand how that could happen. Even after several retries (each waits 500us) the fifo was still full even though Dequeue() should definitely drain while Enqueue() is completely stopped (busy retrying).
In the code example, there are 3 writers, each writing every 200-400us. On my computer (8-core i7-2860 running centOS 6.5 kernel 2.6.32-279.22.1.el6.x86_64, g++ 4.47 20120313), the code would fail in a few minutes. I also tried on several other centOS systems and it also failed the same way.
I know that making the fifo bigger can reduce overflow probability (in fact, the program still fails with c_entries=128), but in my real-time application there is hard constraint on enqueue-dequeue latency, so data must be drained quickly. If it's not a bug in sem_wait(), then what prevents it from getting the semaphore?
P.S. If I replace
        assert(!sem_wait(&_data_avail));// bug in sem_wait?

with
        while (sem_trywait(&_data_avail) < 0) sched_yield();

then the program runs fine. So it seems that there's something wrong in sem_wait() and/or scheduler.

A: You need to use a combination of sem_wait/sem_post calls to be able to manage your read and write threads.
Your enqueue thread performs a sem_post only and your dequeue performs sem_wait only call.  you need to add sem_wait to the enqueue thread and a sem_post on the dequeue thread.
A long time ago, I implemented the ability to have multiple threads/process be able to read some shared memory and only one thread/process write to the shared memory.  I used two semaphore, a write semaphore and a read semaphore.  The read threads would wait until the write semaphore was not set and then it would set the read semaphore.  The write threads would set the write semaphore and then wait until the read semaphore is not set.  The read and write threads would then unset the set semaphores when they've completed their tasks. The read semaphore can have n threads lock the read semaphore at a time while the write semaphore can be lock by a single thread at a time.

A:
If it's not a bug in sem_wait(), then what prevents it from getting
  the semaphore?

Your program's impatience prevents it. There is no guarantee that the Dequeue() thread is scheduled within a given number of retries. If you change
            assert(retry++ < 2);

to
            retry++;

you'll see that the program happily continues the reader process sometimes after 8 or perhaps even more retries.

Why does Enqueue have to retry?

It has to retry simply because the main thread's Dequeue() hasn't been scheduled by then.

Dequeue speed is much faster than all writers combined.

Your program shows that this assumption is sometimes false. While apparently the execution time of Dequeue() is much shorter than that of the writers (due to the usleep(t)), this does not imply that Dequeue() is scheduled by the Completely Fair Scheduler more often - and for this the main reason is that you used a nondeterministic scheduling policy. man sched_yield:

       sched_yield() is intended for use with read-time scheduling policies
       (i.e., SCHED_FIFO or SCHED_RR).  Use of sched_yield() with
       nondeterministic scheduling policies such as SCHED_OTHER is
       unspecified and very likely means your application design is broken.

If you insert
    struct sched_param param = { .sched_priority = 1 };
    if (sched_setscheduler(0, SCHED_FIFO, &param) < 0)
        perror("sched_setscheduler");

at the start of main(), you'll likely see that your program performs as expected (when run with the appropriate priviledge).


text:
Q: how to declare ObservableCollecion in Silverlight Xaml I want to add declarations for a Object with type of ObservableCollection in Silverlight Xaml. This is what I have done.
1.Add the xmlns declaration like this:
xmlns:col="clr-namespace:System.Collections.ObjectModel;assembly=System.Windows"

2.Add the ObservableCollection declaration like this:
    <col:ObservableCollection x:TypeArguments="sys:String" x:Key="AnaBase">
        <sys:String>string1</sys:String>
        <sys:String>string2</sys:String>
        <sys:String>string3</sys:String>
    </col:ObservableCollection>

3.The above code works fine in Vs2010 editor because it doesn't report any errors.
The problem is, when I try to build such xaml it always outputs error such as
 "The tag 'ObservableCollection' does not exist in XML namespace 'clr-namespace:System.Collections.ObjectModel;assembly=System.Windows'."
It seems to me that the namespace resolvers in editing and building of VS work in different ways. Could anyone please to explain this phenomenon to me? Thanks a lot.

A: Finally I found out the answer. The generics is not supported in Silverlight 4. That's why ObservableCollection can't be seen in Intellisense of XAML.

A: Answer: WPF: Xaml, create an observable collection<object> in xaml in .NET 4.0


text:
Q: "Graphics Device initialization failed for : es2, sw", M1 MacBook, OpenJDK 17.0.2/11.0.12 Tested with OpenJDK 17.0.2 and 11.0.12. (Via Homebrew)
OpenJFX 17.0.2 and 18-ea+12. (From https://gluonhq.com/products/javafx/)
MacOS 12.2.1 (Monterey). MacBook Air (M1, 2020).
Graphics Device initialization failed for :  es2, sw
Error initializing QuantumRenderer: no suitable pipeline found
java.lang.RuntimeException: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
...
Caused by: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
...
Exception in thread "main" java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.RuntimeException: No toolkit found

Oracle's JDK 17 does work. SHA256:
265b8ec9279bf91bb4fd5b4cb69acadce42e80f3462254fbb7300e4e8a1e0657


text:
Q: How could I get rid off border around header image I created basic html and css webpage and in header element i put image,with 100% width margin:auto and it still exist some space between image and border of my screen.I am using Edge browser on my laptop with recent update.

A: Most likely you're looking for body { margin: 0; }


text:
Q: Selecting all current attributes of a model for validations in Rails When setting up my models I often find myself having to write out all of its attributes when setting up certain validations. A common example is when I use the presence parameter:
validates :first_name, :last_name, :username, :email, presence: true
Is there a clever way to select all of its attributes without explicitly writing them all out similar to how you can retrieve them in the rails console?
User.columns
And pass it as an argument in the validates method?
ALL_ATTRIBUTES = User.columns

validates ALL_ATTRIBUTES, presence: true

Trying something like this out I got this error undefined method 'to_sym'

A: I will NOT encourage you or anyone to do this. Reason being when you run into issues, when an object of your model doesn't get saved and throw errors because of a new column which was added to application after some time in future, and you or new developers will wonder WHY?!?!.
However, if you must do then here you go:
validates *self.column_names.map(&:to_sym), presence: true

Here, * in Ruby is known as splat operator and here's the explanation on &:.

A: This is an awful idea. But you can do it this way:
attrs = column_names.map { |column| column.to_sym }
validates *attrs, presence: true

Why is it a bad idea? Because it's not very clear what is being validated it. It makes debugging hard, and could cause you have strange bugs. If you add a column in the future that does not require presence validation, you will trip up. Also, some things my not require presence. For example, an email field will need a regex validation, which automatically knows that a blank string is invalid. So a presence validator is redundant.
Beware of being too clever, as it's sometimes not so clever after all.


text:
Q: Posting messages from a web worker during a long-running for-next loop I'm using a web worker to handle some CPU-intensive calculations that take about 10 seconds to run. The calculation requires a for-next loop.
So, roughly, in the web worker, it looks like this:
for (i = 0; i < 1000000; i++) {
    [... a bunch of calculations ...]
    if (i % 10000 === 0) {
        SELF.postMessage({msg:'progress', percent:i/1000000});
    }
}
SELF.postMessage({msg:'complete'});

This works great in Chrome and Safari on OS X - every 10,000 iterations, the parent receives the 'progress' message with the percent complete, and the 'complete' message when the loop is finished.
However, it does not seem work in IE11 or Firefox 37 - only the 'complete' message is sent.
Is this a bug in IE11 and/or Firefox, or just an implementation difference?
Is there a way to accomplish this in IE/Firefox without resorting to setIntervals, or splitting apart the for-next loop (which feels hacky...)?


text:
Q: Swift 3 Segue from UICollectionView Cell Hi I'm a beginner and stuck on a very basic segue! I just want to find out the correct syntax to use for the sender e.g sandals[indexPath.row]sandalName
Thanks
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! shoeCollectionViewCell
    let sandalCell = sandals[indexPath.row]
    cell.sandalImage.image = UIImage(named: sandalCell["image"]!)
    cell.sandalStyleName.text = sandalCell["styleName"]
    cell.sandalPrice.text = sandalCell["price"]
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoeDetailSegue"{
        var detailPage = segue.destination as! shoeDetailViewController
        let selectedCell = sender as! UICollectionViewCell
        let indexPath = collectionView?.indexPath(for: cell)
        detailPage.getName = sandals[indexPath!.row].sandalName
        detailPage.getPrice = sandals[indexPath!.row].sandalPrice
        detailPage.getImage = sandals[indexPath!.row].sandalImage
    }
}

A: If you want to just pass the value with segue you need to simply access the array with subscript same way you are doing in cellForItemAt.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoeDetailSegue"{

        var detailPage = segue.destination as! shoeDetailViewController
        let selectedCell = sender as! UICollectionViewCell
        let indexPath = collectionView?.indexPath(for: cell)
        let sandal = sandals[indexPath!.row]
        detailPage.getName = sandal["styleName"]!
        detailPage.getPrice = sandal["price"]!
        detailPage.getImage = UIImage(named: sandal["image"]!)
    }
}


text:
Q: Yii2 Csrf on turned off cookies I have a problem with crsf verification with my AJAX requests on Yii2.
Crsf is allowed in config file
 'request'=>array(
        'enableCsrfValidation'=>true,
        'enableCookieValidation'=>true,
    ),

and I have this line in main application layout
<?= Html::csrfMetaTags() ?>

All work's normally when cookies is turned on. Also http header have a X-CSRF-Token, witch value is different from cookie's _crsf param.
When I try to disable cookies on my localhost(to test website for nocookie users), ajax request does not work normally. (Error 400 Bad request).
In http request headers I see this line
X-CSRF-Token:"U05vc3J6YmVmPgAaFh8gAiMvPBQTETMrBjc8JRA4GywBBwMGAzA7Og=="

I saw same value in meta parameters of html page(and for cookie requests too).
Ajax request looks like this. I try to add crsf value to headers and to http param, but there is no effect. Also I have no beforeAction() methods
   var noCookieResp = $.ajax({
        //beforeSend: function(request){
        //    request.setRequestHeader("X-CSRF-Token", $('meta[name="csrf-token"]').attr("content"));
        //},
        type: 'POST',
        url: window.location.origin + '/frontend/web/viewer/noc',
        data: {
            id: postId,
            _csrf : yii.getCsrfToken()
        },
        error: function(e) {
            console.log(e);
        },
        success: function(){
            console.log(noCookieResp.responseText);
        }
    });

Any suggestions? Sorry for bad english

A: In most of case we do not need csrf_token when users disable cookies because them are not logged in. So you can disable csrf in some action or controller where you allow guest access.
public function beforeAction($action) {
     $this->enableCsrfValidation = false;
     return parent::beforeAction($action);
}


text:
Q: What can cause a website to not always load Roughly about 20% of the time when clicking on links in my website (www.slr-lens.co.uk), the site completely fails to load. I have tried removing and adding all code segments but to no avail... I've also asked the web hosts, but apparently the server is working normally.
Does anyone have any suggestions about what could cause a web page to sometimes not load? E.g. any specific lines in the php.ini?
The site uses sessions, and there's quite a lot of mysql action for each page load.
Internet explorer will say:
"Internet Explorer can't load this page"
Google chrome will say:
This web page is not avialable: Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error.
Firefox will sometimes only show a blank page.
Sorry for being so vague but its a really vague problem!
Thanks

A: The answer (or at least a clue) likely lies within your PHP / Apache error logs.

A: It could be your Apache logs or you just have a bad host. Either way, it seems to load every time here (10+). Have you tried replicating this problem somewhere else?


text:
Q: UIActivityViewController -- NSURL ActivityItemProvider default thumbnail I am trying to figure out what sets the default thumbnail under the paperclip (instead of the embossed Safari icon) when you use an NSURL to attach a link in a UIActivityViewController. I feel like I have seen websites such as google and the itunes store setting these thumbnails to be helpful images. I feel that the embossed safari icon is too vague and the user doesn't know what link he/she is sending.
Is it perhaps something in the html headers for that link?
Thanks!

A: I had to decypher all the UIActivityViewController documentation recently. You probably don't want to include a UIImage with your NSURL in blind hopes it will be used as a thumbnail. As I understand, you can't be sure what the UIActivity will do with the image, it might post that instead of the URL.
In your activityItems array parameter to initWithActivityItems:applicationActivities:, instead of the NSURL, pass an object you create conforming to the UIActivityItemSource protocol. You can have whatever controller is opening the UIActivityViewController be the object that conforms to this protocol, for example, in which case your activityItems parameter would be @[self].
In addition to implementing the 2 required methods activityViewControllerPlaceholderItem: and activityViewController:itemForActivityType: to both just return your NSURL, also implement this one to return whatever thumbnail image you like:
- (UIImage *)activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size;

Note one thing that isn't really spelled out in the documentation, if you really need to have multiple objects in your activityItems array and are updating it to use UIActivityItemSource (or UIActivityItemProvider) objects, then it needs a separate such object to return each of the original data objects in your original array. For example, if your data items are an NSURL and a UIImage then make one UIActivityItemSource to return the NSURL and another to return the UIImage. Having one UIActivityItemSource that returns an array of NSURL and UIImage like your original activityItems array does not work.

A: Have you tried setting the activityImage property of the derived UIActivity object to the image you want to displayed under the paperclip?
"
For UIActivityTypePostToTwitter:
The object posts the provided content to the user's Twitter feed. When using this service, you can provide NSString, NSAttributedString, UIImage, AVAsset, and NSURL objects as data for the activity items. You may also specify NSURL objects whose contents use the assets-library scheme."
Note the UIImage object that you can include in the array that get passed into the UIActivityViewController.  This link describes more on the activityImage property, http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivity_Class/Reference/Reference.html#//apple_ref/occ/instm/UIActivity/activityType.
Kevin


text:
Q: Python http response decoding I am currently working on a python3.3 api for arangodb and am running into the following problem in the HTTP responses when requesting things from arango's RESTful api.
the specific example has to do with the sha256 hashes of password.
if a section of the hashed password was this:
w/JjMM0gNl
when I use any of the python http libs the response is formated as such:
w\\/JjMM0gNl
encoding/decoding with various methods does not solve this and I am wondering what I can do to remedy this problem. If you are not familiar with arango, data is returned as json.

A: The reason might be that forward slashes are allowed to be escaped in JSON.
The forward slashes in the following JSON might actually be escaped with a backslash.
Unescaped:
{"foo/bar":"bar/baz"}

Escaped:
{"foo\/bar":"bar\/baz"}

When retrieving such escaped data back, the decoder needs to handle the \ in front of the / and ignore them. I think most decoders do not care whether or not forward slashes are escaped, at least they parse JSON data happily with forward slashes being escaped and without.
In any case, when you retrieve your data back as a python object from the decoder, the escape characters should go away. Handling escape sequences is a task encoders/decoders should handle transparently for you.
To go on: can you veryify if the JSON response from the server is actually correct? If yes, can you then try with a standalone python program whether your decode handles encoding/decoding of such string correctly?


text:
Q: Issue with eloquent Laravel I have a problem with Eloquent, how to show the sum of products with 0 purchase price.
my model invoice and method products
public function products()
{
    return $this->belongsToMany(Product::class)->withPivot('quantity', 'product_name', 'net_unit_price', 'gross_unit_price', 'purchase_price');

}

my model products and method invoice
public function invoices()
{
    return $this->belongsToMany(Invoice::class);
}

and I need sum - net_unit_price from invoices sold in this month for eg
$sellMonthReplace = $user->invoices()
        ->with(['products' => function ($query) {
            $query->wherePivot('purchase_price', '=', '0');
        }])
        ->whereNull('parent_id')
        ->where('incoming', '=', '0')
        ->whereNull('is_proforma')
        ->where('sell_date', '>', $now->format('Y-m-01'))
        ->sum('net_value');

but this isn't working.
this below work well but is raw SQL and I don`t know how do it in eloquent
select SUM(invoice_product.net_unit_price*invoice_product.quantity)
from homestead.invoices
join homestead.invoice_product on invoice_product.invoice_id = invoices.id
where invoices.sell_date > 2019-03-01
and invoices.incoming = 0
and invoices.parent_id is null
and invoices.is_proforma is null
and invoice_product.`purchase_price` = 0

anybody could help me? thank you in advance

A: Did you try to cut your query short to make sure that your relations are working?
Also is the $user variable filled properly ?
What does a dump of the $sellMonthReplace return to you?


text:
Q: What are some ways to use different background colors in CSS? Let's say I have 5 webpages and on each webpage I want the background color to be different.  I am using only 1 css file.  Each webpage will be accessed like this: domain.com/page1
Do I simply using 5 different CSS files and just change the background-color in the body or is there a more simpler way to achieve this?

A: Add different class to your <body> on each site, and then use that class to get proper background color.
Of course, you don't have to multiply code, that is common to all sites.

A: For example:
On "page1":
<body id="page1">

On "page2":
<body id="page2">

Your CSS:
body#page1 {
    background: red;
}

body#page2 {
    background: blue;
}

A: well if all pages use the same css file the same background will be used to all...
one easy way to do it is to overrule existing background-color in body. so if you have like a css file containing:
body
{
   background-color: aqua;
}

then below that (after the css file is implemented) and on the page you need to have a new color you can just overrule it with following:
<style type="test/css">
body
{
    background-color: blue;
}
</style>

A: How about adding a simple inline style to the body tag of each page such as this?
Page 01
    <body style="background-color:#111;">

Page 02
    <body style="background-color:#222;">

Page 03
    <body style="background-color:#333;">

Bare in mind that in regards to design, such proposed variation in colour scheme is often a bad idea. There might be some function behind your idea which would make sense but otherwise I would recommend minimalism coupled with consistency throughout the design process.


text:
Q: How to parse page that uses HTML5 local storage? In advance sorry for my English)
I have a task - write a parser for site, but all his pages save entered data in HTML5 local storage. Its really to emulate click on images on pages and retrieve all variables values that was saved to data storage after this click? For example, using NodeJS + parser like jsdom (https://github.com/tmpvar/jsdom)? Or i can use some alternatively technologies for this?
Thank you!

A: Sounds like you are trying to parse a website with lots of javascript. You can use phontom to simulate user behaviour. Consider you want to use node. Then you can use Node-Phontom to do that.
var phantom=require('node-phantom');
phantom.create(function(err,ph) {
  return ph.createPage(function(err,page) {
    return page.open("you/url/", function(err,status) {
      console.log("opened site? ", status);
      page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {
        //jQuery Loaded.
        //Settimeout to wait for a bit for AJAX call.
        setTimeout(function() {
          return page.evaluate(function() {
            //Get what you want from the page
            //e.g. localStorage.getItem('xxx');
        }, 5000);
      });
    });
  });
});

Here is phontom.
Here is node-phontom.


text:
Q: Download file from server to clients system via php I am using following script to download a file via PHP:
header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=sale.csv');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".filesize($CSVFileName));
        readfile($CSVFileName);

$CSVFilename value is "/home/demo/public_html/testwordpress/csv/sale.csv"
Also tried header("Content-type: text/csv");
Somehow it is not downloading the csv file given on the path. It is downloading source code of the page in csv.
Here is the code i am getting:
<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" lang="en-US">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8)  ]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Call Details | Test</title>
<link rel="profile" href="http://gmpg.org/xfn/11" />

Please advise

A: I may be a little off my rocker here, but there is a much simpler way ( I think! ) to simply download a file.
$file = "/home/demo/public_html/testwordpress/csv/sale.csv";
$contents = file_get_contents($file);

// Manipulate the contents however you wish.
$newFilePath = "somewhere/over/the/rainbow/sale.csv";
file_put_contents($newFilePath, $contents);

*

*The file_get_contents will work with http streams as well.

A: I made it this way:
<?PHP
    $filename= "yourfilepath.csv";

    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");

    echo "your content to the .csv file";
?>


text:
Q: ASP more quotes in function inside a tag element I'm trying to make alert with value from DataBinder inside a tag element. I try many variations with quotes, but still no success.
My code
OnClientClick='alert(<%# DataBinder.Eval(Container.DataItem, "path", "{0}")%>);'

Any idea?
Thanks

A: JS
<script type="text/javascript">
            function Check(a) {
                alert(a);
            }

        </script>

Code Behind:
 OnClientClick=<%# "Check('" + Eval("path") +"')"%> runat="server" />

Or simply
  OnClientClick=<%# "alert('" + Eval("Id") +"')"%> runat="server" />