plaster shower walls, how to do them today?

Question: I have an American 1950's home. It appears the previous owner covered original plaster walls with an inexpensive glue together shower panel system. Most of the homes in the area were built with tile bathtub/shower walls, but mine seems to have never been tile.  I am considering removing all the original plaster down to the studs, then recovering with cement board and plaster.
I looked around here, the best post I find is How to better waterproof the shower area? which points out it does not matter much what you cover the wall with it is what is behind that matters.  I searched google a bit and found several walls that seemed to be plaster.
Random example
What is the recommended approach for plastering walls in a shower?  Are there any specific products or practices that I should or should NOT use?
Answer: What you cover the walls with certainly does matter if it can be damaged by water, as many forms of plaster can--such as modern gypsum plaster, which softens and disintegrates in the presence of water. The only way I can imagine a plaster shower working is if you perfectly waterproof the cementboard with a paintable waterproofing membrane like RedGard (preferred) or poly sheeting behind the cementoard, and then use old-fashioned lime plaster, and then paint the lime plaster with multiple coats of a waterproof but vapor-permeable silicate mineral paint or some other type of vapor-permeable waterproofing agent.
But this is a totally non-expert perspective; I have never built a plaster shower and the whole idea sounds risky and ill-advised to me. If you want to go with this approach, you should probably bring in a pro.
Comment: It looks like there are waterproof plasters available [random example](http://www.isomat.eu/Waterproofing-of-walls-by-applying-waterproof-plaster.html)
Comment: You do NOT want multiple waterproof layers --- it creates a "mold sandwich".
Answer: What you want to do is certainly possible. I'm planning on doing a similar thing. Waterproofing is the key. You want your wet walls to be able to dry to the outside of the wall and not retain water or let water travel inside the walls where it can possibly grow mold.
There's a special product I've looked into that's  not available in my area called super shower finish, from Merlex. I'm currently figuring out how to do something similar to it but with products from home depot or Lowe's. Their process for doing it over cement board is to use a base layer of their Base X product (which is a polymer enriched mortar)over the cement board, and embed a 4oz fiberglass mesh into it to lessen cracking. Then put the super shower finish over that surface.
My thought is to use a paint on waterproofer (like red guard and others) over concrete board, a polymer enriched thinset for the base layer, with the mesh, paint on an acrylic binder after it cures (gives the final layer additional working time and adhesion), and finish it with either ardex feather finish, or a cement resurfacing product or something. I haven't used either of those products so I don't know how they'll work. Specifically, I don't know how the resurfacer goes onto vertical surfaces and I don't know how the feather finish handles water.
There are many companies that have "micro cement" mixes, but none of them seem to be in my area as far as I can tell. You might have better luck. Each of them might have their own ideas for how to build the wall to last in a wet area of the house.
Another solution would be something called Tadelakt. It's a lime plaster finish used in Moroccan bath houses for centuries. It's a bit labor intensive apparently and the waterproof layer is on the outside, which means if it gets damaged with harsh chemicals or rough treatment, the waterproofing is gone and the whole wall will have to be redone (according to what I've read). It's waterproofed with a "black soap", which is ash and olive oil, that creates the waterproof surface and binds with the lime more as time goes on.
Apparently, a well done Venetian finish plaster job can also create a waterproof wall, though I'm not sure a shower is the right place for it.
Answer: It's not clear to me what form your new shower will take, whether it will be a commercial modular system ("glue together shower panel system") or if you want to build a new shower yourself. I've recently stripped my shower back to the studs and built a tiled shower. I got a lot of great direction from the Floor Elf. Don't let the name (or the dry, self-deprecating humour) fool you --- this guy knows his stuff, and he's shared a lot of his knowledge on his site. You can piece together how to build a tile shower from his various blog posts, or you can buy a "Complete Shower Waterproofing Manual" (customised for the various designs) for a modest fee of $20.
Regardless of how you're going to build your shower, you have to be aware that plaster is not waterproof. If the walls in question are going to be exposed to water, you should not be using plaster. Walls near but not in a shower should be greenboard (regular drywall with a water resistant facing). Walls in the shower should be waterproofed with one of a variety of methods:

Traditional waterproofing (plastic sheet) behind cementboard
Topical liquid membrane (e.g., Redgard) over cementboard
Topical sheet membrane (e.g., Kerdi) over greenboard
Commercial modular system


Entity Framework get SUM from child property

Question: I have the following model where I'd like to get the sum of all OrderTotalItems for all Orders of a Customer where the OrderTotalType (Enumeration) is "total" or 99:
public class Customer
{
    ...
    public ICollection<Order> Orders { get; set; } = new Collection<Order>();
}

public class Order
{
    ...
    public ICollection<OrderTotalItem> OrderTotalItems { get; set; } = new Collection<OrderTotalItem>();
}

public class OrderTotalItem
{
    [Required]
    public int Id { get; set; }
    [Required]
    [Column(TypeName = "decimal(10, 4)")]
    public decimal Value { get; set; }
    [Required]
    public OrderTotalType Type { get; set; }
}

I am building a CustomerAdminDTO to include all relevant data of a customer for the admin client:
public class CustomerAdminDto
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public Gender Gender { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string VATId { get; set; } = "";
    public bool VATIdValid { get; set; } = false;
    public DateTime Added { get; set; }
    public DateTime LastModified { get; set; }
    public decimal OrdersTotal { get; set; }
    public CustomerStatusShortDto CustomerStatus { get; set; }
    public CustomerAddressDto CustomerAddress { get; set; }
    public CustomerAddressDto BillingAddress { get; set; }
    public ICollection<OrderListShortDto> Orders { get; set; }
}

In my data service I fill the DTO like that
var customerAdmin = await _context.Customers
    .Include(x => x.Addresses)
    .Include(x => x.CustomerStatus)
    .Include(x => x.Orders)
        .ThenInclude(x => x.OrderTotalItems)
    .Where(x => x.UserId == userid)
    .Select(customer => new CustomerAdminDto
    {
        Id = customer.Id,
        UserId = customer.UserId,
        Gender = customer.Gender,
        FirstName = customer.FirstName,
        LastName = customer.LastName,
        VATId = customer.VATId,
        VATIdValid = customer.VATIdValid,
        Added = customer.Added,
        LastModified = customer.LastModified,
        OrdersTotal = customer.Orders.Sum(x => x.OrderTotalItems
            .Where(x => x.Type == Enums.OrderTotalType.Total)
            .Sum(x => x.Value)),
        CustomerStatus = new CustomerStatusShortDto
        {
            Id = customer.CustomerStatus.Id,
            Name = customer.CustomerStatus.Name,
        },
    ...
    }
    .FirstOrDefaultAsync();

where everything works, except the OrdersTotal.
API compiles fine but throws the following error at runtime:

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Thanks for your hints!
Comment: try smth like `customer.Orders.SelectMany(o => o.OrderTotalItems).Where(x => x.Type == Enums.OrderTotalType.Total).Sum(x => x.Value);`
Comment: @ingvar Thanks it worked. Damn, I had a try with "SelectMany" before but in my statement I missed the closing ")" after the OrderTotalItems and continued directly with "Where".
Comment: Cool. I will post an answer with additional explanation
Answer:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

This error in SQL server means that you tried to call aggregation function (customer.Orders.Sum() in your case) on other expression that contains aggregation function (.Sum(x => x.Value) in your case). In order to avoid this you can simplify your LINQ expression for OrdersTotal:
OrdersTotal = customer.Orders.SelectMany(o => o.OrderTotalItems).Where(x => x.Type == Enums.OrderTotalType.Total).Sum(x => x.Value)

There is only one aggregation here so it should work fine


Separating a string according to fixed lengths in R, to create columns

Question: I have a list of strings that I would like to turn into a dataframe.  I would like to delimit each string according to some fixed length, for example, let's say my list looks like:
text = c("ABC      ABC BROWNIES COMPANY            1/31/2009",
         "BCD      BCD BROWNIES COMPANY            1/31/2009")

and I want to turn it into the dataframe that would result if I used:
FINAL <- data.frame(rbind(c("ABC", "ABC BROWNIES COMPANY","1/31/2009"),c("BCD", "BCD BROWNIES COMPANY","1/31/2009")),stringsAsFactors = F)

colnames(FINAL) = c("Ticker","Company","Date")

FINAL
Basically I want to introduce some sort of fixed-length delimiting to separate the items in each element of "text."
I don't think I can use strsplit because I don't really have one character on which to split (spaces won't work because some of my entries contain spaces, and there are uneven spaces from "Ticker" to "Company" and "Company" to "Date").
Any help would be much appreciated!
Answer: Since you mention fixed length delimiting, maybe give read.fwf a try.
read.fwf(textConnection(text), widths = c(3, 21, 13),
         col.names = c("Ticker", "Company", "Date"))
#   Ticker               Company       Date
# 1    ABC  ABC BROWNIES COMPANY  1/31/2009
# 2    BCD  BCD BROWNIES COMPANY  1/31/2009

You can mess around with the middle 21 value to get it to work on all the data.
Another possibility is to split on three or more spaces.
data.frame(do.call(rbind, strsplit(text, " {3,}")))
#    X1                   X2        X3
# 1 ABC ABC BROWNIES COMPANY 1/31/2009
# 2 BCD BCD BROWNIES COMPANY 1/31/2009

Comment: Thank you so much everyone for your input!  I'm going to go with read.fwf, since sometimes in my data the columns will only be separated by one space -- but this is great, so many new things I've learned =)
Answer: Either use read.fwf or substitute long spans of spaces with a delimiter.
> read.table( text=gsub(" {3,10}", ",", text), sep="," )
   V1                   V2          V3
1 ABC ABC BROWNIES COMPANY   1/31/2009
2 BCD BCD BROWNIES COMPANY   1/31/2009

Comment: To play the SO game correctly, you now need to give Richard the checkmark
Answer: Possibly str_split_fixed from stringr:
library(stringr)
##
Df <- data.frame(
  str_split_fixed(text,pattern="\\s{2,}",3),
  stringsAsFactors=F)
##
names(Df) <- c("Ticker","Company","Date")
##
> Df
  Ticker              Company      Date
1    ABC ABC BROWNIES COMPANY 1/31/2009
2    BCD BCD BROWNIES COMPANY 1/31/2009
> str(Df)
'data.frame':   2 obs. of  3 variables:
 $ Ticker : chr  "ABC" "BCD"
 $ Company: chr  "ABC BROWNIES COMPANY" "BCD BROWNIES COMPANY"
 $ Date   : chr  "1/31/2009" "1/31/2009"

which assumes that 2 or more consecutive spaces indicates a new column; although this could be adjusted if necessary.
Comment: The newer version of ["string**i**"](https://github.com/Rexamine/stringi) have a `simplify` argument, that would let you do the following: `stri_split_regex(text, "\\s{3,}", simplify = TRUE)`.
Comment: Thanks so much!  I just downloaded stringr, and I didn't realize it could do so many things!


Input autocomplete in React: How do you update a mapped array in the UI?

Question: I'm writing an address autocomplete field that uses the Google Places autocomplete API.
I'm using React Query to fetch the data as the user types, and showing a <datalist> inside which I'm mapping over the array and outputting <options> when the array of predictions comes in.
All of that works, but the dropdown containing the fetched options doesn't show in the UI unless I click out of the browser window and back into the address field.
Relevant code:
const [placeData, placeIsLoading, placeIsSuccess, placeIsError, placeError] = useFetchPlacesAutocomplete(address)

const [address, setAddress] = useState()
const [addressAutocomplete, setAddressAutocomplete] = useState(false)

<FormControl id="address" position="relative">
                        <FormLabel htmlFor="address">Address</FormLabel>
                        <Input
                            w="20rem"
                            mb={8}
                            value={address}
                            variant={addressAutocomplete ? "flushed" : "outline"}
                            list="predictions"
                            onChange={e => {
                                setAddress(e.target.value)
                                handleAutocomplete(e)
                            }}
                        />
                        {addressAutocomplete && placeIsSuccess &&
                            <datalist id="predictions">
                                {placeIsSuccess &&  placeData.predictions.map(i => (
                                    <option
                                        key={i.description}
                                        onClick={() => {
                                            setAddress(i.description)
                                            setAddressAutocomplete(false)
                                        }}
                                        value={i.description}
                                    />

                                ))}

                            </datalist>
                        }

                    </FormControl>

I think the main question is, why is the placeData variable updating as the user types, but the result of mapping over that array isn't showing up in the UI in real time?
Thanks in advance!
Edit:
Additional info. I believe I know why it's not updating - React is receiving placeData as an array, but the state isn't considered updated if the contents of that array changes, so the component won't re-render. So I think the solution is to force a re-render when input field changes, but I don't know how to do that yet.
Comment: If you update some state a re-render happens. So you can trigger a re-render by updating some state. But I would first recommend checking your conditions `addressAutocomplete && placeIsSuccess` and if that actually works. Does the previous condition evaluate to `true`? Also what does `placeData.predictions` look like?
Comment: impossible to tell without knowing what `useFetchPlacesAutocomplete` does. is the address part of the queryKey?
Comment: @TkDodo I added the address to the queryKey and it worked, that was it. It was previously just a string.
Answer: The solution (or at least my solution) was to pass the input from the address state as the queryKey to generate a new query for each keystroke. Previously the queryKey was just a string.


Combining output of two queries

Question: table1:
col1   col2
john   new york
jimmy  london
jerry  mumbai
jack   perth

table2:
col1   col3
john   10
jimmy  20
jerry  40
jack   30

Query 1 is
select col1,col2 from table1

Query 2 is
select col1,col3 from table2

now since col1 of both the queries are same, I want to merge both the queries and require following o/p
col1   col2        col3
john   new York    10
jimmy  London      20
jerry  Mumbai      40
jack   perth       30

thanks.
Comment: Tip of today: Do a JOIN!
Answer: Try this,
SELECT t1.col1
    ,t1.col2
    ,t2.col3
FROM table1 t1
INNER JOIN table2 t2 ON t1.col1 = t2.col1

Combining output of two queries


Literal or expression to create an object with a string-valued property name

Question: The following code creates an object in which the property name is set at runtime:
let pn = "xyz", ob = {}
op[pn] = 999

Is there any way to do that in a single step, as either a literal or an expression, and avoid the explicit assignment?
let pn = "xyz", ob = { <clever stuff goes in here> }

[Obviously I could write my own function, but where's the fun in that?]
Answer: How about that by just using brackets []?

/*
// old way :)
let pn = "xyz", ob = {}
ob[pn] = 999
console.log(ob)
*/

//clever stuff goes here :)
let pn = "xyz", ob = { [pn]:999 }
console.log(ob)
Comment: Thanks: but pn is just a temporary and not needed, so I assume you could omit it?
Answer: You can define key with in the object like this
 let obj={[pn="Xyz"]:999}
 console.log(obj);

Comment: Am I right in saying this is new in ES2015? See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer.
Comment: Thanks: but pn is just a temporary and not needed, so I assume you could omit it?


Sealing the roof

Question: I have a flat cement roof that is leaking into the ceiling of the top room. How would I seal it?
It is also a patio. What would work? Should I tile it or seal it with rubber paint (can you still walk on it)?
Comment: Can you clarify "flat roof cement roof"? Is your building's roof made out of poured concrete? Does it have some sort of "cement-like" coating over a wooden structure? What type of sealing coating does it currently have on it? If you're not sure, a couple of pictures (especially of the leaking area) would be very helpful. Please [edit] your post and add the answer in there to ensure that the majority of people read it (not everyone reads all the comments).
Answer: A typical approach (there are many options, some more prone to damage than others) to a concrete slab roof that you want to have foot traffic on without damaging the waterproofing membrane is to have something like an EDPM rubber sheet (continuous, or joined in an approved manner to be effectively continuous) a layer of insulating foam board (XPS) and a layer of cementboard or pavers to take the foot traffic and spread that load onto the foam board, which further spreads the load onto the membrane and helps to protect it from damage. Cementboard is sometimes bonded to foamboard to make a panel for this purpose.
If your roof has developed leaks, it's rarely the case that a simple patch will hold, as low-slope ("flat") roofs are relatively more difficult to waterproof effectively than roofs where the water quickly runs off due to slope.
What sort of patch you might expect to work would depend greatly on what the actual waterproofing membrane is at present, and the nature of the damage causing the leak. If the membrane has deteriorated to the point that's it's failed in one spot, it may fail in other spots soon. If there is a clear damage site that is localized to one spot, repair may make more sense, but overall deterioration often means the most sensible repair is a whole new roof. If repair is viable, the repair method should be one compatible with the roofing membrane - hot tar is different from EDPM rubber is different from Acrylic/fabric composite membrane. Using incompatible patch methods may temporarily work, and then fail again shortly.

Sealing the roof


Tensorflow error [image not found]

Question: I installed tensorflow ver1.0.0 but it did not work!!
I use Python3.6.0, Tensorflow-gpu-1.0.0. Please tell me how to fix it!
<code>~/Desktop/tensorflow $ source ~/Desktop/tensorflow/bin/activate
 (tensorflow) ~/Desktop/tensorflow $ python
Python 3.6.0 (default, Feb 17 2017, 14:31:13)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
Traceback (most recent call last):
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 61, in <module>
from tensorflow.python import pywrap_tensorflow
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
_pywrap_tensorflow = swig_import_helper()
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/imp.py", line 242, in load_module
return load_dynamic(name, filename, file)
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/imp.py", line 342, in load_dynamic
return _load(spec)
ImportError: dlopen(/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow.so, 10): Library not loaded: @rpath/libcudart.8.0.dylib
  Referenced from: /Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow.so
  Reason: image not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-    packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 61, in <module>
from tensorflow.python import pywrap_tensorflow
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
_pywrap_tensorflow = swig_import_helper()
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/imp.py", line 242, in load_module
return load_dynamic(name, filename, file)
  File "/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: dlopen(/Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow.so, 10): Library not loaded: @rpath/libcudart.8.0.dylib
  Referenced from: /Users/ubeat0n/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow.so
  Reason: image not found

Failed to load the native TensorFlow runtime.

See     https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
>>>
</code>
seems above, I was able to install tensorflow, and activate tensorflow-gpu 1.0.0....
In reference to other similar question in stackoverflow, I disable csrutil!
    csrutil disable
Wasn't tensorflow installed..??
Comment: Seems I could install CUDA!
Comment: (tensorflow) ~/Desktop/tensorflow $ brew cask info cuda
cuda: 8.0.55
https://developer.nvidia.com/cuda-zone
/usr/local/Caskroom/cuda/8.0.55 (23 files, 1.3G)
From: https://github.com/caskroom/homebrew-cask/blob/master/Casks/cuda.rb
==> Name
Nvidia CUDA
==> Artifacts
(tensorflow) ~/Desktop/tensorflow $
Comment: Please follow up in github for install issues, and make sure you follow the instructions in the documentation.
Answer: I solved the error by adding
<code>$export DYLD_LIBRARY_PATH=/Developer/NVIDIA/CUDA-8.0/lib\
                     ${DYLD_LIBRARY_PATH:+:${DYLD_LIBRARY_PATH}}
</code>
like in the CUDA Installation Guide.

Tensorflow error [image not found]


Do I have to complete all the quests?

Question: Can I complete the game just by doing the main story quests? Or do I have to do all of the side quests as well, to make sure my Hunter level is high enough for the story quests?
Answer: Meow-Oui. Yes to the latter question, but you can skip the ones you don't like on your later playthroughs (D: Oh Air Robo GP, how I loathe thee).
All quests are mandatory, but the order you complete them in is not. The WiFi/DLC quests (already preloaded on the NA versions) are optional. There should be ~80 quests or so.
It's suppose to give you the feel for the atmosphere of the game (such as the fun dialogues).
Don't miss out on the Tail Concerto cameos!
Comment: Argh. I hate Air Robo GP. >.<

Do I have to complete all the quests?


git change branches with some files being modified

Question: I'm working on the branch 'br3'. I have 3 modified files. I want to commit them to different branch, for example 'br1'. I know that I can safely change branches only if I don't have modified files in the tree, so I need to either:

copy files, revert changes, change branch, paste files
stash files, change branch, unstash them

I've never tried second option and I'm not sure it will work out. Will it? Or there is better alternative to the ones I outlined above?
Answer:
I know that I can safely change branches only if I don't have modified files in the tree,

That's not really true; if the changes will apply cleanly, it will work fine.  If not, you'll be told so and given the chance to fix them.
Your second option is probably the safest:
$ git stash
$ git checkout br1
$ git stash apply
$ git add ...
$ git commit ...

But it's quite likely that just:
$ git checkout br1
$ git add ...
$ git commit ...

will work just fine.
Comment: *"If the changes will apply cleanly"* <-- I don't think this is technically true.  IIRC, you can only switch branches with a dirty working directory when all of the dirty files in the working directory are **identical** in the current and target commit.
Comment: @cdhowie - that could be, yeah.
Comment: @cdhowie, >> _are identical in the current and target commit_ --could you please elaborate on that?
Comment: @Maximus I'm not sure how I can elaborate, unless you are not clear on what "current commit" and "target commit" mean.  "Current commit" is the commit you have checked out currently.  "Target commit" is the commit you are trying to check out.
Answer: You can do a so-called "merge checkout" which will attempt to merge any changes you have made in the working tree into the target branch.
git checkout --merge br1

If there are any conflicts then you will have to resolve them just as when merging branches.
I would strongly suggest running git stash && git stash apply first, as this will make sure that you can return the working directory to its current state in case the merge fails so badly that you have to reset.  If this happens and you did stash your changes, you can restore the working directory like this, and then try again:
git reset --hard
git checkout br3
git stash apply

Comment: @Maximus That doesn't really matter.  Merging two identical files is a no-op, so even if Git tried the end result would be the same: the files would still be identical.
Comment: Will it try to merge only modified files?
Comment: If you run git stash first, then there isn't going to be anything to merge unless you reapply them
Comment: @cdhowie, br1 and br3 have a lot of differences in files. However, I want to merge only differences of only those files, that are now determined as modified. I don't want to merge entire branches. Is that what it's going to do?
Comment: @Maximus Yes, according to the documentation.  *"However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch."*
Answer: Stashing and applying is one solution
git stash
git checkout TARGET_BRANCH
git apply
#review and if i like it
git stash drop

Read more about it here:
http://git-scm.com/book/en/Git-Tools-Stashing
Another is diff based, perhaps the other branch you already have open in another repo (stashes don't go from repo to repo). Or perhaps even on a different box!
git diff HEAD > ~/mypatch
cd SOME_OTHER_REPO
#(or mail it to the other box or what have you and extract to ~/mypatch)
git checkout other_branch
git apply ~/mypatch


What happens if a non-suspend function is called from a coroutine?

Question: One of the key concepts of coroutines in Kotlin is that a suspend function must be called from a coroutine or another suspend function.
However, a suspend function can call any kind of function, suspend or normal.
What is the consequence of that? (This is not a real scenario i have, just want to know for theoretical reasons)
I imagine that in that scenario the only point of creating a coroutine would be to change the context (thread) before calling it, so it doesn´t block the main thread.
However, would all the other advantages of coroutines be lost? (cooperative cancellation, structured concurrency...)
Comment: nothing, literally nothing. except when you have to call `withContext` because of the non suspending method has relations to the UI
Answer: If a suspending function calls another suspending function, then the coroutine is suspended, until the result is returned.
Calling a regular function from a suspending function will block the thread. Which thread? Well, that depends on the Dispatcher you're using. IO is able to spawn hundred of threads. But the Default dispatcher has same amount of threads as your CPUs count. Meaning that while this won't block other coroutines, it will reduce the amount of available resources.
Meaning: don't invoke non-suspending function that may block for a long period of time on this dispatcher, same as you don't block your UI thread.
And yes, suspending function may produce the same results, if you're do something like a busy loop without yield() or any other suspend invocation in it.
Comment: You're right. It may be more accurate to say that invocation may or may not suspend the invoking coroutine. But I think this kind of accuracy will confuse the readers more than it will help them.
Comment: The point you want to make with your first sentence is lost if you take it literally. Calling a suspendable function doesn't suspend the coroutine; only calling `suspendCoroutine` and its siblings does that. Also, if enough concurrent coroutines call blocking code on `Default` it _will_ block all coroutine progress.
Answer: Suspend functions can be suspended in between and resumed later. Calling a normal function from a suspend function you lose the ability to pause the execution.
when a suspend function is compiled, kotlin compiler adds a continuation object as a parameter in the arguments. This continuation object is required for suspending a coroutine. When a suspend function calls another suspend function it passes the continuation object same is true with co-routines.
if a non-suspend function is called from suspend function you just wont be able to use co-routines from that function... that's it
Comment: > Calling a normal function from a suspend function you lose the ability
> to pause the execution.

Disagree, you won't loose ability to pause. Root suspend function will work as you expect
Comment: I think he just meant what others has stated in this thread: that the non-suspend function can't be paused.
Answer:
However, would all the other advantages of coroutines be lost? (cooperative cancellation, structured concurrency...)

Even a non-suspendable function can participate in cooperative cancellation by explicitly checking the CoroutineContext.isActive flag. This is more of a theoretical fact, though.
If a function performs a blocking IO operation, it will not respond to cancellation requests. The operation will have to complete on its own.
As for structured concurrency, almost the opposite of your concern is true: it is a Kotlin best practice to launch child coroutines from a non-suspendable function that is instead an extension on CoroutineScope and calls the coroutine builders with it as the receiver.
Comment: Let's say I have root suspend function, launched by ViewModelScope. And inside it I call non-suspend function which does some heavy work, for example Sqlite query using Room. Then at the 50% of that query I cancel that job. What the result I get, leaking? Room won't stop?

Thanks in advance!
Comment: Best to try it out and make sure. If the blocking code is non-interruptible, there's nothing you can do to stop it from the outside, and interruption itself is a dangerous mechanism because you never know what will throw `InterruptedException`. If you did the Kotlin side right, the coroutine would not complete until the blocking operation completes.
Comment: okay, I'll try. I ask it because if there weren't any differences, there weren't be any necessary at adding support of suspend to Room's DAO and Retrofit2's Services
Comment: @AkbolatSSS When you cancel a job it will continue to run and coroutine moves to Cancelling state. The job is canceled fully only when the work inside it is completed
Comment: Adding to @FarazAhmed's statement, the coroutine will get the `CancellationException` as soon as it attempts to suspend itself, and the code is required to let it through without catching, so that it escapes the coroutine's top level. This is not only trivially easy to break, it is actually considered a best practice to have that `catch (e: Exception)` at the top level so you take control of your exceptions. That code must be made coroutine-aware and be transparent to `CancellationException`.


Encoding type and key problem in Bouncy castle AES Encryption

Question: I am using Bouncy Castle crypto libraries. I have a 13 character key something like
string key = "wergt543jusft";
Text to be encrypted is: string plain = "435625241526373";
I convert it into 128 bit key using the following method.
public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.ASCII.GetBytes(key);

    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

Then, I create an object of AESEncryption class which I have defined
AESEncryption aes = new AESEncryption(Encoding.ASCII, new Pkcs7Padding());

Class AESEncryption has two methods:
public string Encrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Encrypt(plain, hashKey);
}

public string Decrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Decrypt(plain, hashKey);
}

Everything works fine.
But, when I change the encoding type to anything other than ASCII, I get error "Key length not 128/192/256 bits.". I made the following chnages in my code to change the Encoding type:
public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.UTF32.GetBytes(key);
    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

AND
AESEncryption aes = new AESEncryption(Encoding.UTF32, new Pkcs7Padding());

Rest of the code remains the same. Can anyone please guide?
Thanks in advance...
I am following the link:
http://elian.co.uk/post/2009/07/29/Bouncy-Castle-CSharp.aspx
My aim is to generate the encrypted string for the variable plian = "435625241526373" using all encoding types such as:
ASCII,BigEndianUnicode,Unicode,UTF32
UTF7,UTF8
[Edit from comments]
The exception is thrown inside this method:
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{
    try
    {
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) :
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        byte[] keyByte = _encoding.GetBytes(key);
        _cipher.Init(forEncrypt, new KeyParameter(keyByte));
        return _cipher.DoFinal(input);

    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message);
    }
}

Comment: What line do you get this error at? MD5 hash will always be 128 bits long, regardless of the key length or encoding, so it isn't clear how you would get such error.
Comment: @Hari: in what class/method is that? I don't see a `_cipher` field in the example. Also, `AESEncryption` is the name of this class you wrote (containing `Encrypt` and `Decrypt` methods?
Comment: If you refer to Bouncy Castle link (Class BCEngine), thr is a method called BouncyCastleCrypto(bool forEncrypt, byte[] input, string key). I am getting error in line=> _cipher.Init(forEncrypt, new KeyParameter(keyByte));
Comment: Also wanted to tell you that I am able to encrypt/decrypt a string for ASCII, UTF7 and UTF8. Its only in the case of other encoding types where i am getting this error.
Comment: @Hari: you can check my answer. Encoding used in the message data shouldn't be used to encode the key, because it doesn't guarantee that the array will have constant length for different inputs. In other words, hashing the key will be the simplest solution since it gives constant hash length for any key.
Answer: You need to make sure that your key is 128/192/256 bits long. Just as you used getKeyMessageDigest inside Encrypt and Decrypt methods, you can use it inside the try/catch clause to create a 128-bit hash value of your key:
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{
    try
    {
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) :
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        // this line will make sure keyByte is 16 bytes long
        byte[] keyByte = getKeyMessageDigest(key);

        _cipher.Init(forEncrypt, new KeyParameter(keyByte));

        return _cipher.DoFinal(input);
    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message);
    }
}

