text:
Q: Unable to get records by join with where clause I have 2 tables. first users second post. without where clause I got all user post but I want to display only logged in user data. here is table structure for my tables. both tables has common value by user.id = post.user_id
First Table User            Second Table Post
ID                           id
NAME                         user_id
Username                     category_id
Password                     user_id
                             title
                             body

My Query to get all records but doesn't logged in user records
public function get_posts(){
  $this->db->order_by('posts.id', 'DESC');
  $this->db->join('categories', 'categories.id = posts.category_id');
  $query = $this->db->get('posts');
  return $query->result_array();
}

A: Hope this will help you :
Here $user_id is id of logged in user should be passed to the model from controller
public function get_posts($user_id)
{
   $this->db->select('*');
   $this->db->from('posts');
   $this->db->order_by('posts.id', 'DESC');
   $this->db->join('users', 'users.id= posts.user_id');
   $this->db->where('users.id',$user_id);
   $query = $this->db->get();
   return $query->result_array();
}

A: try this,
public function get_posts()
{
    $this->db->select('*');
    $this->db->from('posts');
    $this->db->join('users', 'users.id = posts.user_id');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $this->db->order_by('posts.id', 'DESC');
    $query = $this->db->get();
    return $query->result_array();
}

A: you can use it like this , just replace $user_id variable with your dynamic post user id value
$this->db->select('a.*');
$this->db->from('user a');
$this->db->join('post b', 'b.user_id = a.id', 'left');
$this->db->where('a.id', $user_id);
$data_array = $this->db->get()->result_array();
return $data_array ;

Hope this will help you ....


text:
Q: iOS / Swift 3.0: how do you determine which rows are currently visible in a UITableView? How do you determine which rows are currently visible in a UITableViewController in Swift 3.0?

A: You can use:
tableView.visibleCells

This is an array of UITableViewCell that are currently visible in the table view.
If you just need the index paths of the visible rows, you can use:
tableView.indexPathsForVisibleRows

which is an array of IndexPath objects.

A: It's quite simple. You just need to use…
tableView.visibleCells

From Apple docs…

The value of this property is an array containing UITableViewCell
  objects, each representing a visible cell in the table view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\rho g h$ and shape of container inconsistency? The Scenario
Suppose I have a cylindrical beaker and a conical flask (which cross-sectional area is bigger at the bottom), each located on an identical digital weight scale. Both of them have the same area, $A$, at the bottom and both are weightless. I fill both of them with identical fluids so that the height of the fluid in each container is the same. Obviously, the conical flask will require less to do so. Assume equal atmospheric pressure and gravity.
The Inconsistency
According to hydrostatics, the pressure at depth $h$, independent of the container shape, is:
$$P(h)=\rho gh + P_0$$
where $\rho$ is the density of the fluid and $P_0$ is the atmospheric pressure at the fluid surface.
Both the cylindrical beaker and the conical flask have the same fluid height; therefore, both should have the same pressure at the bottom, regardless of their shape. Since they have the same area at the bottom, the force exerted on the weight scale should be equal ($F=PA$). Therefore, the weight scales should register the same weight for both the cylindrical beaker and the conical flask.
This is impossible, since the amount of fluid in each container is significantly different (approximately by a factor of $3$).
The answers to this related question says that the additional weight of an inverted conical flask is due to the forces acting on the walls. However, I don't believe that it is possible for the water to act an upward force on the walls and thus lift the container upwards.
How does one explain this inconsistency?

A: Pressure acts in all directions.  When the pressurized fluid touches the tilted side of the container, the force due to that pressure is outward and perpendicular to the surface.
A similar question (Pressure,Pascals Law) was asked the other day, and this was part of the answer.
Is this counter-intuitive?  It shouldn't be.  It's easy to think of cases when pressurized water is forced to spray upwards.  If that spray is covered up, the force of the water on the plug is upward as well.


text:
Q: Passing FileName dynamically when fetching Data? Selenium -java when i pass the file name like this, it doesn't fetch the data..what to do for passing the fileName dynamically in the method ?
    public static String fetchData(int index,int rowNum, int cellNum,String FileName) throws FileNotFoundException {

        File filePath = new File(System.getProperty("user.dir") + "/InEdge_Files/ExcelData/" + FileName + ".xlsx");
        fis = new FileInputStream(filePath);
        sheet = workbook.getSheetAt(index);
        value = sheet.getRow(rowNum).getCell(cellNum).getStringCellValue();
        return value;

    }