Additionally, you don't need to worry about changing the encoding inside getKeyMessageDigest, encoding is passed around just to ensure correct encoding for the actual data, not the key.
MD5 hash always contains 16 bytes, regardless of the input size. So, the only problem is if you use Encoding.GetBytes to get the key, since this method returns different array lengths for different encodings.
Comment: Hi Groo, thanks a lot for the timely help. Your suggestion did the trick. I made some changes to my getKeyMessageDigest method=>                                                      public byte[] getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.Unicode.GetBytes(key);

    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    return HashData;
}


Select unique random posting/recruitment places of employees within a list of places

Question: I am trying to select unique random posting/recruitment places of employees within a list of places, all the employees are already posted at the places, i am trying to generate a new random posting place for them with "where" condition that "employee new random location will not be equal to their home place"
Employee table is :
EmpNo   Empname           CurrentPosting    Home        Designation RandomPosting
1       Satish Kumar      Samastipur        Gazi        Manager
2       Anil Kumar Singh  Vaishali          Patna       Manager
3       Rajdev Prasad     Nawada            Gaya        PO
4       Rajesh Kumar      Sheikhpura        Muzaffarpur PO
5       Jitendra Kumar    Banka             Bhagalpur   Clerk

And so on...
And Places table is
PlaceID  PlaceName      Manager     PO    Clerk
1        Araria            2        0     1
2        Arwal             1        1     1
3        Aurangabad        1        0     2
4        Banka             2        1     1
5        Begusarai         1        1     1
6        Bhagalpur         1        1     2
7        Bhojpur           0        2     0

and so on...
i tried with rand() and newid() like as below,
select Employee.*, Place.PlaceName As RandomPosting  from Employee
inner join Place on Place.PlaceID=Employee.EmpNo order by newid()

But unable to select what is required... that is to assign each Employee a PlaceName(from Place) randomly which is not equal to CurrentPosting and Home(in Employee).
Thanks in advance.
Comment: thanks for quick response, i didnt tried that , can u please comment that query... i m newbie in sql..
Answer: WITH cteCrossJoin AS (
    SELECT e.*, p.PlaceName,
           ROW_NUMBER() OVER(PARTITION BY e.EmpNo ORDER BY NEWID()) AS RowNum
        FROM Employee e
            CROSS JOIN  Place p
        WHERE e.Home <> p.PlaceName
)
SELECT *
    FROM cteCrossJoin
    WHERE RowNum = 1;

Comment: thanks a lot @Joe, one issue .. i m getting only one record - first employee(EmpNo 1) with random new PlaceName exactly as required, how to get all the employees...
Comment: @MAX: I had a bug where I forgot the PARTITION BY clause. Have you tried it with that change?
Comment: Hi @Joe, I need your help again... how to to limit the random selection based upon designation numbers(in Places table)... that is to assign each Employee a PlaceName(from Places) randomly which is not equal to CurrentPosting and Home(in Employee) and Place wise designation will not exceed as given numbers.
Comment: @Joe I have posted this question at : http://stackoverflow.com/questions/12544051/randomly-assign-work-location-and-each-location-should-not-exceed-the-number-of