...When passing the Data i use, driver.get(fetchData(0,1,2,"Data");

A: String urlToOpen = fetchData(0,1,2,"Data");
driver.navigate().to(urlToOpen);


text:
Q: Arranging numpy arrays in a block matrix I have 3 numpy arrays A, B and C. For simplicity, let's assume that they are all of shape [n, n]. I want to arrange them as a block matrix
A    B
B^t  C

where B^t shall denote the transpose of B. Of course, I could do this via a series of concatenations
top_row = np.concatenate([A, B], axis=1)
bottom_row = np.concatenate([B.transpose(), C], axis=1)
result = np.concatenate([top_row, bottom_row], axis=0)

Is there a simpler, more readable way?

A: As of NumPy 1.13, there's np.block. This builds matrices out of nested lists of blocks, but it's also more general, handling higher-dimensional arrays and certain not-quite-grid cases. It also produces an ndarray, unlike bmat.
np.block([[A, B], [B.T, C]])

For previous versions, you can use the NumPy built-in np.bmat that's perfectly suited for such a task, like so -
np.bmat([[A, B], [B.T, C]])

As mentioned in the comments by @unutbu, please note that the output would be a NumPy matrix. If the intended output is an array instead, we need to convert it, like so -
np.asarray(np.bmat([[A, B], [B.T, C]]))

or
np.bmat([[A, B], [B.T, C]]).A

A: Stripped of some bells and whisles, np.bmat does this:
def foo(alist):
    rowlist=[]
    for row in alist:
        rowlist.append(np.concatenate(row,axis=1))
    return np.concatenate(rowlist, axis=0)

So for example:
In [1026]: A=np.arange(4).reshape(2,2);B=np.arange(2).reshape(2,1);C=np.array([0]).reshape(1,1)

In [1027]: foo([[A,B],[B.T,C]])
Out[1027]:
array([[0, 1, 0],
       [2, 3, 1],
       [0, 1, 0]])

Making the inputs matrices simplifies the reshape preparation.


text:
Q: Resistors both in series and in parallel?
Consider this circuit. I'm assuming that the resistors have the same resistance. The same amount of current flows through them so they must be in series. But the voltage across each resistor is also the same so they must be in parallel. So are these resistors connected in series or parallel?
Am I just confusing the definitions?

A:
the voltage across each resistor is also the same

No.
The voltage across the total of both resistors is the same no matter their values (assuming the voltage source can provide sufficient current).
The voltages across each of the two resistors are the same ONLY if the two resistors are of equal value.  If not, the voltage across each resistor is proportional to its value, per Ohm's Law.

A: In general, circuits are about galvanic closed loops. You can select any such loop you want.
Here's a GRANU schematic (generally recognized as not useful):

simulate this circuit – Schematic created using CircuitLab
A galvanic closed loop might be \$R_1\$, \$C_4\$ and \$B_1\$, for example. You can draw a circle over that to form a loop. Another loop might be just \$C_1\$ and \$R_4\$. Another loop might be \$C_2\$, \$R_5\$, \$R_4\$, and \$R_3\$, since those are also all connected and if you ignored all the other parts and wiring would form a loop. There are many loops above.
But there aren't many parallel pairs of parts. \$C_1\$ is in parallel with \$R_4\$, \$C_3\$ is in parallel with \$R_6\$, and \$C_4\$ is in parallel with \$R_7\$. That's because in all three cases there is a loop formed only by those two parts. If you cannot find a loop that involves just the two parts, then they are not in parallel with each other.
Now let's look at a different schematic:

simulate this circuit
Both resistors have the same voltage across them. But they are not in parallel with each other. Having the same voltage across a part does not mean they are in parallel. And not only do both those resistors have the same voltage across them, but they also have the exact same voltages on both ends, too. Yet they are not in parallel because you cannot draw a loop through just those two resistors. It cannot be done.
If, however, you strung a wire from the top end of one resistor to the top end of the other resistor, then they'd be in parallel.

A: They are in series because current flows through one and then the other.  The fact that the voltages and currents are equal are effects of parallel/series connection but don't define it.


text:
Q: Comparison of java return statement and python return statement So ive learned some basic python programming and was learning some Java through some books.
I was trying out some pretty basic coding examples on eclispe and i had a question about the return statement
in Python a return statement in a function for example would output something to the screen for instance in python if a function was :
def test(x):
    return x
and i tested with test(4)
integer 4 would output to the screen.
Does return work the same way in java?

A: In Python the return statement does not print anything to the screen. What's happening is that you're running Python in a REPL (an interactive mode), so the values returned by the functions get automatically displayed on-screen.
However, if you run Python from a command line (say, by executing a script) the values returned by functions will not be displayed on-screen ... unless you explicitly print them. Same is true for java:
System.out.println(x); // this is how you print in Java
print(x)               // this is how you print in Python

AFAIK all the programming languages that have a return keyword (or equivalent) don't print anything on-screen, return is useful only for, well, returning a value from a function or method. A separate instruction is required for displaying results.

A: In Java the return function passes an object or primitive back to the calling method (the code that originally called your function). The calling method may do whatever it likes (including print) the returned value.
public static int myMethod() {
    return 5;
}

public static void main (String[] args) {
    int a = myMethod();
    System.out.println(a); //prints 5
}


text:
Q: How to query which users are using which certificates in SQL Server? I would like to know which users a certificate is used by.  I tried to do this query but got no results:
SELECT
    master.sys.sql_logins.name,
    sys.certificates.name
FROM
    master.sys.sql_logins
INNER JOIN
    sys.certificates
    ON master.sys.sql_logins.sid = sys.certificates.sid

Does anyone know how to do this?
Any help would be greatly appreciated.

A: That information is not exactly available and may be a security risk if it was, because essentially you'd need to know the public keys used with that certificate. This StackOverflow answer may be relevant and essentially agrees with my previous statement.
Taking a step back, these are the things you can derive though:

*

*If your certificate was generated for a specific database, then all principals within that database are applicable to that certificate. You should be able to see which principals are mapped to the given database certificate by querying sys.database_principals WHERE type = 'C' as discussed here.

*You should be able to get the principal of who owns a given certificate by using the principal_id to join to the sys.server_principals view to get the principal name.


text:
Q: Regular expression for float to distinguish from dates I need detect in the text the floating point numbers. I researched many solutions, but all not work correctly for my case. I have in the text the numbers :
.34

0.34

23.54

but I have too the date in the format: dd.mm.yyyy
The problem is that many solutions detect date from text as float too. In the final I need replace in the text the dot with comma only for numbers, not for date

A: you can use (?<= )(\d+)?\.(\d+)?(?= ) . that used look-around to match float numbers between 2 spaces !
DEMO

A: Try (?<=^| )\d+(\.\d+)?(?=$| ) for matching just floating point numbers. It should not match date numbers.


text:
Q: Regular Expression not working in ios11 only working fine in ios10 Requirement;
All Special characters allowed excluding (`) (') () (") and Spaces
using below for the same and working fine in ios 10
const UserIdRegExp = /[^`"' \\]$/g;

not working in ios11
const value='anand`';
when i am doing UserIdRegExp.test(value);
ios10 return false.
and ios11 return true

A: In iOS 11 Apple introduced "Smart Punctuation", which automatically slants certain punctuation marks based on content.
const regex = /[^`"""''' \\]$/g;

Example:
iOS 10: "double quotes", 'single quotes'
iOS 11 (with Smart Punctuation on): "double quotes", 'single quotes'


text:
Q: What is there to do in the post-game? I've cleared all the sidequests in Blood Dragon before taking on the last missions. Walking around a bit in the post-game, I don't see anything to do. Are there any post-game missions?

A: Not really. That option is really only their if you were missing side missions. All you can really do now is run around.


text:
Q: NoMethodError (undefined method `fetch' for nil:NilClass) Issue is with broadcasting data through a web socket using ActionCable. The error seems to suggest its coming from the create method.
Error Message
 Rendered weight/_weight.html.erb (1.1ms)
 [ActionCable] Broadcasting to weight: "
\n
\n
12.0 kg
\n    less than a minute\n
\n
"
Completed 500 Internal Server Error in 25ms (Views: 7.4ms | ActiveRecord: 10.6ms)

NoMethodError (undefined method `fetch' for nil:NilClass):

app/controllers/weight_controller.rb:7:in `create'
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.8ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.9ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (25.0ms)

Create method from controller.rb
def create
   @weight = Weight.new(weight_params)
   @weight.user_id = current_user.id
    if @weight.save
        ActionCable.server.broadcast "weight", render(partial: 'weight/weight', object: @weight)

    else
        flash[:danger] = "New Weight was not added!"
        redirect_to current_user
    end
end

private

def weight_params
    params.require(:weights).permit(:weight)
end

I just cant work out what is returned as nil. The fact that the info is correct in what it is broadcasting to weight is correct suggests it has saves it correctly to the database. Can't think what else it is performing the 'fetch' method on.
Pretty sure the web socket is set up correctly. See below.
config/application.rb :
config.action_cable.mount_path = '/cable'

config/routes.rb :
mount ActionCable.server => '/cable'

weight_channel.rb :
def subscribed
  stream_from "weight"
end

weight.coffee :
 received: (data) ->
    $("#messages").prepend(data)

A: The error was raised due to a missing config/cable.yml file.
The solution was to use a config/cable.yml with the required setting for the application. i.e.:
# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket.
production:
  adapter: redis
  url: redis://localhost:6379/1

development:
  adapter: redis
  url: redis://localhost:6379/1

staging:
  adapter: redis
  url: redis://localhost:6379/1

test:
  adapter: async

The resolution appears in the question's comments.


text:
Q: PLS-00221: 'DISPLAY_TRANS' is not a procedure or is undefined I am making a PL SQL application for printing a receipt, but I am having a problem with displaying the function. It shows the error --- PLS-00221: 'DISPLAY_TRANS' is not a procedure or is undefined --- when I invoke it.
My function looks like this:
CREATE OR REPLACE FUNCTION DISPLAY_TRANS(in_id diamanteruga_invoice.invoice_id%TYPE) RETURN NUMBER AS
    v_gas_type diamanteruga_gas.gas_type%TYPE;
    v_gas_liters diamanteruga_gas.gas_liters%TYPE;
    v_gas_priceperliter diamanteruga_gas.gas_priceperliter%TYPE;
    v_gas_amount diamanteruga_gas.gas_amount%TYPE;
    v_vatable_sale diamanteruga_invoice.vatable_sale%TYPE;
    v_vat_exempt_sale diamanteruga_invoice.vat_exempt_sale%TYPE;
    v_vat_zero_rated_sale diamanteruga_invoice.vat_zero_rated_sale%TYPE;
    v_subtotal diamanteruga_invoice.subtotal%TYPE;
    v_vat diamanteruga_invoice.subtotal%TYPE;
    v_amount_due diamanteruga_invoice.amount_due%TYPE;
    v_amount_paid diamanteruga_invoice.amount_paid%TYPE;
    v_change_due diamanteruga_invoice.change_due%TYPE;
    v_payment_type diamanteruga_invoice.payment_type%TYPE;
    BEGIN
    select gas_type, gas_liters, gas_priceperliter, vatable_sale, vat_exempt_sale, vat_zero_rated_sale, subtotal, vat, amount_due, amount_paid, change_due, payment_type
    into v_gas_type, v_gas_liters, v_gas_priceperliter, v_vatable_sale, v_vat_exempt_sale, v_vat_zero_rated_sale, v_subtotal, v_vat, v_amount_due, v_amount_paid, v_change_due, v_payment_type
    from diamanteruga_invoice join diamanteruga_gas using (gas_id)
    where invoice_id = in_id;

    dbms_output.put_line ('');
    dbms_output.put_line ('   DESCRIPTION                                  AMOUNT');
    dbms_output.put_line('________________________________________________________________');
    dbms_output.put_line ('   ' ||v_gas_type|| '                               '||to_char((v_vatable_sale), '9999.99'));
    dbms_output.put_line ('       ' || v_gas_liters || ' @ P/L' || v_gas_priceperliter );
    dbms_output.put_line('________________________________________________________________');
    dbms_output.put_line ('   VATable Sale                               ' || to_char(v_vatable_sale, '9999.99'));
    dbms_output.put_line ('   VAT-Exempt Sale                              ' || to_char(v_vat_exempt_sale, '0.99'));
    dbms_output.put_line ('   VAT-Zero Rated Sale                          ' || to_char(v_vat_zero_rated_sale, '0.99'));
    dbms_output.put_line ('   Sub Total(12% VAT)                         ' || to_char((v_vatable_sale/1.12),'9999.99'));
    dbms_output.put_line ('   VAT(12%)                                   ' || to_char((v_vatable_sale-(v_vatable_sale/1.12)), '9999.99'));
    dbms_output.put_line ('');
    dbms_output.put_line ('   Amount Due                                 ' || to_char(v_amount_due, '9999.99'));
    dbms_output.put_line ('   Cash Tendered                              ' || to_char(v_amount_paid, '9999.99'));

    if (v_amount_due-v_amount_paid) <= 0 then dbms_output.put_line ('   Change Due                                   ' || to_char((v_amount_due-v_amount_paid),'0.99'));
    else dbms_output.put_line ('   Change Due                                   ' || to_char((v_amount_due-v_amount_paid),'9999.99'));
    end if;
    dbms_output.put_line ('');
    dbms_output.put_line ('________________________________________________________________');
    dbms_output.put_line ('');
    dbms_output.put_line ('   PAYMENT TYPE: ' || v_payment_type);
    RETURN NULL;
    END DISPLAY_TRANS;

And my invoker looks like this:
    set serveroutput on
    BEGIN
    DISPLAY_TRANS(000000322170);
    END;

Output is supposed to be:
  DESCRIPTION                                  AMOUNT
________________________________________________________________
   8 PREMIUM 95                                 500.00
       11.99 @ P/L41.7
________________________________________________________________
   VATable Sale                                 500.00
   VAT-Exempt Sale                               0.00
   VAT-Zero Rated Sale                           0.00
   Sub Total(12% VAT)                           446.43
   VAT(12%)                                      53.57

   Amount Due                                   500.00
   Cash Tendered                                500.00
   Change Due                                    0.00

________________________________________________________________

   PAYMENT TYPE: Cash

Please help me find a solution...

A: You execute a PL/SQL Function in wrong way.
The correct ways are:
1) Since a function returns a value we can assign it to a variable.
declare result varchar2(20);
result :=  DISPLAY_TRANS(000000322170);

2) As a part of a SELECT statement
SELECT  DISPLAY_TRANS(000000322170) FROM dual;

3) In a PL/SQL Statements like,
dbms_output.put_line( DISPLAY_TRANS(000000322170));

This line displays the value returned by the function.
However in your case, better option is procedure. Drop the function (DROP FUNCTION DISPLAY_TRANS) that you created and try the below:
CREATE OR REPLACE procedure DISPLAY_TRANS(
in_id diamanteruga_invoice.invoice_id%TYPE
)
 AS
    v_gas_type diamanteruga_gas.gas_type%TYPE;
    v_gas_liters diamanteruga_gas.gas_liters%TYPE;
    v_gas_priceperliter diamanteruga_gas.gas_priceperliter%TYPE;
    v_gas_amount diamanteruga_gas.gas_amount%TYPE;
    v_vatable_sale diamanteruga_invoice.vatable_sale%TYPE;
    v_vat_exempt_sale diamanteruga_invoice.vat_exempt_sale%TYPE;
    v_vat_zero_rated_sale diamanteruga_invoice.vat_zero_rated_sale%TYPE;
    v_subtotal diamanteruga_invoice.subtotal%TYPE;
    v_vat diamanteruga_invoice.subtotal%TYPE;
    v_amount_due diamanteruga_invoice.amount_due%TYPE;
    v_amount_paid diamanteruga_invoice.amount_paid%TYPE;
    v_change_due diamanteruga_invoice.change_due%TYPE;
    v_payment_type diamanteruga_invoice.payment_type%TYPE;
 BEGIN
    select gas_type, gas_liters, gas_priceperliter, vatable_sale, vat_exempt_sale, vat_zero_rated_sale, subtotal, vat, amount_due, amount_paid, change_due, payment_type
    into v_gas_type, v_gas_liters, v_gas_priceperliter, v_vatable_sale, v_vat_exempt_sale, v_vat_zero_rated_sale, v_subtotal, v_vat, v_amount_due, v_amount_paid, v_change_due, v_payment_type
    from diamanteruga_invoice join diamanteruga_gas using (gas_id)
    where invoice_id = in_id;

    dbms_output.put_line ('');
    dbms_output.put_line ('   DESCRIPTION                                  AMOUNT');
    dbms_output.put_line('________________________________________________________________');
    dbms_output.put_line ('   ' ||v_gas_type|| '                               '||to_char((v_vatable_sale), '9999.99'));
    dbms_output.put_line ('       ' || v_gas_liters || ' @ P/L' || v_gas_priceperliter );
    dbms_output.put_line('________________________________________________________________');
    dbms_output.put_line ('   VATable Sale                               ' || to_char(v_vatable_sale, '9999.99'));
    dbms_output.put_line ('   VAT-Exempt Sale                              ' || to_char(v_vat_exempt_sale, '0.99'));
    dbms_output.put_line ('   VAT-Zero Rated Sale                          ' || to_char(v_vat_zero_rated_sale, '0.99'));
    dbms_output.put_line ('   Sub Total(12% VAT)                         ' || to_char((v_vatable_sale/1.12),'9999.99'));
    dbms_output.put_line ('   VAT(12%)                                   ' || to_char((v_vatable_sale-(v_vatable_sale/1.12)), '9999.99'));
    dbms_output.put_line ('');
    dbms_output.put_line ('   Amount Due                                 ' || to_char(v_amount_due, '9999.99'));
    dbms_output.put_line ('   Cash Tendered                              ' || to_char(v_amount_paid, '9999.99'));

    if (v_amount_due-v_amount_paid) <= 0 then dbms_output.put_line ('   Change Due                                   ' || to_char((v_amount_due-v_amount_paid),'0.99'));
    else dbms_output.put_line ('   Change Due                                   ' || to_char((v_amount_due-v_amount_paid),'9999.99'));
    end if;
    dbms_output.put_line ('');
    dbms_output.put_line ('________________________________________________________________');
    dbms_output.put_line ('');
    dbms_output.put_line ('   PAYMENT TYPE: ' || v_payment_type);

 END DISPLAY_TRANS;

The procedure can be called declivity by:
SQL> EXECUTE  DISPLAY_TRANS(000000322170);

Or like you mentioned:
BEGIN
DISPLAY_TRANS(000000322170);
END;


text:
Q: An axis number cannot be repeated in a query i use SSAS And Sql Server 2008 R2.
i writed this query in SSAS
SELECT
 Measures.[Internet Sales Amount] ON COLUMNS
    , [Measures].[Internet Freight Cost] ON COLUMNS
FROM [Adventure Works]
WHERE
    (
        [Date].[Calendar].[Calendar Quarter]. & [2003] & [2],
        [Product].[Product Line].[Mountain],
        [Customer].[Country].[Australia]
    )

I was got this error

Executing the query ...
An axis number cannot be repeated in a query.
Execution complete

How i can select two columns in MDX Query?

A: You don't need to specify the axis for each measure:
SELECT
{
    [Measures].[Internet Sales Amount],
    [Measures].[Internet Freight Cost]
}ON COLUMNS
FROM [Adventure Works]
WHERE
    (
        [Date].[Calendar].[Calendar Quarter]. & [2003] & [2],
        [Product].[Product Line].[Mountain],
        [Customer].[Country].[Australia]
    )


text:
Q: How do I power a pump with a Reactor So, I built a 5 x 5 reactor.  My next question cannot be as easily answered any where else.  Can I power a BC Factory Pump with A Big Reactor Yellorium passively cooled 5 x 5 reactor.
Bonus:  What site can point me to what all can be powered by a reactor.

A: Yes. A Big Reactors reactor produces Redstone Flux (RF). Redstone Flux is converted to Buildcraft power automatically within most energy conduits.
Redstone Flux is a common power system that a lot of mods use. Your reactor should be able to power pretty much anything except for machines from IndustrialCraft2 (and given the right setup, you can convert RF to EU).


text:
Q: using google map API or usual API for compiling android project in V2? In google map android V1 project, it should be compiled with google maps API not ordinary API. I wonder if the same story for google map android V2 also?

A: No, Maps V2 has no dependency on the original Maps SDK add-on. You are welcome to set a plain Android build target on your project and skip the <uses-library> element. Maps V2 has its own set of dependencies, notably on OpenGL ES 2.0+ and the existence of the Play Services Framework.


text:
Q: using mutate with purrr's map
how could I add a column in a tibble which is in a list?
The data looks like the following and I just want to add a column at the end which checks if column 2 is the same as 3
[[1]]
# A tibble: 620 x 4
   DataName              `Technischer Platz...4` `Technischer Platz...5` `Technischer Platz...307`
   <chr>                 <chr>                   <chr>                   <lgl>
 1 WrW_SAPP17_VIAUFKAFVC 1202362-001             1202362-001             NA
 2 WrW_SAPP17_VIAUFKAFVC 1202362-002 037         1202362-002 037         NA
 3 WrW_SAPP17_VIAUFKAFVC 1202362-011             1202362-011             NA
 4 WrW_SAPP17_VIAUFKAFVC 1202362                 1202362                 NA
 5 WrW_SAPP17_VIAUFKAFVC 1202362-004 052         1202362-004 052         NA
 6 WrW_SAPP17_VIAUFKAFVC 1202362-018 005         1202362-018 005         NA
 7 WrW_SAPP17_VIAUFKAFVC 1202362-017             1202362-017             NA
 8 WrW_SAPP17_VIAUFKAFVC 1202362-012             1202362-012             NA
 9 WrW_SAPP17_VIAUFKAFVC 1202362-002 002         1202362-002 002         NA
10 WrW_SAPP17_VIAUFKAFVC 1202362-002 039         1202362-002 039         NA

A: We can use :
library(dplyr)
library(purrr)

list_df <- map(list_df, ~.x %>%
            mutate(is_2_same_as_3 = `Technischer Platz...4` == `Technischer Platz...5`))

If you want to do it based on position of columns use :
list_df <- map(list_df, ~.x %>%
                          mutate(is_2_same_as_3 = .[[2]] == .[[3]]))

Same in base R would be using lapply :
list_df <- lapply(list_df, function(x) transform(x, is_2_same_as_3 = `Technischer Platz...4` == `Technischer Platz...5`))
list_df <- lapply(list_df, function(x) transform(x, is_2_same_as_3 = x[[2]] == x[[3]]))

A: Let's use a simpler example
library(tidyverse)

honda <- tibble(brand = "HONDA",
                disp  = c(3, 8, 20),
                hp    = c(3, 90, 115))

volvo <- tibble(brand = "VOLVO",
                disp  = c(3, 8, 20),
                hp    = c(3, 34, 115))

list_df <- list(honda, volvo)

list_df %>% map(~ mutate(., check = disp == hp))
#> [[1]]
#> # A tibble: 3 x 4
#>   brand  disp    hp check
#>   <chr> <dbl> <dbl> <lgl>
#> 1 HONDA     3     3 TRUE
#> 2 HONDA     8    90 FALSE
#> 3 HONDA    20   115 FALSE
#>
#> [[2]]
#> # A tibble: 3 x 4
#>   brand  disp    hp check
#>   <chr> <dbl> <dbl> <lgl>
#> 1 VOLVO     3     3 TRUE
#> 2 VOLVO     8    34 FALSE
#> 3 VOLVO    20   115 FALSE

Created on 2021-02-18 by the reprex package (v1.0.0)


text:
Q: Load external Assembly (RCL) to Blazor WebAssembly app It is possible to load a RCL (Razor Component Library) to Blazor WebAssembly dynamically?
I found this Loading an external .NET Standard 2.0 assembly with blazor to load a standard classes
What I want is to develop a pluggable/extensible visual framework, where putting a dll in a ASP.NET Core Server folder where enought to access to that blazor component
Solution config:

*

*ASP.NET Core WebAPI project

*Blazor WebAssembly project

*RCL project 1 with some components

*RCL project 2 with another components

Steps:

*

*Open a Blazor Page and OnInitializedAsync() retreive some dll from WebAPI as binary

*Load binary to Assembly

*Reference the assembly and use it dynamically in the page

A: Sorry for the late answer, but yes, you can do that.
To use dynamic components, follow these steps:

*

*Load the assemblies using the Assembly.LoadfFrom(assemblyFilename)

*In a .razor file, use the blazor render tree builder to render your component dynamically, like this:

RenderFragment EditContent = (__builder) =>
{
    __builder.OpenComponent(0, TypeOfYourComponent);
    __builder.AddAttribute(1, "attr1", attrValue);
    ...
    __builder.AddAttribute(n, "attrn", attrNValue);
    __builder.CloseComponent();
};
@EditContent

*Implement a method that returns the type you want from the currently loaded assemblies. The following will provide you a list with all types exported by dynamically loaded assemblies:

var exportedTypes = new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

foreach (var assembly in assemblies)
{
    exportedTypes.AddRange(assembly.GetExportedTypes().ToList());
}

In my case, I created a singleton that loads the assemblies from a folder when it is initialized, and created a method in this singleton to return the type from the list defined on step 3. So, in this way, you can call this service whenever you like by registering it on the Startup.cs and injecting it on your razor components:
public class CustomComponentService : ICustomComponentService
{
    public CustomComponentService(...)
    {
        // load the assemblies here
    }

    public Type GetCustomComponent(...)
    {
        //search in the loaded assemblies by any criteria you like
    }
}

In the Startup.cs ConfigureServices method:
_ = services.AddSingleton<ICustomComponentService, CustomComponentService>();

In the razor file:
@inject ICustomComponentService CustomComponentService

...
__builder.OpenComponent(0, CustomComponentService.GetCustomComponent(...));
...

A: I finally develop a solution I want to share with you. A Module Manager witch allows you to load any outside component dynamically
Check it out here:
https://github.com/elgransan/BlazorPluginComponents
Some example code
        var componentPackage = "RazorClassLibrary2";
        var component = "Component2";
        var stream = await Http.GetStreamAsync($"{MyNavigationManager.BaseUri}/{componentPackage}/{componentPackage}.dll");
        var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
        componentType = assembly.GetType(componentPackage + "." + component);
        await DOMinterop.IncludeLink(componentPackage, $"/{componentPackage}/{componentPackage}.styles.css");

Where the files are in the server


text:
Q: Why am I getting a "unique key prop" warning when my mapped input components already have a unique key? I'm trying to create a form in my react app. I created an input.js component which is imported into my contact.js component and then mapped. I'm getting a "Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of input" inside the console, but I don't understand why because every input component has a unique key already set. When I check them in chrome inspector's react tab, they all have a unique key set.
This is my contact.js component:
import React, { Component } from 'react';
import Input from './Input/input';
import Button from './Button/Button';
import Spinner from '../UI/Spinner/Spinner';
import {checkValidity} from '../../shared/utility';

import axios from '../../axios-contact';

class ContactForm extends Component {
    state = {
        contactForm: {
            name: {
                elementType: 'input',
                elementConfig: {
                    inputprops: {
                        type: 'text',
                        id: 'name',
                        name: 'name',
                        required: 'required'
                    } ,
                    label: 'Name',
                    htmlFor: 'name',
                    invalid: 'Please enter your firstname',
                    value: '',
                },
                validation: {
                    required: true,
                    minLength: 2,
                    maxLength: 30
                },
                valid: false,
                touched: false
            },
            company: {
                elementType: 'input',
                elementConfig: {
                    inputprops: {
                        type: 'text',
                        id: 'company',
                        name: 'company',
                        required: 'required'
                    },
                    label: 'Company',
                    htmlFor: 'company',
                    invalid: 'Please enter your company name',
                    value: '',
                },
                validation: {
                    required: true,
                    minLength: 2,
                    maxLength: 30
                },
                valid: false,
                touched: false
            },
            location: {
                elementType: 'input',
                elementConfig: {
                    inputprops: {
                        type: 'text',
                        id: 'location',
                        name: 'location',
                        required: 'required'
                    },
                    label: 'Company location (city / country)',
                    htmlFor: 'location',
                    invalid: 'Please enter your location',
                    value: '',
                },
                validation: {
                    required: true,
                    minLength: 2,
                    maxLength: 30
                },
                valid: false,
                touched: false
            },
            email: {
                elementType: 'email',
                elementConfig: {
                    inputprops: {
                        type: 'email',
                        id: 'email',
                        name: 'email',
                        required: 'required'
                    },
                    label: 'Email',
                    htmlFor: 'email',
                    invalid: 'Please enter a propper email address',
                    value: '',
                },
                validation: {
                    required: true,
                    isEmail: true,
                    minLength: 7,
                    maxLength: 40
                },
                valid: false,
                touched: false
            },
            phone: {
                elementType: 'input',
                elementConfig: {
                    inputprops: {
                        type: 'tel',
                        id: 'phone',
                        name: 'phone',
                        required: false
                    },
                    label: 'Phone',
                    htmlFor: 'phone',
                    invalid: 'Please enter a propper phone number',
                    value: '',
                },
                validation: {
                    required: false,
                    minLength: 6,
                    maxLength: 30
                },
                valid: true,
                touched: false
            },
            message: {
                elementType: 'textarea',
                elementConfig: {
                    inputprops: {
                        type: 'textarea',
                        id: 'message',
                        name: 'message',
                        required: 'required',
                        rows: 4
                    },
                    label: 'Message',
                    htmlFor: 'message',
                    invalid: 'Please enter a message',
                    value: '',
                },
                validation: {
                    required: true,
                    minLength: 2,
                    maxLength: 500
                },
                valid: false,
                touched: false
            },
            compliance: {
                elementType: 'checkbox',
                containerClass: 'custom-control custom-checkbox',
                inputClass: 'custom-control-input',
                elementConfig: {
                    inputprops: {
                        type: 'checkbox',
                        id: 'gdpr',
                        name: 'gdpr',
                        required: 'required'
                    },
                    label: 'I consent to having this website store my submitted information so they can respond to my inquiry.',
                    htmlFor: 'gdpr',
                    invalid: 'Please give your consent before proceeding',
                    value: '',
                },
                validation: {
                    required: true,
                    isCheckbox: true,
                    isToggled: false
                },
                valid: false,
                touched: false
            }
        },
        formIsValid: false,
        loading: false,
        sent: false
    }

    contactHandler = ( event ) => {
        event.preventDefault();
        this.setState( { loading: true } );
        const formData = {}
        for (let formElementIdentifier in this.state.contactForm) {
            formData[formElementIdentifier] = this.state.contactForm[formElementIdentifier].elementConfig.value;
        }

        axios.post('/contacts.json', formData)
            .then(response => {
                this.setState({ loading: false, sent: true });
                console.log(formData);
            })
            .catch(error => {
                this.setState({ loading: false, sent: true });
                console.log(formData);
            });
    }

    inputChangedHandler = (event, inputIdentifier) => {
        const updatedContactForm = {
            ...this.state.contactForm
        };
        const updatedFormElement = {
            ...updatedContactForm[inputIdentifier]
        };
        updatedFormElement.elementConfig.value = event.target.value;
        updatedFormElement.valid = checkValidity(updatedFormElement.elementConfig.value, updatedFormElement.validation);
        updatedFormElement.touched = true;
        updatedFormElement.validation.isToggled = !updatedFormElement.validation.isToggled;

        updatedContactForm[inputIdentifier] = updatedFormElement;

        let formIsValid = true;
        for ( let inputIdentifier in updatedContactForm) {
            formIsValid = updatedContactForm[inputIdentifier].valid && formIsValid;
        }
        this.setState({contactForm: updatedContactForm, formIsValid: formIsValid});
    }

    render () {
        const formElementsArray = [];
        for (let key in this.state.contactForm) {
            formElementsArray.push({
                id: key,
                config: this.state.contactForm[key]
            });
        }

        let form = (
            <form onSubmit={this.contactHandler} name="contact">
                {formElementsArray.map(formElement =>(
                    <Input
                        key={formElement.id}
                        elementType={formElement.config.elementType}
                        containerClass={formElement.config.containerClass}
                        inputClass={formElement.config.inputClass}
                        elementConfig={formElement.config.elementConfig}
                        value={formElement.config.value}
                        invalid={!formElement.config.valid}
                        shoudValidate={formElement.config.validation}
                        touched={formElement.config.touched}
                        checked={formElement.config.validation.isToggled}
                        changed={(event) => this.inputChangedHandler(event, formElement.id)}
                        exited={(event) => this.inputChangedHandler(event, formElement.id)} />
                ))}
                <Button disabled={!this.state.formIsValid} />
            </form>
        );

        if (this.state.loading) {
            form = <Spinner />
        }

        if (this.state.sent) {
            form =
Thank you for your message.
 We will respond as soon as possible.

        }

        return (

Contact

                    {form}

        )
    }
};

export default ContactForm;

and this is my input.js component:
import React from 'react';
import { NavLink } from 'react-router-dom';

const input = ( props ) => {
    let label = {props.elementConfig.label};
    let inputElement = null;
    let errorlabel = null;
    let inputClass = ['input'];
    const errorid = [props.elementConfig.id];

    if(props.invalid && props.shoudValidate && props.touched) {
        inputClass.push('error');
    }

    switch (props.elementType) {
        case ('input'):
            inputElement = <input
                className ={inputClass.join(' ')}
                {...props.elementConfig.inputprops}
                value={props.elementConfig.value}
                onChange={props.changed}
                onBlur={props.exited} />;
            break;
        case ('email'):
            inputElement = <input
                className ={inputClass.join(' ')}
                {...props.elementConfig.inputprops}
                value={props.elementConfig.value}
                onChange={props.changed}
                onBlur={props.exited} />;
            break;
        case ( 'textarea' ):
            inputElement = <textarea
                className ={inputClass.join(' ')}
                {...props.elementConfig.inputprops}
                value={props.elementConfig.value}
                onChange={props.changed}
                onBlur={props.exited} />;
            break;
        case ( 'checkbox' ):
            inputElement = <input
                className ={[props.inputClass, inputClass.join(' ')].join(' ')}
                {...props.elementConfig.inputprops}
                value={!props.checked}
                onChange={props.changed} />;
            label = This form collects your name, e-mail, phone number, company name, and location so that we may correspond with you. Read our <NavLink to="/privacy" exact>privacy policy</NavLink> for more information. By submitting the form, you consent to have StackApp collect the listed information.;
            break;
        default:
            inputElement = <input
                className ={inputClass.join(' ')}
                {...props.elementConfig.inputprops}
                value={props.elementConfig.value}
                onChange={props.changed}
                onBlur={props.exited} />;
    }

    if(props.invalid && props.touched) {
        errorlabel = {props.elementConfig.invalid}
    };

    let output = null;
    if(props.elementType === 'checkbox') {
        output = [inputElement, label, errorlabel];
    } else {
        output = [label, inputElement, errorlabel];
    }

    return (

            {output}

    )
};

export default input;

What am I missing here?

A: Even though formElementsArray.map seems like the most likely candidate, it is not the source of the warning in this case. Like you mentioned in the comments, each of your keys is unique by construction. The error comes from input.js where you assign output = [inputElement, label, errorlabel] then render {output} directly. React sees that this is an array, but doesn't know that it is of fixed size and expects each element in the array to have a unique key prop. If you put a key prop on inputElement, label, and errorLabel the warning should go away.


text:
Q: Python String function Looking to put together a simple python function that checks the following
Given two strings, return True if either of the strings appears at the very end of the other string,
ignoring upper/lower case differences (in other words, the computation should not be "case
sensitive").
end_other('Hiabc', 'abc') → True
end_other('AbC', 'HiaBc') → True
end_other('abc', 'abXabc') → True

A: Try with
def end_other(s1, s2):
    s1 = s1.lower()
    s2 = s2.lower()
    return s1.endswith(s2) or s2.endswith(s1)

A: You can use regex
def end_other(s1,s2):
    return bool(re.search(s1+'$',s2,re.I)) or bool(re.search(s2+'$',s1,re.I))

A: Or if you need to "create" your own function:
def check(str1, str2):
    str1 = str1.lower()
    str2 = str2.lower()
    check = True

    # If string 1 is bigger then string 2:
    if( len(str1) > len(str2) ):
        # For each character of string 2
        for i in range(len(str2)):
            # Compare the character i of string 2 with the character at the end of string 1, keeping the order
            if str2[i] != str1[-(len(str2)-i)]:
            check = False

    # If string 2 is bigger then string 1:
    else:
        # For each character of string 1
        for i in range(len(str1)):
            # Compare the character i of string 1 with the character at the end of string 2, keeping the order
            if str1[i] != str2[-(len(str1)-i)]:
                check = False
    return check

So, basically, if string1 = "ABCD" and string2 = "CD", it will check character 0 of string2 with 2 of string1 and 1 of string2 with 3 of string1

A: Here's another approach using zip, which avoids having to do multiple passes of endswith(), re.search() or slicing. It iterates the 2 strings in reverse and returns True if all the letters are equal up to the exhaustion of one of the strings:
def end_other(s1, s2):
    return all(a == b for a, b in zip(reversed(s1.lower()), reversed(s2.lower())))

In Python2 you can use itertools.izip() for a marginal space improvement:
>>> end_other('Hiabc', 'abc')
True
>>> end_other('AbC', 'HiaBc')
True
>>> end_other('abc', 'abXabc')
True
>>> end_other('cbc', 'abXabc')
False

A: You could use slicing.
>>> s1 = "Hiabc"
>>> s2 = "abc"
>>> l = len(s2)
>>> s2 == s1[-l:]
True
>>> s2 = "aBc"
>>> s2 == s1[-l:]
False

You can read more about string and slicing here.
Slicing means to get part of the string based on passed index. General construction look like this: string[starting_index:ending_index].
Let's take a look at this:
string1 = "doggy"
string1[0:1] -> "d"
string1[0:2] -> "do"
string1[0:] = string[:] = "doggy" (from zero to end)
You can also pass index lesser than 0:
string1[-1:] (from -1 to end) -> "y"
So in the code above calling s1[-l:] means starting position is the length of s2 sentece. In this case s1[-l:] = 'abc' = s1[-3:]. Because lenght of s2 is 3.

A: You can use OOP if you want, subclassing str and writing an appropriate method:
>>> class String(str):
...     def isend(self, other):
...             self = self.lower()
...             other = other.lower()
...             return self.endswith(other) or other.endswith(self)
...
>>> a = String('HiAbC')
>>> b = String('Bc')
>>> a.isend(b)
True
>>> b.isend(a)
True
>>> c = String('Hello')
>>> d = String('el')
>>> c.isend(d)
False
>>> d.isend(c)
False


text:
Q: classList.add() is not activated immediately in clicked event

function highlight1(){
  document.getElementById("div1").classList.add("red");
}
function highlight2(){
  document.getElementById("div2").classList.add("red");
}
function highlight3(){
  document.getElementById("div3").classList.add("red");
}
div{
  display: inline-block;
  border: 1px solid black;
  height: 100px;
  width: 100px;
}
div:hover{
  background: yellow;
}
.red{
  background: red;
}

Division

Division

Division

I'm new to CSS and I have two questions for the code.

*

*(1) When I click the divs, they are not turning red until I move the
pointer outside of the divs? What is the reason? How can I make it
highlighted immediately?

*(2) How can I just highlight the div of
three that I clicked? I only want to highlight one div at the same
time.

A: Your :hover is making hovered divs, even .red divs, appear hovered (yellow) instead of red. You could make hovered .red divs red as well if you wanted.
If you only want one to be red at a time, you can remove .red from all divs before using classList.add.
It would also be more appropriate to use classes than individual ids, because the elements are part of a collection rather than being unique in some way:

const divs = document.querySelectorAll('.box');
function reset(i) {
  divs.forEach(div => div.classList.remove("red"));
  divs[i].classList.add('red');
}
.box {
  display: inline-block;
  border: 1px solid black;
  height: 100px;
  width: 100px;
}

.box:hover {
  background: yellow;
}

.red,
.red:hover {
  background: red;
}

Division

Division

Division

A: You can do this by applying, div.red:hover by doing this you are actually overriding div:hover with div.red:hover prioritizing div.red:hover

function highlight1(){
  document.getElementById("div1").classList.add("red");
}
function highlight2(){
  document.getElementById("div2").classList.add("red");
}
function highlight3(){
  document.getElementById("div3").classList.add("red");
}
div{
  display: inline-block;
  border: 1px solid black;
  height: 100px;
  width: 100px;
}
div:hover{
  background: yellow;
}
div.red:hover,.red{
  background: red;
}

Division

Division

Division


text:
Q: chkdsk doesn't repair the file system corruption I have, now what? Operating system is Windows XP w/SP3. While running Paragon Disk Wiper, to clean the unused portion of my system partition of garbage, it belches and comes up with this error "Incorrect dir structure - Errors in dir tree" CHKDSK should be used to correct.
I run CHKDSK /r and it does some repairs, but not all. After running it the second time I still end up with CHKDSK telling me "CHKDSK discovered free space marked as allocated in the Master File Table (MFT) Bitmap. Correcting errors in the volume bitmap. Windows found problems with the File System". I run CHKDSK a third time and it does no further repairs.
All of this is way above my pay grade. I have no clue where to go from here. Any suggestions on fixing this problem would be greatly appreciated.
I should note that I noticed nothing unusual lately the way the system was running. Not one single problem I could put my finger on.
EDIT: Okay, if I do an image backup of the C:/ & D:/ partitions on this drive, should I delete the D:/ partition so it's all one drive again, before I go ahead with the format? Then re-partition the drive again after restoring the image? Will the restored images be error free or am I just backing up the errors too?

A: It appears as if your file system is corrupt and you might have to completely erase your hard drive and re-partition it (after you backup your data, of course).
I have heard of cases where people have been booting into (XP) recovery mode, running CHKDSK from there, boot into the computer and repeat that cycle about 100 times and it eventually 'fixed' the problems, but all this sounds like a lot of hassle.
I strongly suggest you re-partition your whole hard drive again to remove any of these errors.

A: I agree with joshhunt. It sounds like the filesystem is hosed to the point where you might not want to repair it and continue.
However, I would add that before using that exact same hard drive again, it should be thoroughly checked for errors using a diagnostic utility. There's no point in re-partitioning and re-formatting the hard drive if the hard drive itself is unreliable.  It could have caused the filesystem corruption in the first place.
Most hard drive manufacturers have diagnostic utilities freely available for download, such as Western Digital's Data Lifeguard Diagnostics tool.  Find one appropriate to your hard drive.
Another tool I particularly like that works with most hard drives is Steve Gibson's SpinRite. It's not free, but it's great at surface defect detection.  On the other hand, it's $89.00 price exceeds the cost of a new hard drive.  I bought it because I troubleshoot failing systems relatively frequently.

A: If you still can't seem to find an answer to this issue, try reading from this site about chkdsk errors. It specifically addresses common questions related to chkdsk, including ways to troubleshoot them.

A: Depending on what you mean by an "image" backup, you can easily preserve all the filesystem errors and reinstall them, yes.
Why chkdsk /r instead of /f?


text:
Q: How to sort my array of objects based on firebase Timestamp I need my messages should be ordered based on timestamp ("createdAt" is the name of filed) i can do it in earlier versions of firebase but cant fig out how to do it in firebase v9
DATA STRUCTURE ON FIRESTORE

const [messages, setMessages] = useState([])
    useEffect(() => {

        const unsub = onSnapshot(doc(db, "messages", state.id), (snapshot) => {
            if(snapshot.data()){
                console.log(123,Object.values(snapshot.data()))
                setMessages(Object.values(snapshot.data()))
            }
        });
    }, [])

A: What you have in your document is not an array. They are just fields with random IDs. You can sort them using .sort() as shown below:
if (snapshot.data()) {
  const sortedMessages = Object.values(snapshot.data()).sort((a, b) => a.createdAt.toMillis() - b.createdAt.toMillis())

  setMessages(sortedMessages);
}


text:
Q: weird result when parsing XML document using php I am attempting to use PHP to parse an XML document.  It is basically working except I am getting a very weird error that I do not see a reason for.  The XML for the first ASIN is this:
    <?xml version="1.0"?>
<GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetLowestOfferListingsForASINResult ASIN="1580230032" status="Success">
<AllOfferListingsConsidered>true</AllOfferListingsConsidered>
<Product xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Identifiers>
  <MarketplaceASIN>
    <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
    <ASIN>1580230032</ASIN>
  </MarketplaceASIN>
</Identifiers>
<LowestOfferListings>
  <LowestOfferListing>
    <Qualifiers>
      <ItemCondition>New</ItemCondition>
      <ItemSubcondition>New</ItemSubcondition>
      <FulfillmentChannel>Merchant</FulfillmentChannel>
      <ShipsDomestically>True</ShipsDomestically>
      <ShippingTime>
        <Max>0-2 days</Max>
      </ShippingTime>
      <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
    </Qualifiers>
    <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
    <SellerFeedbackCount>221</SellerFeedbackCount>
    <Price>
      <LandedPrice>
        <CurrencyCode>USD</CurrencyCode>
        <Amount>10.12</Amount>
      </LandedPrice>
      <ListingPrice>
        <CurrencyCode>USD</CurrencyCode>
        <Amount>6.13</Amount>
      </ListingPrice>

and the XML for the second ASIN is:
    <GetLowestOfferListingsForASINResult ASIN="0870714376" status="Success">
  <AllOfferListingsConsidered>true</AllOfferListingsConsidered>
  <Product xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Identifiers>
  <MarketplaceASIN>
    <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
    <ASIN>0870714376</ASIN>
  </MarketplaceASIN>
</Identifiers>
<LowestOfferListings>
  <LowestOfferListing>
    <Qualifiers>
      <ItemCondition>New</ItemCondition>
      <ItemSubcondition>New</ItemSubcondition>
      <FulfillmentChannel>Merchant</FulfillmentChannel>
      <ShipsDomestically>True</ShipsDomestically>
      <ShippingTime>
        <Max>0-2 days</Max>
      </ShippingTime>
      <SellerPositiveFeedbackRating>98-100%</SellerPositiveFeedbackRating>
    </Qualifiers>
    <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
    <SellerFeedbackCount>1416</SellerFeedbackCount>
    <Price>
      <LandedPrice>
        <CurrencyCode>USD</CurrencyCode>
        <Amount>18.49</Amount>
      </LandedPrice>
      <ListingPrice>
        <CurrencyCode>USD</CurrencyCode>
        <Amount>14.50</Amount>
      </ListingPrice>

As you can see, the Amount for each of these is different, yet when I run the program I am only getting the Amount from the first ASIN.  Here is my PHP code to get the results:
    $parsed_xml = amazon_xml($isbn);

$current = $parsed_xml->ListMatchingProductsResult->Products->Product;
$asin = $current->Identifiers->MarketplaceASIN->ASIN;

// get information based on the items ASIN
$price_xml = amazonPrice_xml($asin, $ItemCondition);
$currentPrice = $price_xml ->GetLowestOfferListingsForASINResult->Product->LowestOfferListings->LowestOfferListing;

// check to see if there are values
if(!empty($currentPrice))
{

    foreach($currentPrice as $offer){
            $totalFeedback = $offer->SellerFeedbackCount;
        //if ($totalFeedback >99) {
            $condition = $offer->Qualifiers->ItemSubcondition;

                //amazon condition matching algorithm (so we can match our condition up against amazons conditions)
                switch ($condition) {
                case "New":
                    $amazonCondition = 5;
                    break;
                case "Mint":
                    $amazonCondition = 4;
                    break;
                case "VeryGood":
                    $amazonCondition = 3;
                    break;
                case "Good":
                    $amazonCondition = 2;
                    break;
                case "Acceptable":
                    $amazonCondition = 1;
                    break;
                default:
                    $amazonCondition = 0;
                }

            $lowestAmazonPrice = 0;

                            $currentPrice = $price_xml ->GetLowestOfferListingsForASINResult->Product->LowestOfferListings;
             foreach($currentPrice->LowestOfferListing as $offer){
                                if( ($ourCondition = $amazonCondition) /*&& ($totalFeedback >= 5000)*/) {
                    $offerArray[$y] = str_replace('$','',$offer->Price->ListingPrice->Amount);
                    $y++;
                                }
            }
            $lowestAmazonPrice = min($offerArray);
    }

                    if ($fillzPrice > $lowestAmazonPrice ) {
                        $avgPrice = ($lowestAmazonPrice - ($lowestAmazonPrice * .08));
                         $source = "Adjusted Fillz Price";
                    } else {
                        $avgPrice = $fillzPrice;
                        $source = "Original Price";
                    }
    // check to make sure we are not going below established floor for prices
            if($avgPrice < ($follettPrice * 2.37)){
        $avgPrice = $follettPrice * 2.37;
        $source = "Follett Pricing";
    }
    if($avgPrice < ($row['cost'] * 2)){
        $avgPrice = $row['cost'] * 2;
        $source = "Double Cost";
    }
    /*if($avgPrice < 5.50){
        $avgPrice = 5.50;
        $source = "Lowest Base Cost";
    }*/
            //update fillzPrice
    $conn->query("UPDATE inventory SET ourPrice = $avgPrice, upload = '1' WHERE sku=" . $row['sku']);

    $pricedSKU[$n] = array('sku' => $row['sku'],
                            'new price' => number_format($avgPrice, 2, '.', ''),
                            'price source' => $source,
                                                            'Fillz' => $fillzPrice,
                                                            'Amazon'=> $lowestAmazonPrice,
                                                            'asin'=> $asin,
                                                            'condition'=>$ourCondition
                            );

    $n++;

}

}

As I stated earlier, most of the output is correct with the exception of this issue.  I have an email sent to me with the ASIN and amounts so I can check the results.  Any thoughts onbn what I am doing wrong and how to correct it?

A: In case anyone else has this issue, the resolution was to add this line of code:
 $offerArray = array();

in after the first while statement.  Everything works fine now.


text:
Q: JQuery Autocomplete Display Error MSG if No Result i found this piece of code somewhere on the net and adapted it to my needs.
hi, may be the rest of my code will help clarify it:
index.php >

DBLookUp <input id="autocomplete" type="text"  />

searchdb.js >
//autocomplete function
        $(document).ready(function(){
            $("#autocomplete").keyup(function()
            {
                $("#showresults").show();
                var dbsearch;
                dbsearch = $("#autocomplete").val();

                if (dbsearch.length > 0)
                {
                    $.ajax(
                    {
                        type: "POST",
                        url: "autocomplete.php",
                        data: "dbsearch=" + dbsearch,
                        success: function(message)
                        {
                            $("#showresults").empty();
                            if (message.length > 0) {
                    $("#showresults").append(message);
                } else {
                    $("#showresults").append("No Results found!");
                }
                        }
                    });
                }
                else
                {
                    // if empty
                    $("#showresults").empty();
                }
            });
        });

//end of autocomplete function
        function selectItem(id,value)
        {
            document.getElementById("autocomplete").value=value;
            autocomplete(id,value);
        }

autocomplete.php >
<?php
require_once("searchdb.php");
$dbsearch = strtolower(mysql_real_escape_string(strip_tags($_POST['dbsearch'])));
$autocompl=new DBQUERY();
$autocompl->autocomplete($dbsearch);
?>

searchdb.php >
<?php
class DBQUERY {

private $dbh;

public function __construct() {
    $this->dbh = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
}

public function autocomplete($dbsearch)
{

  $cons = $this->dbh->prepare("select * from  clients  where  cl_name like :dbsearch");

                    $cons->execute(array(':dbsearch' => '%'.$dbsearch.'%'));
                    while($dbrow = $cons->fetch())
        {
        $data=$dbrow["cl_name"];$id=$dbrow["cli_id"];

                    echo "".$data."
";
                    }
                  ?>

<?php
    }
//end autocomplete
}
?>

it works great, but i cant make it show the "no results found!" message.
i think the else-clause is overwritten by the if-statement, which starts to works as soon as it detects input. ( ...if (dbsearch.length > 0)... )
but since im new to jquery i cant seem to figure out where to change the script so that it works correctly.

A: Maybe you should check the $cons:
public function autocomplete($dbsearch) {
    $cons = $this - > dbh - > prepare("select * from  clients  where  cl_name like :dbsearch");

    $cons - > execute(array(':dbsearch' = > '%' .$dbsearch. '%'));

    if (count($cons) > 0) {
        while ($dbrow = $cons - > fetch()) {
            $data = $dbrow["cl_name"];
            $id = $dbrow["cli_id"];

            echo "".$data."
";
        } ?>
    } else {
        $data = '';
    }

<?php
    }
// end autocomplete
} ?>