How to use the CS:GO sharing code

Question: In the 'Watch' tab there is a match sharing code for your last games. If i want to share a demo to my friends, what should they do to see it? How to use the sharing code? Is there a special command?
Answer: Apparently there is a Copy Link near that code. If you click it you should get a URL like this one: steam://rungame/730/76561202255233023/+csgo_download_match%20CSGO-Y4DVh-amkvh-OyBrh-SyMHN-2SvPB
If you put that in a browser tab it will tell CS:GO to launch via steam and then watch the match.. The code at the end of the URL is the id of the match.

How to use the CS:GO sharing code


(PHP) Getting null in a preg_match instead of getting a empty string

Question: I have the following code:
$pattern = '(([a-z]{2})/)?(([a-z]{3,})/)?(\d{4}+)(/(\d{2})(/(\d{2}))?)?';

preg_match('#^' . $pattern . '$#i', '2010/12/01', $match);

$match = Array (
    [0] => 2010/12/01
    [1] =>
    [2] =>
    [3] =>
    [4] =>
    [5] => 2010
    [6] => /12/01
    [7] => 12
    [8] => /01
    [9] => 01
)

The problem is that $match[1], $match[2], $match[3] and match[4] are string(0), is there any way to modify the $pattern in order to get null instead of string(0)?
Comment: Why do you want it null and not ''. I dont think this is possible but we can help with a workaround.
Comment: A quick workaround: `foreach( $match as &$item ) if( $item == '' ) $item = null;`
Comment: Which version of PHP are you targeting?
Comment: I was wondering is your source always like `YYYY/MM/DD`?
Comment: The problem is that when I join it with another array, the string(0) parameters do not get replaced.
Answer: No, that is not possible in PHP. The preg_match() function only deals with strings and null is an entirely other data type.
Converting this to what you want is simple though. In PHP 5.3 you can use an anonymous function with array_walk() to iterate over the array and then update your values with a shortened ternary operation.
array_walk($array, function(&$val) { $val = $val ?: null; });


Why does this FTP block read operation throw EOFError?

Question: Can someone please explain why this block read operation would throw an EOFError?  The way I saw it, it would just end the block when the file was read completely.  What am I missing?  How can I fix it?  Thanks so much.
NOTE: I should mention that at times it runs fine and at others it throws the EOFError.  On the same file which is in the same location...
    Net::FTP.open(host=ftp.address, user='********', passwd='********') do |ftp|
      ftp.passive = true
      files = ftp.nlst('*')
      s3 = Aws::S3::Resource.new(region: 'us-east-1')
      files.each do |file|
        ftp.getbinaryfile(file, file, 65536) # Copies file to /tmp
        UpdateVfile.loader(@company, file) # Process file from /tmp
        s3_file = file + Time.zone.now.strftime("-%Y-%m-%dT%H-%M.xls")
        obj = s3.bucket('mydatafeed').object(s3_file) # Build object in S3 bucket
        data = ''
        ftp.getbinaryfile(file, nil, 65536) do |block|  <== EOFError thrown here!
          data << block
        end
        obj.put(body: data) # Write it to S3
        ftp.delete(file) # Delete the file from FTP
      end
    end

Stack trace:
An EOFError occurred in background at 2015.11.23 :

  end of file reached
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:1112:in `readline'

  -------------------------------
Backtrace:
-------------------------------

  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:1112:in `readline'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:289:in `getline'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:300:in `getmultiline'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:318:in `getresp'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:351:in `block in sendcmd'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:349:in `sendcmd'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:394:in `makepasv'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:406:in `transfercmd'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:490:in `block (2 levels) in retrbinary'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:199:in `with_binary'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:488:in `block in retrbinary'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:487:in `retrbinary'
  /app/vendor/ruby-2.0.0/lib/ruby/2.0.0/net/ftp.rb:620:in `getbinaryfile'
  /app/lib/tasks/updates_vfile.rake:40:in `block (6 levels) in <top (required)>'

FTP debug_mode OUTPUT:
put: TYPE A
get: 200 Command TYPE okay.
put: PASV
get: 227 Entering Passive Mode (75,101,155,12,5,165)
put: NLST *
get: 150 File status okay; about to open data connection.
get: 226 Closing data connection.
put: TYPE I
get: 200 Command TYPE okay.
put: PASV
get: 227 Entering Passive Mode (75,101,155,12,5,163)
put: RETR <filename redacted>
get: 150 File status okay; about to open data connection.
get: 226 Transfer complete.
...output from update processing
put: PASV
rake aborted!
EOFError: end of file reached

Comment: `ftp.debug_mode = true` please enable it and try it
Comment: @RajarshiDas It's been added above.  Thanks.
Answer: The issue turned out to be an FTP idle timeout.  Because UpdateVfile.loader is a long-running task, I left FTP alone for too long and it cratered with an EOFError.  Obviously, a timeout error would have been much better than such a nondescript failure that gave me worse than no diagnostic information.
If the loader was short, it worked.  For more intense updates, it took too long.  As I changed the source to try to diagnose and resolve the issue, the EOFError moved to the ftp.delete command, which made even less sense to me.
I found some discussions that hinted at this problem.  As a result, I changed my process to handle all of the FTP work before calling the loader.  This works reliably.  Otherwise, I'd either have to send periodic keep-alives or find a way to modify the timeout period.  Neither appears easy to accomplish.
I'd be happy if someone could explain to me why FTP would issue EOFError instead of a timeout error.  That's just not right and would lead anyone in totally the wrong direction, diagnostically.  Thanks...


How to return key's value of a map of type empty interface

Question: I have taken a variable like var u = make(map[string]interface{}) which means that a key could hold a string/int or another map.
When I do the following it gives error cannot use v (type interface {}) as type string in return argument: need type assertion which looks obvious as the generic map have no idea what should it search. How can I resolve the issue? The code is given below(DO note that currently, the map is entirely empty)
var u = make(map[string]interface{})

// Get function retrieves the value of the given key. If failed, it returns error.
func Get(k string) (string, error) {
    v, found := u[k]
    println(reflect.Type(v))
    if found {
        v = u[k]
        return v, nil
    }
    return v, errors.New(-1)
}

Answer: v, found := u[k] here v is interface{} type
But your function return type is (string, nil) where you are returning (v, nil) or (interface{}, nil).
interface{} can not convert into string automatically, need type assertion.
data, ok := v.(string)

You can return interface{} also and the consumer can decide which type it will converted.
Comment: Ah. OK now I got it. Since the map could contain either string or anything, so it is better to return an `interface` and then the consumer of the function should figure out the type of return value whether it is a string, interface or otherwise and use accordingly?
Comment: yes you can return interface{} also and consumer can decide which type it will converted
Answer: I'm not sure what's your question. But you're getting this error because you are trying to return interface{} as concrete type string. If you want to return string, and you're sure that value of map is always string(then why are you using map[string]interface{} instead of map[string]string?) you can get underlying type of interface by using type assertion:
s, ok := v.(string)

Comment: Now I got it. Since the map could contain either string or anything, so it is better to return an `interface` and then the consumer of the function should figure out the type of return value whether it is a string, interface or otherwise and use accordingly?
Comment: @Volatil3 Yep, that would be good solution, to leave that to consumer


What will Math.floor(Math.random() * 10 + 1); do

Question: I came across the following command:
Math.floor(Math.random() * 10 + 1);

I understand that Math.floor() will convert to the lowest integer, but what does Math.random() * 10 + 1 do?
Comment: you only need to know what `Math.random()` does ... the `* 10 + 1` is elementary level maths - when in doubt [read the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
Comment: `Math.random() * 10 + 1` generates a random number between ( 0 - 10 ) + 1
Comment: `Math.random()` will return a float `0 - 0.99999999` (less than 1) so `* 10` is  `0 to 9.999999` then `+ 1` is `1 to 10.99999999`, and rounded down is `1 to 10`
Answer: Math.random returns a floating point number x such that:

Multiplying 10 to x yields a floating point number in the range:

And then adding 1 to 10x yields a floating point number in the range:

And finally flooring 10x + 1 yields an integer in the range:

Therefore, Math.floor(Math.random() * 10 + 1) yields an integer that lies in the range [1, 10].
Comment: `evaluates to a number...` should probably be `evaluates to an integer....`
Comment: @MikeMat Yeah nice observation, updated my answer.
Answer: Math.random generates a random number between 0 and 1. So for example it can be .124 or .42242. When you multiply this random number against something, you are basically making it so that the new result is no less than 0, but no more than the number you are multiplying it against.
So in your example, you are multiplying it against 10, which means you will get a random number between 0 and 10 with decimals; technically this range is 'more than 0, but less than 10'. The +1 just increases the total range so that it is between 1 and 11, or 'more than 1, but less than 11.
When you apply Math.floor() to this, you are rounding all of these results down. So in the case without the '+1', your finite range is actually 0-9, and with the +1 it is 1-10
Comment: Keep in mind that any time you do the 'Math.floor(Math.random()*num)' that whatever your num is means your range is 0-num not including num.

So when you add something to that, you are increasing both the start and end of the range.


Reverse print result of unix find without sort

Question: I want to sort the result of the find as follows:
I am using:
find . -type f -print0

Result is:
/mnt/sdcard/qu/led/t1/temp42.txt
/mnt/sdcard/qu/led/File.plist
/mnt/sdcard/qu/yellow.plist
/mnt/sdcard/SHA1Keys/SHA1SUMS
/mnt/sdcard/File.xml
/mnt/sdcard/File.plist
/mnt/sdcard/.DS_Store

But i want the result as:
/mnt/sdcard/.DS_Store
/mnt/sdcard/File.plist
/mnt/sdcard/File.xml
/mnt/sdcard/SHA1Keys/SHA1SUMS
/mnt/sdcard/qu/yellow.plist
/mnt/sdcard/qu/led/File.plist
/mnt/sdcard/qu/led/t1/temp42.txt

And if i do:
find . -type f print0 | sort -r

The order gets all messed up. I saw this solution somewhere:
find . -type f -ls | awk '{print $(NF-3), $(NF-2), $(NF-1), $NF}'

But I can't use it since it prints the results.
Also note I don't have permissions to write to the filesystem, so writing to a file and reversing the lines is not an option.
Comment: Are you using `-print` or `-print0`? Your output suggests `-print`.
Comment: @jkshah The output of `find` is NOT *sorted* in any specific way. They look like they are in reverse alphabetical order here, but that is just a coincidence. The order of the output of `find` depends on how the files are stored internally by the filesystem.
Comment: Output of `find` is already sorted. You just need print reverse using `tac`
Comment: This question belongs on Super User not Stack Overflow IMHO.
Answer: Use tac (cat backwards) to reverse output. You don't need to sort it in reverse order, you just need it reversed.
find . -type f | tac

If you want to keep the -print0 then use:
find . -type f -print0 | tac -rs '\0'

Comment: While this will reverse the order, it will not output the files in any specific order. The order of the output of `find` depends on how the files are stored internally by the filesystem.
Comment: For me, this answer does not work for files containing a `0` in their filename.
Comment: On OSX you can get tac via [homebrew](http://brew.sh) by installing `coreutils` - see this answer: http://stackoverflow.com/a/32434423/181664
Answer: Alternatively, you could use tail -r:
find . -type f | tail -r

Comment: This works only on BSD systems like Mac, not with GNU `tail`.


how do I insert output from othermodules/controllers in a view

Question: I have a view and I want to display data that would be generated by othe modules and controllers on the page.
What is the best way to do this?
For example:  If on a certain page I want to pull in the latest news from the news module.
Answer: There's a view helper called Action which allows you to call another controller's action (and display the markup generated).
I would add an action called latestNewsAction that renders a latest news panel/div/list and call that using the action view helper.
Comment: Does this work if the action/controller is in a different module?
Comment: Yep, and you can pass params in an array as the 4th parameter to the helper, especially useful if you need a way of telling the view to do something *slightly* different when it's called from another view!


Why authorization header not included in request ? - Auth0

Question: I have been struggling with this problem for two weeks, Basically I have configured the auth0 settings with my Flask app which runs on local host.
So, I have the following two endpoints in my flask app:

A public endpoint which requires no authentication process:

<code>@APP.route("/api/public")
@cross_origin(headers=["Content-Type", "Authorization"])
def public():
    # No access token required to access this route

    response = "Hello from a public endpoint! You don't need to be authenticated to see this."
    return jsonify(message=response)
</code>

A private endpoint which requires authentication:

<code>@APP.route("/api/private")
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "http://localhost:3000"])
@requires_auth
def private():
    # A valid access token is required to access this route

    response = "Hello from a private endpoint! You need to be authenticated to see this."
    return jsonify(message=response)
</code>
So here is the following scenario:

I try to log in with the auth0 url that redirects me to universal login page for my app. After successful login, it redirects me to the private end point and I get 401 Un-authorized error.

Whenever I make this request with valid token from the browser it throws 401 error.
With the same token, I call this endpoint using postman it works !!
The reason for that is this request from the browser is not including the Authorization header, unlike postman.
I really don't understand why the browser is not including the Authorization header.
Can someone explains ?
NOTE: At first it was working using browser without any problems but suddenly it appeared somehow.
Since the private endpoint requires authentication, whenever I try to access the private end point this function is called:
<code>def get_token_auth_header():
    """Obtains the access token from the Authorization Header
    """
    auth = request.headers.get("Authorization", None) # HERE IS THE PROBLEM OCCURRS
    print("REQUEST HEADERS: \n", request.headers)
    if not auth:
        raise AuthError({"code": "authorization_header_missing",
                        "description":
                            "Authorization header is expected"}, 401)

    parts = auth.split()

    if parts[0].lower() != "bearer":
        raise AuthError({"code": "invalid_header",
                        "description":
                            "Authorization header must start with"
                            " Bearer"}, 401)
    elif len(parts) == 1:
        raise AuthError({"code": "invalid_header",
                        "description": "Token not found"}, 401)
    elif len(parts) > 2:
        raise AuthError({"code": "invalid_header",
                        "description":
                            "Authorization header must be"
                            " Bearer token"}, 401)

    token = parts[1]
    return token
</code>
I have been struggling with this for almost two weeks, I tried everything.
I would really appreciate your help.
Comment: Was it printing the Authorization in the headers. See [this](https://stackoverflow.com/questions/13387516/authorization-header-missing-in-django-rest-framework-is-apache-to-blame) maybe it is happening with flask too.
Comment: @charchit Unfortunately It did not solve my problem
Answer: I'm copying here the same answer I provided in the community forum in case you still need it ;)
It seems you are missing the authlib configuration ;)
You can see here how to configure that and use it on your app


How to convert coordinates in Unity?

Question: I have a JSON file with coordinates where (0.0) is at top left corner (first picture). In Unity (0.0) is at the center of the screen (second picture). I am looking for a way where I can convert my file's coordinates to Unity coordinates.

So my question is how can I convert the coordinates from the first picture to Unity Coordinates?
For example at position (2.3) I have letter 'A'. How to convert it to match with Unity?
I have already tried Camera.main.ScreenToWorldPoint but I always get the same result for all of the inputs.
This is what I get:
Comment: Yes I am getting the width and height of the board.
Comment: Yes camera at (0,0). From the first pair of images, if you see (2,3) from the left grid that has the Letter A, and also see (2,3) on the right grid it will be on top right and that is the reason I have this problem.
Comment: Do you know the width and height of the grid you're working with?
Comment: Is your camera in position (0,0)?
Comment: Can you post your current process of transforming the coordinates, expected results for a single letter and actual results for that letter?
Answer: try this python code, or translate it to your language:
def transformXY(x,y, jsonSizeX,jsonSizeY):
  x -= jsonSizeX/2
  y -= jsonSizeY/2
  return x,y

x,y = getDataFromJson(...)
x,y = transformXY(x,y, jsonMaxX, jsonMaxY)
useInUnity(x,y)

Comment: Sorry but this is not clear. Please explain or rewrite your code.
Answer: This should work:
int unityX = -gridWidth/2 + jsonX/gridWidth * gridWidth;
int unityY = gridHeight/2 - jsonY/gridHeight * gridHeight;

Edit:
I just realised you would probably need the position of the center of the tile in your grid. In that case the code above needs some modifications:
float unityX = -gridWidth/2 + jsonX/gridWidth * gridWidth + 0.5f;
float unityY = gridHeight/2 - jsonY/gridHeight * gridHeight - 0.5f;

This will place the objects you're working with in the center of their respective tiles.
Comment: I tried your suggestion but it doesn't seem to work. Not sure if it's something wrong with the gridWidth and gridHeight I am using.
Comment: When you say "doesn't work" what exactly do you mean?
Comment: I am getting different coordinates and letters are placed on wrong position. I added a screenshot of what I am getting until now.
Answer: Simplest way I can think of would be to have an empty GameObject where you want 0,0 to be and then calculate the positions relative to that GameObject
public class CoordinateAdjustment : MonoBehaviour
{
    public GameObject positionAdjustmentGameObject;
    public float cellSize = 1f; // Set to 1f for this example can change to your needs

    public Vector2 GetPosition(int row, int column)
    {
        Vector2 position = new Vector2
        (
            positionAdjustmentGameObject.transform.position.x + (column * cellSize),
            positionAdjustmentGameObject.transform.position.y + (row * cellSize)
        );
        return position;
    }
}

Might need some refining but will work.

How to convert coordinates in Unity?


Is it possible to create a shortcut to a file that is in Google Drive?

Question: I have asked this question so that they can respond that it is possible to create a shortcut for a file that is in the cloud, this access will be created in the device memory, what is the purpose of this: My application has integrated a function to upload a file to the cloud and then run it from a system application like player, gallery, among others, but without having to download anything, but from an application that is installed Installed on the device (nothing external). Thank you very much.
Answer: You may want to check Create a shortcut to a file. As mentioned,

To create a shortcut instead of a file stored in Drive, use the files.create method of the API and make sure you set the MIME type application/vnd.google-apps.drive-sdk. Do not upload any content when creating the file.

However, for Google Drive Android API, you may want to check Creating Files for more information.
Comment: One question: this method creates a shortcut to a gogole drive file in the device memory, right?


Is it OK that my circuit breaker panel does not latch closed

Question: I plan on doing some work and having it inspected.
As part of the work I will be switching some normal breakers to AFCI.
Before I get started I notice my panel does not fully latch closed.
The latch appears to be thin sheet metal that has snapped off.
I am wondering if this is a code violation and something I will have to fix.
If so that might really change my plans as I don't see these latches as being sold separately or meant to be replaced.
My town is on the 2011 NEC.
The breaker panel is a 200A GE catalog # TM3020F
Answer: You should be able to replace the latch
Try using a GE TDL106 to replace the broken latch on your panel, although it's not a Code violation, simply annoying to have the door on a NEMA 1 (indoor) panel floating loose like that.  (Some smaller panels lack a door, even.)


Inaccessible value causing Access violation

Question: I have a program that makes a bike (TObject)
When calling my Create method, I get an access violation error 00453359 and a write of address 00000004.
constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC; // <- Here is the error
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel;

When I watch that line, it says that it is an inaccessible value, as for all the variables there.
Here is the rest of my class:
type
  MyBike = class(TObject)
  private
    fCC, fStroke, fYear, fPrice: Integer; //I will at a later stage use fPrice as a currency
    fName, fModel: string;
  public
    constructor Create(iPrice, iStroke, iYear, iCC: Integer; sName, sModel:
      string);
    function GetValues: string;
  end;

implementation

{ MyBike }

constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC;
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel;
end;

and my main unit:
private
    { Private declarations }
    NewBike : MyBike;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  redtSavedObject: TRichEdit;
  btnClearSavedObject: TButton;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  btnSaveToText.Enabled := False;
  btnSavetodata.Enabled := False;
end;

procedure TForm1.btnSaveasObjectClick(Sender: TObject);
var
  Price, Year, CC, Stroke : Integer;
  Name, Model : String;

begin
  Price := StrToInt(edtPrice.Text); //All of these values are fine
  Year := StrToInt(edtYear.Text);
  CC := StrToInt(edtCC.Text);
  Stroke := StrToInt(edtStroke.Text);
  Name := edtName.Text;
  Model := edtModel.Text;

  NewBike.Create(Price, Stroke, Year, CC, Name, Model);

I looked at this post: Delphi strange inaccessible value (acess violation) o.O and says I must edit the project settings to:
Debug info: ON
Local Symbols: ON
Optimization: OFF.
Ive done a rebuild, still no change. Ive gone as far as restarting my pc to no avail
Comment: On which line / variable you are getting the error
Comment: `fCC := iCC' in the constructor method in the class
Answer: Change
NewBike.Create(Price, Stroke, Year, CC, Name, Model);