A: maybe also this might work:
if (message.trim() != "") {
    //message = message; <-- not needed..
    $("#showresults").append(message);
}else{
    //message = "No Results found!"; <-- also not needed..
    $("#showresults").html("No Results found!");
}

You have to return empty string form your php...
And also, this shouldnt be there...

put this in the document not in php like this:
   //autocomplete function
    $(document).ready(function(){
        $("#showresults").on("click", ".resultsdb", function(){
            $("#showresults").hide();
        });

        $("#autocomplete").keyup(function()
        //....


text:
Q: How to upload large files to a 99designs/gqlgen backend I want to upload large files to my backend which I created with gqlgen.
To do that, I want to use multipart requests to keep only one endpoint.
(Client implementation e.g. apollo-upload-client)
There is an example and documentation on how to upload files using gqlgen using multipart requests. However, this only works for small files. When I try to upload large files (only 500mb in this case) I get a connection reset error. (I get the same error in my implementation and the example gqlgen provided)
Does anyone know a solution for this?


text:
Q: Passing a GWT Widget to a js function I want to pass a complex widget with many click handlers to a js function, via jsni, so that it is included in a div element of my js code (in fact it's for the infoWindow content of the maps v3 api).
If I pass the element I loose all my handlers, for some reason. The result is that nothing is triggered when I click on buttons or links.
I thought I could sort it out by first passing a flowpanel and its node and then adding the widget to the flowpanel itslef. But it works sometimes and some times not, in particular not with the infoWindow. The widget appears fine but all handlers won't work.
Please send me any suggestions or ideas you might have!

A: OK I got the trick from... stackoverflow, suprise ;-)
Here's the post:
http://www.google.com/url?sa=D&q=https://stackoverflow.com/questions/6183181/how-to-add-a-custom-widget-to-an-element
So in the end I did the following
in my jsni function:
            var newDiv = $doc.createElement('div');

the function returns the div as an Element which I in turn wrap in an HTMLPanel using HTMLPanel.wrap and then I add the widget!


text:
Q: How can I resolve a "NameError: name 'null' is not defined" error while trying to import any module in Python 2.7 I installed python today and used pip install successfully to get some modules. But I am unable to import any .py modules.
I created mod.py (it has a simple print command) in the same directory as the code I am trying to run. I uninstalled and reinstalled anaconda as well. But the error persists.
Anyone with any ideas on how to fix this?
Thanks!
import mod

NameErrorTraceback (most recent call last)
<ipython-input-1-18de99490651> in <module>()
----> 1 import mod

C:\Users\Mayank\mod.py in <module>()
      3   {
      4    "cell_type": "code",
----> 5    "execution_count": null,
      6    "metadata": {},
      7    "outputs": [],

NameError: name 'null' is not defined

This is a sample of what the .py code looks like in the editor (same problem):
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib(n):    # write Fibonacci series up to n\n",
    "    a, b = 0, 1\n",
    "    while b < n:\n",
    "        print b,\n",
    "        a, b = b, a+b\n",
    "\n",
    "def fib2(n):   # return Fibonacci series up to n\n",
    "    result = []\n",
    "    a, b = 0, 1\n",
    "    while b < n:\n",
    "        result.append(b)\n",
    "        a, b = b, a+b\n",
    "    return result"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}

A: I figured out the issue. I was doing 'Save As' mod.py for the code I was writing. Instead, I needed to 'Save As 'mod' and then 'Download As' .py file type. This was only an issue due to the way the module file is saved/created in Jupyter. The responses to my question yesterday were helpful in me to figure this out. Thanks, everyone!

A: null is not pre-defined in Python. You may have gotten it by copying and pasting a JSON object. Use None in place of null to denote null objects.

A: I think the problem was that your original saved file was not in python format. I was having the same problem as when I saved from Jupytr. The file had an extension
.ipynb which is a python notebook format.
To convert the .ipynb to a .py (which is a text file) I ran the following command in the terminal window:
 $ jupyter nbconvert --to script mynotebook.ipynb

This created a file "mynotebook.py" which I could then run using
$ python mynotebook.py

in the terminal window.

A: I had this issue just remaining the ipynb file to .py. What worked for me is to just copy the script from the ipynb file to a new empty .py file.

A: null isn't a reserved word like it is in JavaScript. None is used.

A: That is code from a Jupyter notebook, which is stored in JSON format and cannot be run directly by Python. To fix it, remove everything that doesn't correspond to the 'source' attribute.

A: I fixed this by running every cell at least one time, so    "execution_count": is changed to 1. Then save .py file.


text:
Q: How to get FX Forward Rates instead of Points in BLPAPI in Python I am trying to get "CHF1M Curncy" as Forward Rates and not as points from Bloomberg API BLPAPI in Python. The Code itself works fine for the Forward Points, but as soon as I use the override to switch from Points to Rates, I get an error "No value for []" for the line with the first override. This is my code:
import blpapi
import json

HISTORICAL_DATA_RESPONSE = blpapi.Name("HistoricalDataResponse")

def historical_bloomberg_data(securities, fields, periodicity="DAILY", start_date="20190101", end_date="20190105"):

    # Create and start a session
    print("Creating session ...")

    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost('localhost')
    sessionOptions.setServerPort(8194)

    session = blpapi.Session(sessionOptions)

    if not session.start():
        print("Failed to start session")
        return

    try:
        # Create and open a service
        print("Creating historical data service")

        if not session.openService("//blp/refdata"):
            print("Failed to create service")
            return

        refDataService = session.getService("//blp/refdata")
        request = refDataService.createRequest("HistoricalDataRequest")

        # Add all securities
        for security in securities:
            request.getElement("securities").appendValue(security)

        # Add all fields
        for field in fields:
            request.getElement("fields").appendValue(field)

        # Further settings
        request.set("periodicitySelection", periodicity)
        request.set("startDate", start_date)

        request.set("endDate", end_date)
        request.set("maxDataPoints", 2000)

        #Override code
        overrides = request.getElement('overrides')
        override1 = overrides.appendElement()
        override1.setElement('fieldID', 'FWD_CURVE_FORMAT')
        override1.setElement('value', 'RATES')
        #request.setOverride("FWD_CURVE_FORMAT", "RATES")

        # Send and process request
        print("Sending request...")
        session.sendRequest(request)

        results = {}

        while True:
            ev = session.nextEvent(500)
            for msg in ev:
                if msg.messageType() == HISTORICAL_DATA_RESPONSE:
                    #response = msg.getElement()
                    response = msg.getElement("securityData")
                    _sec = response.getElementAsString("security")
                    _data = [[fd.getElementAsString("date")] + [fd.getElementAsString(_) for _ in fields] for fd in response.getElement("fieldData").values()]

                    results[_sec] = results.get(_sec, []) + _data

            if ev.eventType() == blpapi.Event.RESPONSE:
                break

        print("Results retrieved")
        return results

A: The correct override is FWD_CURVE_QUOTE_FORMAT. The values can be:

*

*POINTS

*RATES

*OUTRIGHT
(I suspect OUTRIGHT and RATES do the same thing)
EDIT
And the correct way to override a field is by using fieldId (ending with a small cap d) and not fieldID.


text:
Q: How to change vimtex highlight colors for matching delimiters? I've installed vimtex and have enabled highlighting of matching delimiters, but it's a bit painful to see the highlighted part. How can I change the highlight color?

A: This can be changed using the MatchParen highlighting group, for example:
:hi MatchParen ctermbg=5


text:
Q: VirtualHost / httpd not accepting absolute paths In my previous question, SSL certificates weren't working for me, until I got it to work using relative paths rather than absolute.
Question: Why won't my VirtualHost/httpd not accept absolute paths? Is there some configuration or something?
My VirtualHost (non-working);
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    RewriteEngine on
    RewriteRule ^/?(.*) https://example.com/$1 [R,L]
</VirtualHost>
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/msdfw
    ErrorLog /var/iwww/logs/e-msdfw
    CustomLog /var/iwww/logs/c-msdfw combined
    DirectoryIndex index.php
    SSLEngine on
    SSLCertificateFile /var/iwww/certs/msdfw/c.pem
    SSLCertificateKeyFile /var/iwww/certs/msdfw/p.key
    SSLCertificateChainFile /var/iwww/certs/msdfw/b.pem
    <Directory /var/www/msdfw/>
            Require all granted
    </Directory>
</VirtualHost>

Error Log:
Sep 26 17:00:11 localhost systemd[1]: Starting The Apache HTTP Server...
-- Subject: Unit httpd.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has begun starting up.
Sep 26 17:00:11 localhost httpd[5579]: AH00526: Syntax error on line 15 of
/etc/httpd/enabled/msdfw.conf:
Sep 26 17:00:11 localhost httpd[5579]: SSLCertificateFile: file
'/var/iwww/certs/msdfw/c.pem' does not exist or is empty
Sep 26 17:00:11 localhost systemd[1]: httpd.service: main process exited,
code=exited, status=1/FAILURE
Sep 26 17:00:11 localhost kill[5581]: kill: cannot find process ""
Sep 26 17:00:11 localhost systemd[1]: httpd.service: control process exited,
code=exited status=1
Sep 26 17:00:11 localhost systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit httpd.service has failed.
--
-- The result is failed.
Sep 26 17:00:11 localhost systemd[1]: Unit httpd.service entered failed state.
Sep 26 17:00:11 localhost systemd[1]: httpd.service failed.

VirtualHost (working):
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    RewriteEngine on
    RewriteRule ^/?(.*) https://example.com/$1 [R,L]
</VirtualHost>
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/msdfw
    ErrorLog /var/iwww/logs/e-msdfw
    CustomLog /var/iwww/logs/c-msdfw combined
    DirectoryIndex index.php
    SSLEngine on
    SSLCertificateFile /etc/httpd/certs/msdfw/c.pem
    SSLCertificateKeyFile /etc/httpd/certs/msdfw/p.key
    SSLCertificateChainFile /etc/httpd/certs/msdfw/b.pem
    <Directory /var/www/msdfw/>
            Require all granted
    </Directory>
</VirtualHost>

I had to move the folder containing the certificates to the httpd folder (relative) in order for it to work? Anyone know why and how I can make it accept absolute paths? Thanks!

A: No, you can specify absolute paths from anywhere as long as httpd can reach them (with root)
The only rule that applies to httpd regarding configuration is relative paths are relative to ServerRoot path, but if you specify absolute paths they can point anywhere in the filesystem you specify.
So double-check the previous paths and that the files were there, or that SELinux or similar is not getting in the way.


text:
Q: SwiftUI set state variables through another view instance In SwiftUI I've created a struct that should create different overlay views depending on some state variables. If any of the state booleans is true, then it should return custom view (either ErrorOverlay or LoadingOverlay or else an EmptyView) like this:
struct OverlayContainer: View {
    @State var isLoading: Bool = false
    @State var isErrorShown: Bool = false

    func setIsLoading(isLoading: Bool) {
        self.isLoading = isLoading
    }

    func setIsErrorShown(isErrorShown: Bool) {
        self.isErrorShown = isErrorShown
    }

    var body: some View {
        Group {
            if(isErrorShown) {
                ErrorOverlay()
            }
            else if(isLoading) {
                LoadingOverlay()
            }
            else {
                EmptyView()
            }
        }
    }
}

Now I've implemented the overlay on some content in the Home view with buttons that should change the state and show the correct overlay, like this:
struct Home: View {

    var body: some View {
        let overlayContainer = OverlayContainer()

        return HStack {
            // Some more content here

            Button(action: {
                overlayContainer.setIsLoading(isLoading: true)
            }) {
               Text("Start loading")
            }
            Button(action: {
                overlayContainer.setIsErrorShown(isErrorShown: true)
            }) {
               Text("Show error")
            }
        }.overlay(overlayContainer)
    }
}

This isn't working: when I click the button nothing happens. Why and how to solve this? (without using binding, see below)

ps. I've been able to get a working solution by doing the following:

*

*extracting the state booleans to the Home view

*pass these through the constructor of the OverlayContainer

*change the state booleans instead of calling the set methods when clicking the buttons

*change the OverlayContainer so it implements an init method with both booleans

*change the state booleans in the OverlayContainer to bindings.

However, I'd like to implement the states in the OverlayContainer to be able to re-use that in different screens, without implementing state variables in all of these screens. Firstly because there will probably be more cases than just these 2. Secondly because not all screens will need to access all states and I haven't found out a simple way to implement optional bindings through the init method.
To me it feels that all these states belong to the OverlayContainer, and changing the state should be as short and clean as possible. Defining states everywhere feels like code duplication. Maybe I need a completely different architecture?

A: It should be used Binding instead. Here is possible solution.
struct OverlayContainer: View {
    @Binding var isLoading: Bool
    @Binding var isErrorShown: Bool

    var body: some View {
        Group {
            if(isErrorShown) {
                ErrorOverlay()
            }
            else if(isLoading) {
                LoadingOverlay()
            }
            else {
                EmptyView()
            }
        }
    }
}

struct Home: View {
    @State var isLoading: Bool = false
    @State var isErrorShown: Bool = false

    var body: some View {
        HStack {
            // Some more content here

            Button(action: {
                self.isLoading = true
            }) {
               Text("Start loading")
            }
            Button(action: {
                self.isErrorShown = true
            }) {
               Text("Show error")
            }
        }.overlay(OverlayContainer(isLoading: $isLoading, isErrorShown: $isErrorShown))
    }
}

A: To make it the way you want, use Binding:
struct OverlayContainer: View {

    @Binding var isLoading: Bool
    @Binding var isErrorShown: Bool

    func setIsLoading(isLoading: Bool) {
        self.isLoading = isLoading
        self.isErrorShown = !isLoading
    }

    func setIsErrorShown(isErrorShown: Bool) {
        self.isErrorShown = isErrorShown
        self.isLoading = !isErrorShown
    }

    var body: some View {
        Group {
            if(isErrorShown) {
                ErrorOverlay()
            }
            else if(isLoading) {
                LoadingOverlay()
            }
            else {
                EmptyView()
            }
        }
    }
}

struct Home: View {

    @State var isLoading = false
    @State var isErrorShown = false

    var body: some View {

        let overlayContainer = OverlayContainer(isLoading: $isLoading, isErrorShown: $isErrorShown)

        return HStack {
            // Some more content here

            Button(action: {
                overlayContainer.setIsLoading(isLoading: true)

            }) {
                Text("Start loading")
            }
            Button(action: {
                overlayContainer.setIsErrorShown(isErrorShown: true)
            }) {
                Text("Show error")
            }
        }.overlay(overlayContainer)
    }
}


text:
Q: Как считать данные из файла в модель данных? Каждые 10 строк в файле повторяется структура данных, например:
name1
name2
name3
.....
name10

name1
name2
name3
.....
name10

Необходимо считать данные в модель. Я читаю так:
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
        Data data= new Data();
        String[] strings = TextUtils.split(line, " ");
            for(int i=0;i<11;i++){
                myApplication.setDataValue1(strings[0].trim);
                myApplication.setDataValue2(strings[1].trim);
                myApplication.setDataValue3(strings[2].trim);
                ...
            }
        data.setData(myApplication.getDataValue);
        }
        br.close();
    }
catch (IOException e) {
}

Но таким образом считывается совсем не то, что мне бы хотелось. В чём ошибка?

A: Мне кажется следующая строка лишняя.
String[] strings = TextUtils.split(line, " ");

Ведь ваш файл считывается построчно. И в каждой line будет соответствующее name.
Попробуйте сделать что-то вроде:
int j = 0;
String [] strings = new String [11];

while ((line = br.readLine()) != null) {
    strings[j % 11] = line;
    j++;
    if (j % 11 == 0) {
        myApplication.setDataValue1(strings[0].trim);
        myApplication.setDataValue2(strings[1].trim);
        ...
        myApplication.setDataValue2(strings[9].trim);
        data.setData(myApplication.getDataValue());
    }
}

Хотя смысл последней команды мне непонятен (getDataValue - это что метод или поле).
Подозреваю, что мое решение не совсем в точку, но если вы предоставите больше информации - класс myApplication, Data, то можно будет помочь вам более точно.

A: *

*Попробуйте сначала прочитать весь файл в одну строку.

*Потом порезать строку на массив с разделителем в два переноса строки \n\n

*Теперь осталось порезать каждую ячейку массива по разделителю в один перенос строки \n

A: Добавлю своего исходничка:
try {
    // Конструкция, авто закрытие файла
    try(FileInputStream file = new FileInputStream("test")){
        // Если в файле байтов хотя бы 1
        if(file.available() > 0){
            // Буфер, первоначальное количество 10 байт
            ByteArrayOutputStream out = new ByteArrayOutputStream(10);
                int a = -1;
                while(true){
                    a = file.read();  // Читаем поток
                    // -1 конец (всё, в файле ничего нету)
                    if(a == -1) break;
                    // 10 это \n
                    if(a == 10){
                        // Пишу считанную строку, что с ней еще делать...
                        System.out.println(out.toString());

                        out.reset(); // Чистим буфер
                        continue;
                    }
                    out.write(a); // Пишем считанный байт в буфер
                }
            }
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
catch (IOException ex) {
    ex.printStackTrace();
}

P.S. (Buffered)Reader не советую: памяти скушает очень много (а если файл огромный, то еще больше). Если надо - могу сделать работу trim на лету, не используя trim().


text:
Q: Call R function from Rcpp which returns List leads to error during compilation I'm trying to use the stats::constrOptim function inside of Rcpp Code and I'm only interested in the par object of the returned list.
This is what it looks like in R.
Rcpp::sourceCpp("development/batch_reprex.cpp")

A <- matrix(1:6, ncol = 2)
weights <- c(0.5, 0.5)
pred <- A %*% weights
truth <- c(3, 3, 3)

# Optim constraints:
positivity <- diag(ncol(A))
convexity <- rep(1, ncol(A))
constr_left <- rbind(convexity, positivity)
constr_right <- c(1, rep(0, ncol(A)))

constrOptim(weights,
    subject_function,
    grad = NULL,
    ui = constr_left,
    ci = constr_right - 1e-12, # see https://stackoverflow.com/a/50474095
    method = "Nelder-Mead",
    predictions = A,
    truth = truth
)$par

I just want to do this last call inside of an RCPP function. This is what my batch_reprex.cpp looks like:
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(RcppProgress)]]
#define RCPP_ARMADILLO_RETURN_VEC_AS_VECTOR
#include <RcppArmadillo.h>
#include <string>
#include <progress.hpp>
using namespace arma;

// [[Rcpp::export]]
double subject_function(const vec &weights,
                        const mat &predictions,
                        const vec &truth)
{
    vec pred = predictions * weights;
    vec loss_vec = arma::pow(pred - truth, 2);
    return arma::mean(loss_vec);
}

// [[Rcpp::export]]
SEXP constr_optim_rcpp(const vec &weights,
                       const mat &predictions,
                       const vec &truth,
                       const mat &ui,
                       const vec &ci)
{
    Rcpp::Environment pkg = Rcpp::Environment::namespace_env("stats");

    Rcpp::Function f = pkg["constrOptim"];

    return f(weights,
             subject_function,
             Rcpp::Named("grad", NULL),
             Rcpp::Named("ui", ui),
             Rcpp::Named("ci", ci),
             Rcpp::Named("method", "Nelder-Mead"),
             Rcpp::Named("predictions", predictions),
             Rcpp::Named("truth", truth));
}

Running sourceCpp returns a lot of error messages including:
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/traits/is_convertible.h:35:12: error: function returning a function
   35 |   static T MakeT() ;
      |            ^~~~~

Thank you so much in advance.
Edit:
I figured out that the problem has something todo with the fact that I'm passing the Rcpp subject_function to constrOptim. When I pass an R function, everything works fine:
// [[Rcpp::export]]
Rcpp::List constr_optim_rcpp(const vec &weights,
                             const mat &predictions,
                             const vec &truth,
                             const mat &ui,
                             const vec &ci)
{
    Rcpp::Environment pkg_base = Rcpp::Environment::namespace_env("base");
    Rcpp::Function f_sum = pkg_base["sum"];
    Rcpp::Environment pkg = Rcpp::Environment::namespace_env("stats");
    Rcpp::Function f = pkg["constrOptim"];
    Rcpp::List res = Rcpp::List::create(f(weights,
                                          f_sum,
                                          R_NilValue,
                                          ui,
                                          ci,
                                          Rcpp::Named("predictions", predictions),
                                          Rcpp::Named("truth", truth)));

    return res;
}


text:
Q: Criteria for being an $\infty$-category? Let $\mathcal{C}$ be a simplicial category, such that for any two objects $X, Y\in\mathcal{C}$, $\text{Hom}_{\mathcal{C}}(X,Y)$ is a simplicial commutative monoid. Is the simplicial nerve $\text{N}(\mathcal{C})$ an $(\infty, 1)$-category?
If for any two objects $X,Y\in \mathcal{C}$, $\text{Hom}_{\mathcal{C}}(X,Y)$ was a simplicial abelian group, this would be true as a consequence of Prop. 1.1.5.10 in J. Lurie's Higher Topos Theory.
Thanks

A: Since this example is kinda fun, let me spell it out. (The intuition should be clear though: the simplicial category I defined is really the result of taking a not-so-exciting (2,2)-category and applying the nerve. This 2-category has non-invertible 2-morphisms, so its nerve shouldn't magically have invertible 2-morphisms. And indeed that's what we'll see: the horn filling condition for 3-horns forces the 2-morphisms to be invertible (up to yet higher morphisms, which won't play a role here))
First of all, for any poset $P$ with pairwise maxima, the assignment $(a,b) \mapsto \mathrm{max}(a,b)$ gives $P$ the structure of a commutative monoid in the category of posets. Taking the nerve now yields a simplicial commutative monoid $NP$, and we can then build a simplicial category with one object, which I'll call $\mathcal{C}_P$ since $BNP$ looks strange.
Here is what the coherent nerve of $\mathcal{C}_P$ looks like in low dimensions:

*

*0-simplices: there's only one.

*1-simplices: elements of $P$

*2-simplices: A pair of elements $(a,b)$ together with a third element $c$ such that $c \le \mathrm{max}(a,b)$.

*3-simplices: A triple of elements $(a_1, a_2, a_3)$, a pair of elements $(b_{12}, b_{23})$ such that $b_{i, i+1} \le \mathrm{max}(a_i, a_{i+1})$, and an element $c$ such that $c \le \mathrm{max}(b_{12}, a_3), \mathrm{max}(a_1, b_{23})$

(It's helpful to draw pictures here. One should view $\mathrm{max}(a,b)$ as the 'actual' composite, and a 2-simplex as a 2-morphism from $c$ to the composite. Hopefully I've gotten my arrows in the right direction...)
Anyway, a map from $\Lambda^3_1$ is described by the same data of a 3-simplex except we don't necessarily require $c \le \mathrm{max}(b_{12}, a_{3})$. It can fill to a 3-simplex if and only if this condition happens to be satsfied, in which case it fills uniquely. Of course, said this way, it's clear that we should be able to find un-fillable horns.
As an explicit example, take $P= [1]$, and consider the horn specified by $a_2 = a_3 = b_{12} = b_{23} = 0$, $a_1 = c= 1$.

Some bonus info which you may or may not care about (mostly in response to Porter's comment):

*

*Porter is of course correct that the proper birthplace for the modern version of these ideas is Cordier (and Porter himself!) and Boardmann-Vogt/Vogt, but I might add Segal and Leitch to that list, who were also thinking about homotopy coherent diagrams in the 70s but using topological categories instead of simplicial categories. I guess Dwyer and Kan's work is also related at the very least in spirit. Mainly I wanted to mention this because Segal's name for $\mathfrak{C}(K)$ is the 'explosion of $K$', and we should all totally use this name because it's great.

*Given a category enriched in marked simplicial sets (a model for $(\infty,1)$-categories) its coherent nerve can be given the structure of a "scaled simplicial set", which is a riff on Verity's general notion of stratified simplicial sets/ complicial sets and model $(\infty,2)$-categories. This is developed in Lurie's paper on $(\infty,2)$-categories and Goodwillie calculus.

*If instead you have a category enriched in quasi-categories, you can associate to each quasi-category $X$ the marked simplicial set $(X, E_X)$ where $E_X$ is the collection of 1-simplices which are equivalences. This will produce a fibrant marked simplicial set (I think) and then you can do the procedure in the previous bullet to get a (fibrant) scaled simplicial set.


text:
Q: Is it possible to have a CSS selector based on an attribute range? Assume the following:

Is it possible to have different background colours based on the range:
for instance:

Obviously I made up the syntax but I think it indicates what I'm trying to do. Is this possible in CSS alone?


text:
Q: Make Arduino and 89C52 talk to each other I am trying to create a project in which I am required to make Arduino and Atmel 89C52 talk to each other.
I know this can be achieved via UART but the problem is my Arduino is already using its TX/RX ports. Is there a way to make them talk by any other means? Like I2C or SPI interface? Would soft UART suffice? The whole project depends on then talking to each other effectively.

A: It is absolutely possible to make them talk :) Arduino has a feature for multiple RX/TX communications. It can be accomplished with Software serial. As far as connecting Arduino with 89c52 with I2C is concerned, it is only possible when you write I2c protocol from 89c52 side (AT89C52 doesnot have hardware I2C port).
So if your Serial port of Arduino is occupied by any other device, you could change that pin to software serial (meaning transfer the purpose to other pins) and use that serial port for making communication with 89c52.
EDIT
Yes you can use SPI interface, but that is not my choice ;) since it requires 3 wires and is only intended for short distances. And also you need to have At89s52 not at89c52.

A: With additional hardware you could switch the Arduino's UART lines between the Atmel 89C52 and the other device. These hardwares are called multiplexers, and by some control pins it is available to swap between analog or digital lines. This way you could communicate only with one device at a time, so if it is a problem then stick with the software serial.
To give an example let's see CD4052B
It is a Differential 4-Channel Analog Multiplexer/Demultiplexer, which means that it can swap two lines (RX,TX in your case) between four different devices.

You connect RX and TX to X-COM and Y-COM and by A and B switch between the devices.

A devices/channel could be selected according to the table above.