To
NewBike := MyBike.Create(Price, Stroke, Year, CC, Name, Model);

Thats the correct way to mane a new instance of a Class.
When you create an new instance of a class you call then constructor on the Class (MyBike) and assign it's retun value to a variable NewBike := MyBike.Create(...);`
Inside every object (instance of a class) you have a hidden parameter called Self more info on Delphi Basics. The problem in your case was that you didn't create a new instance of the class and therefor your self variable was nil.
Comment: Thats right, thanks you :)
Comment: You are welcom @AidanQuinn. Please close the question.


Check if checkbox is checked and alert "Hi"

Question: So I have a dropdown list with checkboxes.

     <label
       Item 1
       <input type="checkbox" class="clickable">

     <label
       Item 2
       <input type="checkbox" class="clickable">

     <label
       Item 3
       <input type="checkbox" class="clickable">

     <label
       Item 4
       <input type="checkbox" class="clickable">

     <label
       Item 5
       <input type="checkbox" class="clickable">

     <label
       Item 6
       <input type="checkbox" class="clickable">

I am trying to check if checkbox is checked and just simple text "Hi".
But it doesn't work. I am not sure but I am trying to get all inputs with type="checkbox" and for each checkbox addEventListener on click.
const checkboxes = document.querySelectorAll('input[type="checkbox"]')
for (let i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener("click", function() {
        if (checkboxes[i].checked) {
            alert("Hi")
        }
    })
}

Comment: Your HTML is syntactically invalid. There are missing `>` characters after `label`.
Comment: Your code seems to work fine: https://jsfiddle.net/knoam32g/1/. I wonder if you have alert/popups disabled in your browser? Replace the alert with a `console.log("clicked")`
Comment: good catch @tromgy Fixed here: https://jsfiddle.net/knoam32g/3/
Answer: Add an event listener for the change event. It triggers whenever a checkbox is checked and unchecked. Use this.checked to verify if the checkbox is checked or not. Note that it is safe to use this keyword here because the function in addEventListener is a regular function and not an arrow function.

const checkboxes = document.querySelectorAll('input[type="checkbox"]');

for (let i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener("change", function() {
        if (this.checked) {
            console.log(`Hi from Checkbox #${i + 1}`);
        }
    })
}

       Item 1
       <input type="checkbox" class="clickable">

       Item 2
       <input type="checkbox" class="clickable">

       Item 3
       <input type="checkbox" class="clickable">

       Item 4
       <input type="checkbox" class="clickable">

       Item 5
       <input type="checkbox" class="clickable">

       Item 6
       <input type="checkbox" class="clickable">


Norm of conjugate Hardy operator

Question: For the classical Hardy operator $T\colon \ell^p\to \ell^p \quad (Tx)_n=\frac{1}{n}\sum_{k=1}^n x_k$ or the integral type $S\colon L^p\rightarrow L^p \quad (Sf)(x)=\frac{1}{x}\int_0^x f(t) dt \ \ $ the norm is well known to be $\frac{p}{p-1}$ for $1<p<\infty$.
I did some research but did not find the result for the adjoint operator $T'\colon \ell^p\rightarrow \ell^p \quad (T'x)_n=\sum_{k=n}^{\infty} \frac{x_k}{k}$ or its integral version.
What does adjoint mean in the case of general Banachspaces at all? For $p=2$ it's easy to verify $\langle Hx,y\rangle =\langle x,H'y\rangle$.
Answer: It's the duality braket: if $l$ is a linear map and $x$ a vector we denote $\langle l,x\rangle:=l(x)$.
We can identify an element $l$ of the dual of $\ell^p$ by an element of $\ell^q$ (where $q$ is the conjugate of $p$): define $l_n:=l(e_n)$ where $e_n$ is the sequence whose $n$-th term is $1$ and the others $0$ and check that the sequence $\{l_n\}$ represents $l$.
For the problem, let $x\in\ell^p$ and $y\in \ell^q$. We have
\begin{align}
\langle Tx,y\rangle&=\sum_{n=1}^{+\infty}\frac 1n\sum_{k=1}^nx_ky_n\\
&=\sum_{1\leq k\leq n<\infty}\frac{x_ky_n}n\\
&=\sum_{k=1}^{+\infty}x_k\sum_{n\geq k}\frac{y_n}n\\
&=\langle x,T^*y\rangle,
\end{align}
as wanted (the interversion of the sum is justified by the fact that the sum is absolutely convergent).
Comment: I meant "this form", typo. $T'$ has the same norm as $T$.
Comment: @woucrouc when Mathematica contradicts mathematics, I side with the latter. :) Here's a proof of $\|T^*\|\le \|T\|$ for any operator $T\colon X\to Y$. Take any $\psi \in Y^*$; since $T^*\psi$ is the composition $\psi\circ T$, we have $\|T^*\psi\|\le \|\psi\|\|T\|$. [BTW I use asterisks for dual objects, they are easier on the eyes than primes].
Comment: Thank you! I thought this argument just applied for $p=2$. Does this help in any way with the computation of the norm?
Comment: What do you mean by "norm of the form"? This doesn't mean that $\lVert T' \lVert=\lVert T \lVert$ I guess. My intuition tells me that $\lim_{p\rightarrow \infty} \lVert T' \lVert=\infty$ whereas for $T$ the limit is clearly 1.
Comment: I don't think this is true. I did some computation in Mathematica using the truncated haromonic series $x_k=\frac{1}{k^{1/p}}$: `Table[{p, N[Sum[Sum[1/k^(1 + 1/p), {k, n, 500}]^p, {n, 1, 500}]^(1/p)/
     Sum[1/k, {k, 1, 500}]^(1/p)]}, {p, 1, 5}]`. The result was: `{{1, 1.}, {2, 1.70325}, {3, 2.27878}, {4, 2.75247}, {5, 3.14595}}` which makes something like $\lVert T'\lVert=p$ more plausible.
Comment: Probably I don't understand how the argument applies to spaces without scalar product (as $l^p$ for $p\not = 2$). Can you explain?
Comment: @LeonidKovalev Sorry didn't want to post this as an answer. Your argument obviously doesn't work for $T$ on $l^{\infty}$: $\lVert T\lVert=1$ whereas $\lVert T^* \lVert =\infty$ since for $y=(1,1,\dots)$ we have $(T^* y)_1=\sum_{k=1}^{\infty} \frac{1}{k}$. What am I missing?
Comment: @woucrouc Note the spaces on which these operators act: if $T\colon X\to Y$, then $T^*\colon Y^*\to X^*$.
Comment: Oh yes. But I'm interested in the norm of $T^*$ as a linear operator $l^p \rightarrow l^p$. Is the following correct? I'm interested in the norm of $T^*: l^p\rightarrow l^p$. But this is the same as the norm of $(T^*)^*=T: (l^p)^*\rightarrow (l^p)^*$. But $(l^p)^*\tilde{=} l^{p'}$. This norm is known to be $\frac{p'}{p'-1}=p$. So the answer $\lVert T^* \lVert=p$ is correct.

Norm of conjugate Hardy operator


What tools are used to show a type of convergence is or is not topologizable?

Question: There are many types of convergence. For example,

in measure theory and probability theory, there are many types of convergence of measurable mappings (random variables).
in measure theory and probability theory, there are also many types of convergence of measures (over a sigma algebra, a Borel sigma algebra, or ...).
in topology, there are topology of pointwise convergence and topology of uniform convergence (why?).

For other areas, I believe there exist similar examples. They seem very overwhelming and intimidating (to me at least).
I have seen some discussion on whether there exists a topology or metric or norm such that some type of convergence is consistent wrt them. For example, convergence a.e. is not topologizable, not to mention metrizable or normable.

So I was wondering when studying whether a type of convergence is
topologizable, metrizable, normable, ..., what tools are are used?
Are there some general ways to construct the topologies if they exist?
Do all the instances of a certain convergence type form a
convergence class? or a convergence space? Do those convergence structures have some general ways to tell if a certain type of convergence is topologizable and to construct such a topology if there is one?

Thanks and regards!
Comment: Maybe the conditions I've mentioned in my answer [here](http://math.stackexchange.com/questions/19681/when-is-a-notion-of-convergence-induced-by-a-topology/37643#37643) might be interesting for you.
Answer: The one that I have seen used: in a topological convergence, suppose we have a sequence $(x_n)$ with the following property, for some fixed point $p \in X$:
(*) If every subsequence $x_{n_k}$ of $(x_n)$ has itself a subsequence that converges to $p$,
then $(x_n)$ itself converges to $p$.
(Sketch of proof: suppose $(x_n)$ does not converge to $p$, then there is a neighbourhood of $O$ of $p$ such that no tail of the sequence lies in $O$, or equivalently, for every $k_1$ there exists $k_2 > k_1$ such that $x_{k_2} \notin O$. This allows one to define a subsequence of the original sequence, that lies wholly outside $O$ and so every subsequence of that subsequence also does not converge to $p$. So then the sequence satisfies the negation of the condition (*), so by contrapositive we have shown that (*) holds. )
I believe that in general convergence spaces such convergences (with the condition (*)) are even called topological convergences. [Corrected] The topology of convergence a.e. is in general not a topologisable convergence (it does obey other axioms for a general convergence).
Comment: Thanks! I saw that claim is used to prove convergence a.e. is to topologizable by contradiction. However is it used to prove a type of convergence is topologizable?
Comment: Well, with sequences one cannot in general. It's a bit tricky with sequences, because there can be many topologies that have the same convergence behaviour for sequences, but are different, like the discrete topology on $\mathbb{R}$ and the co-countable topology on the same set. With nets one can hope for a unique topology as topologies *can* be uniquely characterised with nets. And not all topologies can be characterised by sequences.
Comment: I know this is a year old, but I should comment that your last sentence is incorrect.  Convergence in measure is a topological convergence.  It is even a metrizable convergence.  One can use the Ky-Fan metric or the metric described here: http://mathoverflow.net/questions/139113/does-this-metric-have-an-official-name-lévy-metric-ky-fan-metric
Comment: @JasonRute You're quite right: I recalled wrongly: it was the convergence a.e. that I was referring to.
Answer: I was going to post this as comment to Henno Brandsma's answer, but it's a little too long for a comment. Nonetheless, this is a follow-up to his answer. Here's an exercise from Tao's "An Epsilon of Room I: Real Analysis" that uses the characterization:

A sequence $x_{n}$ converges to $x$ in a topological space iff every subsequence has a futher subsequence that converges to $x$.

to show that almost everywhere convergence is not, in general, topologisable.
Let $[0,1]$ be equipped with the usual Lebesgue measure. Then the vector space $L^{\infty}([0,1])$ of essentially bounded functions on $[0,1]$ cannot be given a topological vector space structure in which $f_n \to f$ in this topology precisely when it converges almost everywhere.
His hint is to construct a sequence $f_{n} \in L^{\infty}([0,1])$ which does not convergence pointwise almost everywhere to zero, but such that every subsequence has a futher subsequence that converges almost everywhere to zero.
We can let $f_n$ be the so-called "typewriter sequence" (which we can read about here -- the well known sequence that converges in $L^1$ to zero but not pointwise). It is easy to see that this sequence does not convergence pointwise almost everywhere to zero. In fact, it converges pointwise to zero nowhere. How shall we show that every subsequence of $f_n$ has a further subsequence that converges to $0$ almost everywhere? The pigeonhole principle.
Given some subsequence $f_{n_k}$, here is how we will choose our sub-subsequence. At the first step, partition $[0,1]$ into $[0,0.5]$ and $[0.5,1]$. Now, by the pigeonhole principle, infinitely many of these $f_{n,k}$ have support either inside one of these intervals, or have support on both. If it is the latter, then infinitely many functions have support at $0.5$, and then we can just choose a sub-subsequence of such functions whose support shrinks in measure. Thus, let us suppose that infinitely many functions in our subsequence have support in $[0,0.5]$. We can then divide up $[0,0.5]$ into two subintervals and repeat the process. Without loss of generality, all the functions have support on one of these new subintervals, else we can repeat the argument above if infinitely many have support at a point. Iterating this construction, we choose a sub-subsequence of functions which have support in smaller and smaller nested subintervals, and such a sub-subsequence must convergence almost everywhere to zero.
Comment: Thanks! I am a fan of Tao! Actually I was also wondering [why pointwise convergence and uniform convergence are topologizable](http://math.stackexchange.com/questions/312270/why-are-uniform-and-pointwise-convergences-topologizable).
Comment: I really recommend you read Chapter 1, Section 9 of his "An Epsilon of Room I: Real Analysis", which you can find online. In example 1.9.3 and 1.9.4 he topologizes pointwise and uniform convergence.
Comment: Is it also in his blog?
Comment: He collected his blog posts into a book, and published it free online here: http://terrytao.files.wordpress.com/2010/02/epsilon.pdf . The examples you want are on page 131. It's also published as two books in paper form through AMS, the first one of which is about Real Analysis. I'm currently working through this book for a class and it really is excellent and full of intuition. Worth having on one's shelf.


Automatically search all fields for all models in django admin

Question: I want to be able to search all models for all fields in Django admin, without having to setup ModelAdmin and searchfields individually.
example:
I have all my models in model.py:
# This is an auto-generated Django model module.
from django.db import models

class Diagnosis(models.Model):
    id = models.BigAutoField(primary_key=True)
    code = models.CharField(max_length=255)
    starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis'

    def __str__(self):
        return 'Diag #' + str(self.id) + ' - ' + self.code

class DiagnosisHistory(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=255, blank=True, null=True)
    date = models.DateTimeField(blank=True, null=True)
    id_user = models.TextField(blank=True, null=True)
    report = models.TextField(blank=True, null=True)
    json_report = models.TextField(blank=True, null=True)
    vin = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis_history'

# and so on

and the admin.py where I register the models:
from django.contrib import admin

from . import models

# Do not care. Register everything
for cls in [cls for name, cls in models.__dict__.items() if isinstance(cls, type)]:
    admin.site.register(cls)

I don't want to run through each Model and manually create a ModelAdmin with each field
Answer: This is the solution I came up with:
from django.contrib import admin
from django.db import models as django_models

from . import models

relationship_fields = (django_models.ManyToManyField, django_models.ForeignKey, django_models.OneToOneField)

for cls in [cls for name, cls in models.__dict__.items() if isinstance(cls, type)]:
    meta_fields = [field.name for field in cls._meta.local_fields if not isinstance(field, relationship_fields)]

    class Admin(admin.ModelAdmin):
        search_fields = meta_fields
    admin.site.register(cls, Admin)

Note: registering all fields will fail since some are relationships. using cls._meta.local_fields exclude inferred relationships but you also need to exclude fields such as foreign keys defined in your model. Thus, we filter with isinstance(field, relationship_fields)
Note 2: I should probably use get_fields since local_fields seems to be private API (see https://docs.djangoproject.com/en/3.1/ref/models/meta/)
Answer: class MyModelAdmin(admin.ModelAdmin):
    # ...
    search_fields = [field.name for field in MyModel._meta.fields]
    # ...

Comment: This is all fields for one model. The question is for searching across all models.


How to transfer data between Toplevel widgets (OOP):

Question: I am beginner to Python language !
I designed three windows by three classes.
First window is the main window and it is on the first class.
And the others defined as toplevel widgets by another two classes.
I need to send data which input to the second window (first toplevel widget) and get (view) it from the third window (second toplevel widget).
So, to do that I used the - getattr - function.
But it gaven some (AttributeError) error :

d = self.var1.get()
File "C:\Python\Python310\lib\tkinter_init_.py", line 2383, in getattr
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'var1'

from tkinter import *
import tkinter as tk

class obj_1(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title("TK WINDOW 01")
        self.geometry("300x150+10+10")

        btn_next = tk.Button(self, text="Second Window", width=15, height=1, command=lambda: obj_2())
        btn_next.pack(pady=20)

class obj_2(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)

        self.title("TK WINDOW 02")
        self.geometry("400x100+300+300")

        self.var1 = tk.StringVar()

        btn_next = tk.Button(self, text="-->", width=15, height=1, command=lambda: obj_3())
        btn_next.pack()

        self.lbl_ent_1 = tk.Entry(self, textvariable=self.var1, width=15)
        self.lbl_ent_1.pack(pady=20)

        self.lbl_ent_1.focus()

    def get_from_second(self):
        d = self.var1.get()
        return d

class obj_3(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)

        self.title("TK WINDOW 03")
        self.geometry("400x100+800+300")

        self.var2 = tk.StringVar()

        btn_view = tk.Button(self, text="View", width=15, height=1, command=lambda: self.get_from_third())
        btn_view.pack()

        self.lbl_vw = tk.Label(self, textvariable=self.var2, width=15, height=1, pady=20)
        self.lbl_vw.pack()

    def get_from_third(self):
        p = getattr(obj_2, 'get_from_second')(self)

        self.var2.set(p)
        print(p)

if __name__ == '__main__':
    app = obj_1()
    app.mainloop()

Comment: avoid using (a wildcard) `from tkinter import *` .  Prefer to use this (an alias) `import tkinter as tk` which is clearer...  dont use both together !!
Comment: You are creating two different instances of `Tk` (technically, two subclasses), which is not how tkinter is designed to work.
Comment: As `obj_2` and `obj_3` inherit from `tk.Tk`, why do you call `tk.Toplevel.__init__(...)` inside `obj_2.__init__()` and `obj_3.__init__()`?
Comment: @acw1668 : I need to make depend obj_2() and obj_3() on first window.
Comment: @sonny What I mean is that you should call `tk.Tk.__init__(...)` instead because they inherit from `tk.Tk`.  Or it is better to change them to inherit from `tk.Toplevel`.
Comment: @acw1668  :  Please sir, can you rewrite the coding part !
Answer: I commented the changes where they were made, but in short: you had the wrong super for both of your toplevel windows, with the proper super you get a master to refer to. Too much juggling (C from A from B). My example is direct (B from A) then (C from A). You don't even need the get_from_second because it has been obsoleted by a virtual get_directly_from_root. In other words, store your var on the root and then refer to it via master.
from tkinter import *
import tkinter as tk

class obj_1(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title("TK WINDOW 01")
        self.geometry("300x150+10+10")

        btn_next = tk.Button(self, text="Second Window", width=15, height=1, command=lambda: obj_2(self))
        btn_next.pack(pady=20)

        self.var1 = tk.StringVar() #store the var on the master

class obj_2(tk.Toplevel): #Toplevel not Tk
    def __init__(self, master, *args, **kwargs): #master will be your main Tk window
        tk.Toplevel.__init__(self, master, *args, **kwargs)

        self.title("TK WINDOW 02")
        self.geometry("400x100+300+300")

        btn_next = tk.Button(self, text="-->", width=15, height=1, command=lambda: obj_3(master))
        btn_next.pack()

        self.lbl_ent_1 = tk.Entry(self, textvariable=master.var1, width=15) #<--var from master
        self.lbl_ent_1.pack(pady=20)

        self.lbl_ent_1.focus()

class obj_3(tk.Toplevel): #Toplevel not Tk
    def __init__(self, master, *args, **kwargs): #master will be your main Tk window
        tk.Toplevel.__init__(self, master, *args, **kwargs)

        self.title("TK WINDOW 03")
        self.geometry("400x100+800+300")

        self.var2 = tk.StringVar()

        btn_view = tk.Button(self, text="View", width=15, height=1, command=lambda: self.get_from_third())
        btn_view.pack()

        self.lbl_vw = tk.Label(self, textvariable=self.var2, width=15, height=1, pady=20)
        self.lbl_vw.pack()

    def get_from_third(self):
        self.var2.set(self.master.var1.get())

if __name__ == '__main__':
    app = obj_1()
    app.mainloop()

I left your code mostly in tact but consider the below. Your button is entirely unnecessary, you can just automatically have the data by sharing var1 from master.

class obj_3(tk.Toplevel): #Toplevel not Tk
    def __init__(self, master, *args, **kwargs): #master will be your main Tk window
        tk.Toplevel.__init__(self, master, *args, **kwargs)

        self.title("TK WINDOW 03")
        self.geometry("400x100+800+300")

        self.lbl_vw = tk.Label(self, textvariable=master.var1, width=15, height=1, pady=20)
        self.lbl_vw.pack()

Aside: All this obj_x naming is very poor practice. Give your classes meaningful names that give an indication of what they do. The same goes for varx, and any other name you make which is entirely arbitrary. Imagine if tkinter named everything Widget1, Widget2, etc...How could you possibly work with that? The same goes for your code. You keep naming everything arbitrarily and you wont be able to work with your own code.
What is vw in self.lbl_vw? VariableWindow, perhaps? That sounds like a great name for that class. While you're at it, stop naming your classes with definition syntax. Even if you kept the poor obj_x naming it should still, at least, be: Obj_x.
Not really a question:
Why are you opening a 3rd window to display a variable that was just typed, and why would you have to click a button to see it? Again, I'm not really asking this. I want you to ask yourself that. Now that I've boiled your code down to one var, your app doesn't make any sense in design. Your app is currently 3 entire windows built around 1 variable. It's probably time to reconsider what it is you are actually trying to do.
Imagine if you opened your browser, had to click a search button which opens up a query window, and then click another button which opens ANOTHER window with the page in it. It looks like you are essentially building that. It's a bad design.


Turning off warning messages in GDB

Question: I am writing a script that runs GDB and a series of GDB commands.
One of my commands file myfile.elf generates warning messages;
warning: Loadable segment ".func_addrs" outside of ELF segments
warning: Loadable segment ".aux_info" outside of ELF segments

I have tried using the set verbose off command in GDB to try to turn these off but it didn't work.
Does anyone know how I can stop these messages?
Thanks!
Answer: There isn't a way to do this in gdb.
You can disable all output using "set logging".
Or you could redirect it to a file, then grep out the offending lines, displaying the rest.
Answer: You should be able to suppress the warning messages by simply redirecting stderr to the bit bucket.
Just add 2>/dev/null onto the end of your gdb command.
For example:
gdb -p [Process ID] 2>/dev/null

At least this worked for the warning messages that I was encountering!

Turning off warning messages in GDB


Sometimes my monitors stop working an my Dell Precision with Ubuntu 20.04

Question: I have an Ubuntu 20.04 running on a Dell Precision, to which I have connected two Samsung monitors S27H850QFU connected through a HDMI to USB-C converter. It's not exactly a HDMI to USB-C converter since has 3 inputs (HDMI, USB-C and USB 3.0) and one output (USB-C) which I connect to the laptop.
Just to clarify, I have two of these 'hubs/converters' connected to two of my laptop's USB-C ports.
The problem is that sometime, when I boot, I find a combination of the following problems with the monitors:

One of them doesn't come up.
One of them doesn't show all the resolutions that should be available. For instance, I see 1920x1080 as the maximum resolution  while the maximum is 2560x1440.
Sometimes I just turn off one of the monitors, but I still have the problem above.
Sometimes the problem gets fixed by unplugging/plugging one or both monitors. Sometimes it doesn't.
Sometimes I have one monitor plugged and working fine and, when connecting the second one, one or more of the above problems happen.

Generally, I need to reboot one or more times until the above gets fixed (that is, I have (at least) one monitor with the maximum resolution available)
I'm using the Intel Corporation UHD Graphics driver:
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics (rev 05)
    Subsystem: Dell Device 097e
    Kernel driver in use: i915

I have listed the available resolutions when the problem is happening:
> xrandr

Screen 0: minimum 8 x 8, current 1680 x 1050, maximum 32767 x 32767
eDP-1-1 connected (normal left inverted right x axis y axis)
   1920x1200     59.95 +  59.88    47.96
   1920x1080     60.01    59.97    59.96    59.93
   1600x1200     60.00
   1680x1050     59.95    59.88
   1600x1024     60.17
   1400x1050     59.98
   1600x900      59.99    59.94    59.95    59.82
   [...]
DP-1-1 connected primary 1680x1050+0+0 (normal left inverted right x axis y axis) 597mm x 336mm
   1920x1080     60.00    50.00    59.94
   1680x1050     59.88*
   1600x900      60.00
   1280x1024     75.02    60.02
   1440x900      59.90
   1280x800      59.91
   1152x864      75.00
   1280x720      60.00    59.94
   1024x768      75.03    70.07    60.00
   832x624       74.55
   800x600       72.19    75.00    60.32    56.25
   720x576       50.00
   720x480       60.00    59.94
   640x480       75.00    72.81    66.67    60.00    59.94
   720x400       70.08
DP-1-2 connected (normal left inverted right x axis y axis)
   2560x1440     59.95 +
   1920x1080     60.00    50.00    59.94
   1680x1050     59.88
   1600x900      60.00
   1280x1024     75.02    60.02
   1440x900      59.90
   1280x800      59.91
   1152x864      75.00
   1280x720      60.00    59.94
   1024x768      75.03    70.07    60.00
   832x624       74.55
   800x600       72.19    75.00    60.32    56.25
   720x576       50.00
   720x480       60.00    59.94
   640x480       75.00    72.81    66.67    60.00    59.94
   720x400       70.08
DP-1-3 disconnected (normal left inverted right x axis y axis)

DP-1-1 and DP-1-2 are the monitos, Screen 0 is the laptop one. I don't know what DP-1-3 is.
I have tried as well to set the resolutions through the terminal:
  1 #!/bin/bash
  2 # script name: monitors.sh
  3 xrandr --output DP-1-1   --mode 2560x1440 --right-of   DP-1-2
  4 xrandr --output DP-1-2   --mode 2560x1440 --left-of  DP-1-1

and, when executing it, I get:
bash ./monitors.sh
xrandr: cannot find mode 2560x1440

I have observed that, after trying to plug in the second monitor and having the error, and recovering by unplugging it, I see 'ghost' devices in xrandr:
Screen 0: minimum 8 x 8, current 2560 x 1440, maximum 32767 x 32767
eDP-1-1 connected (normal left inverted right x axis y axis)
[...]
DP-1-1
[...]
DP-1-2 disconnected (normal left inverted right x axis y axis)
DP-1-3 disconnected (normal left inverted right x axis y axis)

I have tried to remove DP-1-2 and DP-1-3 to see if that is the problem, but neither xrandr --rmmode nor xrandr --delmode can do it.
Comment: Sounds like the ports have border line power to run the 2 monitors.
Answer: I have fixed the problem but attaching both monitors to a dock station through HDMI and mini DisplayPort respectively, and authorizing the dock station from Ubuntu. I imagine my previous adapters weren't very good.
Comment: So, nothing to do with Ubuntu.
Comment: It has all to do with Ubuntu. If I use two HDMIs in either Mac or Windows, all works without no problem (no way this happens on Ubuntu). In addition, both OS' perfectly remember the monitor configuration, so I don't need to re config it all the time.
Comment: *I imagine my previous adapters weren't very good.* enough said.
Comment: I repeat, I have tried both adapters on a Mac with a dockstation and they work....
Comment: And I repeat: Unless you test the same peripherals in the same computer with a different OS and confirm they work as expected, the OS is unrelated, immaterial and irrelevant. That the same peripherals work in a totally different computer is also unrelated, immaterial and irrelevant. Troubleshooting 101. End of story.


Navigation of items in a list

Question:
I have 15 items in a list
I have 10 such lists
Each list SHOULD OCCUPY at most 1 row on the page
Overflow items should be navigated via "NEXT" or "PREV" button.
For displaying items in each list, I "float:left".
But then the overflow items wrap to next row.

For now, I am doing a hack for my laptop screen size:

I .hide() all items at window load for each list
Then .show() first 4 items for each list
I have configured next and prev buttons accordingly.

I am positive this is wrong. But it enabled me to see how the look and feel is of what I wanted to do.
Please suggest me the correct approach. All major websites handle this. This is very common problem. I am just ignorant for now.
Comment: We should not *overuse* our ability to down vote somebody. It is plain wrong.
Answer: The easiest way to achieve this is probably:

Don't use float:left, just use regular inline display.
For the container element, use overflow:hidden.
Wrap the container element in an outer container, also with overflow:hidden.
Now, when the user clicks next/prev, adjust/animate the margin of the inner container, so that it slides across to reveal the other elements.
Comment: How would I know that I have reach the last element? In the beginning I dont know how many items were displayed...so I can not maintain a counter
Comment: I want to maintain a circular sliding effect. How can I do that with this approach?
Comment: @gauravjain what do you mean circular sliding?
Comment: 1 2 3 4 5 (next click) 2 3 4 5 1 (next click) 3 4 5 1 2 (next click) 4 5 1 2 3 ( and so on). Its like a loop
Comment: with the above you suggested, I keep moving left and once I reach end of list, it shows blank spaces...which I did not like...
Answer: I think I solved the problem by another SO response:
How to move first child to the end?
Thanks for all your help
Comment: To be complete, to do the reverse, use prepend on the last element of the collection

Navigation of items in a list