text:
Q: How to pass unit of work container into constructor of repository using dependency injection I'm trying to work out how to complete my implementation of the Repository pattern in an ASP.NET web application.
At the moment, I have a repository interface per domain class defining methods for e.g. loading and saving instances of that class.
Each repository interface is implemented by a class which does the NHibernate stuff. Castle Windsor sorts out the DI of the class into the interface according to web.config. An example of an implemented class is provided below:
  public class StoredWillRepository : IStoredWillRepository
  {
    public StoredWill Load(int id)
    {
      StoredWill storedWill;
      using (ISession session = NHibernateSessionFactory.OpenSession())
      {
        storedWill = session.Load<StoredWill>(id);
        NHibernateUtil.Initialize(storedWill);
      }
      return storedWill;
    }

    public void Save(StoredWill storedWill)
    {
      using (ISession session = NHibernateSessionFactory.OpenSession())
      {
        using (ITransaction transaction = session.BeginTransaction())
        {
          session.SaveOrUpdate(storedWill);
          transaction.Commit();
        }
      }
    }
  }

As pointed out in a previous thread, the repository class needs to accept an unit of work container (i.e. ISession) rather than instantiating it in every method.
I anticipate that the unit of work container will be created by each aspx page when needed (for example, in a property).
How do I then specify that this unit of work container instance is to be passed into the constructor of StoredWillRepository when Windsor is creating it for me?
Or is this pattern completely wrong?
Thanks again for your advice.
David

A: I have a persistence framework built on top of NHibernate that is used in a few Web apps. It hides the NH implementation behind an IRepository and IRepository<T> interface, with the concrete instances provided by Unity (thus I could in theory swap out NHibernate for, say, Entity Framework fairly easily).
Since Unity doesn't (or at least the version I'm using doesn't) support the passing in of constructor parameters other than those that are dependency injections themselves, passing in an extant NH ISession isn't possible; but I do want all objects in the UOW to share the same ISession.
I solve this by having a controlling repository class that manages access to the ISession on a per-thread basis:
    public static ISession Session
    {
        get
        {
            lock (_lockObject)
            {
                // if a cached session exists, we'll use it
                if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
                {
                    return (ISession)PersistenceFrameworkContext.Current.Items[NHibernateRepository.SESSION_KEY];
                }
                else
                {
                    // must create a new session - note we're not caching the new session here... that's the job of
                    // BeginUnitOfWork().
                    return _factory.OpenSession(new NHibernateInterceptor());
                }
            }
        }
    }

In this example, PersistenceFrameworkContext.Current.Items accesses an IList<object> that is stored either ThreadStatic if not in a Web context, or within HttpContext.Current.Items if it is in a Web context (to avoid thread-pool problems). The first call to the property instantiates the ISession from the stored factory instance, subsequent calls just retrieve it from storage. The locking will slow things down slightly but not as much as just locking an appdomain-scoped static ISession instance.
I then have BeginUnitOfWork and EndUnitOfWork methods to take care of the UOW - I have specifically disallowed nested UOWs because frankly they were a pain to manage.
    public void BeginUnitOfWork()
    {
        lock (_lockObject)
        {
            if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
                EndUnitOfWork();

            ISession session = Session;
            PersistenceFrameworkContext.Current.Items.Add(SESSION_KEY, session);
        }
    }

    public void EndUnitOfWork()
    {
        lock (_lockObject)
        {
            if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
            {
                ISession session = (ISession)PersistenceFrameworkContext.Current.Items[SESSION_KEY];
                PersistenceFrameworkContext.Current.Items.Remove(SESSION_KEY);
                session.Flush();
                session.Dispose();
            }
        }
    }

Finally, a pair of methods provide access to the domain-type-specific repositories:
    public IRepository<T> For<T>()
        where T : PersistentObject<T>
    {
        return Container.Resolve<IRepository<T>>();
    }

    public TRepository For<T, TRepository>()
        where T : PersistentObject<T>
        where TRepository : IRepository<T>
    {
        return Container.Resolve<TRepository>();
    }

(Here, PersistentObject<T> is a base class providing ID and Equals support.)
Access to a given repository is thus in the pattern
NHibernateRepository.For<MyDomainType>().Save();

This is then facaded over such that you can use
MyDomainType.Repository.Save();

Where a given type has a specialised repository (ie needs more than it can get from IRepository<T>) then I create an interface deriving from IRepository<T>, an extending implementation inheriting from my IRepository<T> implementation, and in the domain type itself I override the static Repository property using new
    new public static IUserRepository Repository
    {
        get
        {
            return MyApplication.Repository.For<User, IUserRepository>();
        }
    }

(MyApplication [which is called something less noddy in the real product] is a facade class which takes care of supplying the Repository instance via Unity so you have no dependency on the specific NHibernate repository implementation within your domain classes.)
This gives me full pluggability via Unity for the repository implementation, easy access to the repository in code without jumping through hoops, and transparent, per-thread ISession management.
There's lots more code than just what's above (and I've simplified the example code a great deal), but you get the general idea.
MyApplication.Repository.BeginUnitOfWork();
User user = User.Repository.FindByEmail("wibble@wobble.com");
user.FirstName = "Joe"; // change something
user.LastName = "Bloggs";
// you *can* call User.Repository.Save(user), but you don't need to, because...
MyApplication.Repository.EndUnitOfWork();
// ...causes session flush which saves the changes automatically

In my Web app, I have session-per-request, so BeginUnitOfWork and EndUnitOfWork get called in BeginRequest and EndRequest respectively.

A: I have a pretty similar structure to yours, and here's how I solve your question:
1) To specify my container on each method, I have a separate class ("SessionManager") which I then invoke via a static property. By doing so, here's an example using my Save implementation:
private static ISession NHibernateSession
{
    get { return SessionManager.Instance.GetSession(); }
}

public T Save(T entity)
{
    using (var transaction = NHibernateSession.BeginTransaction())
    {
        ValidateEntityValues(entity);
        NHibernateSession.Save(entity);

        transaction.Commit();
    }

    return entity;
}

2) My container is not created on each ASPX page. I instantiate all of my NHibernate goodness on the global.asax page.
** A few more things spring up **
3) You don't need to have a helper to instantiate the Load. You might as well use Get instead of Load. More information @ Difference between Load and Get.
4) Using your current code, you would have to repeat pretty much the same code for each domain object you need (StoredWillRepository, PersonRepository, CategoryRepository, etc..?), which seems like a drag. You could very well use a generic class to operate over NHibernate, like:
public class Dao<T> : IDao<T>
{
    public T SaveOrUpdate(T entity)
    {
        using (var transaction = NHibernateSession.BeginTransaction())
        {
            NHibernateSession.SaveOrUpdate(entity);
            transaction.Commit();
        }

        return entity;
    }
}

In my implementation, I could then use something like:
Service<StoredWill>.Instance.SaveOrUpdate(will);

A: Technically, the answer to my question is to use the overload of container.Resolve which allows you to specify the constructor argument as an anonymous type:
IUnitOfWork unitOfWork = [Code to get unit of work];
_storedWillRepository = container.Resolve<IStoredWillRepository>(new { unitOfWork = unitOfWork });

But let's face it, the answers provided by everyone else have been much more informative.


text:
Q: How to force Maven to download maven-metadata.xml from the central repository? What I want to do is to force Maven to download the 'maven-metadata.xml' for each artifact that I have in my local repository.
The default Maven behaviour is to download only metadata from remote repositories (see this question).
Why I want to do that:
Currently I have a remote repository running in a build machine. By remote repository I mean a directory located in the build machine that contains all dependencies that I need to build my Maven projects. Note that I'm not using a repository manager like Nexus, the repository is just a copy of a local repository that I have uploaded to my build machine.
However, since my local repository did not contain the 'maven-metadata.xml' files, these metadata files are also missing in the build machine repository. If I could retrieve the metadata files from the central repository, then it would be possible to upload a working remote repository to my build machine.

A: You don't want to get the metadata from the public repositories, it will contain all the versions available of a given artifact, whereas your repository will have some subset of the releases.
It's worth pointing out that you really would be better off with a repository manager. The following steps allow you to generate your artifact metadata once. But if your needs change, you'll have to repeat the process or update the files manually, so why not just use a manager? Nexus can run standalone and has a very small footprint.

Even if you're not planning on using Nexus for a repository manager, you can still use it to generate your metadata.

*

*First install Nexus.

*Locate the nexus work directory (by default ${user.home}/sonatype-work.

*Copy your local repository contents to the nexus-work/releases sub-directory.

*Start Nexus and connect to the Nexus home page in the browser (by default http://localhost:8081/nexus)

*Log in using the admin account (password admin123)

*Click on the repositories link on the left hand side.

*Select the Releases repository, right-click and click Rebuild Metadata
In a few moments you should have the metadata generated for all the artifacts. You can then copy them to wherever you need them to be and uninstall Nexus.

A: The default repositories are defined in the super pom.xml that all poms inherit from by default.
If by local you mean you want to only use ~/.m2/repos/* then work in offline mode. Add  <offline>true</offline> to your settings.xml
If by local you mean your local server, you could install a repository manager like Nexus, modify your settings file to use nexus under "mirrors" like this:
<mirror>
  <id>central-proxy</id>
  <mirrorOf>central</mirrorOf>
  <url>my/local/nexus/server</url>
</mirror>

And disable remote repositories you don't want in Nexus.

A: One thing I found is someone was doing an initial search of jarvana and had placed this within the pom, causing a metadata error message to occur.  This ...
   <!-- <repository>
        <id>jarvana</id>
        <url>http://www.jarvana.com/jarvana/browse/</url>
    </repository> -->

..fixed it and the error went away.

A: Repository manager is great but I don't want install and run it on my laptop. I just want to save resource.
So, my solution is below:

*

*install repository as artifactory (https://www.jfrog.com/artifactory)

*run materialize thru this server (localhost:8081)

*run materialize thru remote server (center.maven.org)

*download cache content of artifactory

*merger to folder: folder download from step 4 and folder at ~/.m2/repository.

Now I have a repository offline with full content (binary, source, xml, md5, sha1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rule clarification for Enlightened badge (again, I know) I know that this very question was asked before (more than once), but the answers don't apply here.
This answer was the first and only one given, was accepted with 10 votes, but didn't result in the badge being awarded.
The only reason I can see is that the answer needs to be accepted after it gets 10 votes. Is that so?


text:
Q: Remove unlimited amounts of text between two text values I'm using the following code to delete text between a range of characters.
However, when I try to delete multiple paragraphs of text, I receive the following error:

Index (548) must be less than the content length (377). (line 195, file "")

How I can remove unlimited amounts of text between two text values?
function removeCbSevHD1(X) {
    var rangeElement1 = DocumentApp.openById(X).getBody().findText('<CS1>');
    var rangeElement2 = DocumentApp.openById(X).getBody().findText('<CS2>');
    Logger.log(rangeElement1.getElement());
    if (rangeElement1.isPartial()) {
        var startOffset = rangeElement1.getStartOffset();
        var endOffset = rangeElement2.getEndOffsetInclusive();
        rangeElement1.getElement().asText().deleteText(startOffset,endOffset);}
    }
}

A: Expanding on my answer to your previous question, you cannot select from the beginning of one range to the end of another range. That is what the if (element.isPartial()) { ... } else { ... } condition is for. If the range is the entire element, it will remove the whole element.
If you want to remove multiple ranges, then you have to remove one at a time.
In the following example I do this by looping through an array of search strings and applying the function to each.
function removeCbSevHD1(X) {
    // If you want to add more things to match and remove, add to this array
    var search = /<CS1>.*<CS2>/;
    var rangeElement = DocumentApp.openById(X).getBody().findText(search);
    if (rangeElement.isPartial()) {
        var startOffset = rangeElement.getStartOffset();
        var endOffset = rangeElement.getEndOffsetInclusive();
        rangeElement.getElement().asText().deleteText(startOffset,endOffset);
    } else {
        rangeElement.getElement().removeFromParent();
    }
}

Note: Not tested.

A: Tiny G! Thanks for all the help man.
I was able to find some help. Here's the answer:
function removeSection3(X) {
for (var i = 1; i <= 7; i++) {
var search = '<ZY' + i + '>';
var rangeElement = DocumentApp.openById(X).getBody().findText(search);
if (rangeElement) {
  rangeElement.getElement().getParent().removeFromParent();
}

}
}


text:
Q: How do I use py32win to automate opening powerpoint files with password? For work, I need to convert all ppt/pptx and doc/docx files in a given folder and convert them to pdf. However, some of the files are password protected. So far I have this code:
import os
import win32com
import win32com.client

print("Please set the directory you want to scrape files from:")
FOLDER_PATH = input()

def PPTtoPDF(inputFileName, outputFileName, formatType=32):
    powerpoint = win32com.client.Dispatch("Powerpoint.Application")
    if inputFileName[-3:] == "ppt":
        outputFileName = outputFileName[:-4] + ".pdf"
    if inputFileName[-4:] == "pptx":
        outputFileName = outputFileName[:-5] + ".pdf"
    if (inputFileName[-3:] == "ppt") | (inputFileName[-4:] == "pptx"):
        try:
            deck = powerpoint.Presentations.Open(inputFileName, WithWindow=False)
            deck.SaveAs(outputFileName, formatType)  # formatType = 32 for ppt to pdf
            deck.Close()
            os.remove(inputFileName)
        except:
            print("PPT2PDF: There's an error" + inputFileName)

After that I have another function that grabs the filenames from the directory I've set, put it into a list, and then loops through the list to run the PPTtoPDF function.
The above function works, but I have to input the password manually every time there's a password-protected document.
I have tried the following fixes:
deck = powerpoint.Presentations.Open(inputFileName, WithWindow=False, Password="password1234")

But this turns an error:
TypeError: Open() got an unexpected keyword argument 'Password'

A similar error also often happens with the WithWindow argument, and I don't know why that is. Sometimes it works, sometimes it doesn't.
I have also tried
deck = powerpoint.Presentations.Open(inputFileName, False, True, None, "password1234")

which was suggested in How to open a password protected excel file using python?
But it returns the following error:
TypeError: Open() takes from 1 to 5 positional arguments

I'm not sure what went wrong. Coding is definitely not my expertise, and the documentation for py32win seems to be scarce and very technical. Any help/suggestion is appreciated.
Thanks!


text:
Q: Codeigniter: SMTP mail not working I'm trying to set up a contact form, and I'm struggling to get it working with the SMTP configuration in CI. However I've successfully tried with the basic 'mail' config.
To cut it short, I'm doing my tests with this simple code:
    $config = array(
        'protocol' => 'smtp',
        'smtp_host' => 'smtp.1and1.es',
        'smtp_port' => 25,
        'smtp_user' => 'user@mysite.com',
        'smtp_pass' => '********',
        'mailtype'  => 'text',
        'charset'   => 'utf-8',
        'wordwrap'  => true,
        'wrapchars' => 50
    );

    $this->load->library('email');
    $this->email->initialize($config);

    $this->email->from('my_real_email_address@gmail.com');
    $this->email->to('my_real_email_address@gmail.com');
    $this->email->reply_to('my_real_email_address@gmail.com', 'John Doe');
    $this->email->subject('Message sent from the contact form in website');
    $this->email->message('Body of message...');

    if ($this->email->send()) {
            return true;
    }
    echo '<!--' . print_r($this->email->print_debugger(), true) . '-->';
    return false;

I've just asked my hosting provider and all the SMTP config is correct. They've also checked my e-mail account is working properly.
In fact if I choose:
protocol => 'mail'
the message is delivered without problems. AFAIK the php mail() function also uses the hosting provider SMTP but it simply hands it over to the server and forgets it.
Instead I'd like to use SMTP authentication, which worries about the dispatch of the e-mail. But only by changing
protocol => 'smtp'
when I send the form there's a lot of processing time and I finally get this debugging message:
220 smtp.1and1.es (mreu2) Welcome to Nemesis ESMTP server

hello:  The following SMTP error was encountered:
Failed to send AUTH LOGIN command. Error: 421 smtp.1and1.es connection timed out

from:  The following SMTP error was encountered:
to:  The following SMTP error was encountered:
data:  The following SMTP error was encountered:

The following SMTP error was encountered:
Unable to send email using PHP SMTP.  Your server might not be configured to send mail using this method.
User-Agent: CodeIgniter
Date: Thu, 24 Jan 2013 18:51:31 +0100
From: <my_real_email_address@gmail.com>
Return-Path: <my_real_email_address@gmail.com>
To: my_real_email_address@gmail.com
Reply-To: "John Doe" <my_real_email_address@gmail.com>
Subject: =?utf-8?Q?Message_sent_from_the_contact_form_in_website?=
X-Sender: my_real_email_address@gmail.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <510174a33158d@gmail.com>
Mime-Version: 1.0

Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit

Body of message...

What might be the reason of this error?

A: Some have reported having an issue with a config item having single quotes:
$config['crlf'] = '\r\n';      //should be "\r\n"
$config['newline'] = '\r\n';   //should be "\r\n"

I'm pretty certain protocol => mail does not use your provider -- it will send the email directly from your server.
If it's not the single quote issue, it might be an issue with incorrect credentials, firewall or connection requirement (say if your email provider requires TLS/SSL).
Try connecting to the mail server and send an email with another client (you could use telnet: http://www.wikihow.com/Send-Email-Using-Telnet or thunderbird or somesuch) to verify the protocols are correct.


text:
Q: How to describe charge density waves in k-space? I am reading this article about variational ground state wavefunction. In equation 10 they said that charge density wave (CDW) for spinless fermionic system at half-filling can be written as following:
$$|CDW\rangle=\prod_{k\epsilon RBZ} \frac{1}{\sqrt2} (c_k^\dagger+c_{k+\pi}^\dagger) |0\rangle$$
According to article charge density wave is alternating occupied and empty sites.
I can't understand how this equation is representing CDW. Can someone please give me little explanation of this equation? What is meaning of $c_{k+\pi}^\dagger$ ? Or any reference regarding this CDW equation?

A: I believe this argument is due to Peierls...
A breaking of a lattice symmetry $\mathbb{Z}$ down to a subgroup $n \mathbb{Z}$ is equivalent to changing the periodicity of $k$ from $2\pi$ to $2\pi/n$. This means that each of the original bands wraps the new Brillouin zone $n$ times, causing some bands to intersect each other. Then interactions among the new bands will generically separate these crossings yielding a band structure which cannot be unwound back to a $2\pi$ periodic one.
In particular an $n=2$ CDW comes from an interaction between $k$-points separated by $\pi$ momentum in the original band structure, but which sit right on top of each other in the $\pi$-periodic Brillouin zone. A ground state like the one you wrote is exactly the sort of wavefunction that will appear in this case. Your product is over the reduced Brillouin zone ($\pi$-periodic) and says that particle modes at $k$ and $k+\pi$ are phase-locked. It's easy to see that the unit translation does not preserve the state you wrote down because it messes up the phases:
$$c_k^\dagger + c_{k+\pi}^\dagger \mapsto e^{i k} c_k^\dagger - e^{ik} c_{k+\pi}^\dagger$$
but if we do it twice we get
$$c_k^\dagger + c_{k+\pi}^\dagger \mapsto e^{2 i k} c_k^\dagger + e^{2 ik} c_{k+\pi}^\dagger$$


text:
Q: How to model array of key/value pairs We are using ClickHouse to store internal performance metrics for webpage loads. Each metric contains an array of key/value pairs for custom load times they care about. We'd like to store these in ClickHouse and be able to query the times like any other time value.
For example, when I get a metric, along with all the standard data I may have data that gives me the load time for a bunch of custom stuff, like this:
TimeStamp=1548268715
CustomEvents="a=10,b=20,c=30"

In this case, I want to store the values a=10, b=20, and c=30 in such a way that:

*

*It's still tied to the original data (so I can filter by timestamp, any other field, etc.).

*I can aggregate and query specific "custom events." For example, I may want to do a histogram on all a time values between certain dates.

The challenge is that I don't know in advance which custom events exist. I suppose I could white-list these, but the number of them may become very large, and the cardinality of custom events is very high.
I'd appreciate any thoughts on this. I've got a few ideas, but wouldn't mind any thoughts.

A: The standard approach for that in ClickHouse is using Nested structures and select from that using ARRAY JOIN.
Under the hood Nested field in ClickHouse is just a group of arrays of the same length.
Sample:

*

*Create the table like that
CREATE TABLE performance_metrics
(
    timestamp DateTime,
    website String,
    custom_events Nested (
        metric String,
        value UInt64  -- actually you can have more attributes here, if needed
    )
)
ENGINE = MergeTree
PARTITION BY toMonday(timestamp)
ORDER BY (website, timestamp);

*Put the data, referencing Nested subfields as multiple arrays. Names of those arrays should be prefixed by Nested name, and length should be the same:
INSERT INTO performance_metrics (timestamp, website, custom_events.metric, custom_events.value)  VALUES
( '2019-02-04 10:00:00', 'google.com',        ['a', 'b', 'c'],[10,20,30]),
( '2019-02-04 10:00:01', 'stackoverflow.com', ['b', 'c', 'd'],[22,29,40]),
( '2019-02-04 10:00:01', 'google.com',        ['a','d'], [8,42]);

*And now you can select from performance_metrics using ARRAY JOIN:
SELECT
    website,
    custom_events.metric,
    median(custom_events.value),
    min(timestamp),
    max(timestamp)
FROM performance_metrics
ARRAY JOIN custom_events
GROUP BY
    website,
    custom_events.metric
ORDER BY
    website ASC,
    custom_events.metric ASC


text:
Q: Partial results in Solr Let's assume a query with the following words in Solr: yellow, blue, green.
I would like to return documents matching in this order:

*

*all documents that contain: yellow AND blue AND green

*then documents that contain (yellow AND blue) OR (yellow AND green) OR (blue AND green)

*then documents that contain yellow OR blue OR  green

In short: documents matching all 3 terms, then matching 2 terms, then single matches.
How can I structure the query for this?

A: This should be the default behavior when searching against a single field. The more optional SHOULD clauses are matched - the higher the score.
However, if you are using Dismax or eDismax and terms match against different fields, you will get competing scores and only the highest will get picked. This could cause some terms in one field shadow the presence of additional terms in a different field and give you possible different order.
One strategy to try in those situations is the tie (Tie Breaker) parameter, which will take into account scores from those non-maximum-score field matches. Try setting it to 1 for the extreme effect and see if the results are more like what you expected.


text:
Q: If $x$ is rational and $xy$ is irrational, then $y$ is irrational. This is a statement that I need to prove.

Let $x$ and $y$ be real numbers. If $x$ is rational and $x\times y$ is irrational, then $y$ is irrational.

I believe you have to prove this using contradiction. Thanks in advance.

A: Fill in the blanks proof: suppose $y$ is rational. Then $x\times y$ is $\underline{~~~~~~~~~~~~~~~~}$. Therefore, $y$ cannot be rational, and is hence irrational.

A: Let's do this as you suggested. By contradiction. Assume that $x$ is rational, $xy$ irrational but $y$ rational. Then, since $x$ is rational, and $y$ is rational, then $xy$ is also rational (why?). But $xy$ is irrational, by assumption. Hence we have a contradiction. (You can reason by contrapositive as well)

A: Consider contraposition: $(\neg Q \Rightarrow \neg P) \Rightarrow (P \Rightarrow Q)$. If $y$ is rational ($\neg Q$) then $xy$ is rational
 ($\neg P$) by closure of rationals. Therefore, if $xy$ is irrational ($P$) so is $y$ ($Q$).


text:
Q: Weird "shadow lines" on my display These things exist only from time to time, restarting and resetting the display doesn't help. These lines are shown Any idea what could be the cause or the solution? I feel like it's something really simple but couldn't find it on the web.
I have NVIDIA GeForce GTX 750 Ti

A: It was a cable connection issue. After adjusting it, the lines disappear. It's not HDMI, maybe I need to get HDMI...


text:
Q: openpyxl won't open XLSX file when extension is not .xlsx I am using openpyxl to read an Excel XLSX file, but openpyxl won't open it, unless I explicitly give it a .xlsx extension. Otherwise, I get this error:

openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support  file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm

I open the file like this:
wb_input = load_workbook(filename_without_extension)

When using file on the file, I see it is, in fact, an Excel 2007+ (xlsx) file.
[bf@localhost ~]$ file my_excel_file
my_excel_file: Microsoft Excel 2007+

And when copying to a filename with a .xlsx extension, openpyxl does open it.
How can I open a valid xlsx file without extension, using openpyxl?

A: Turns out load_workbook also accepts a file-like object, so this works:
with open(filename_without_extension, "rb") as wbook:
    wb_input = load_workbook(wbook)


text:
Q: Left-Outer-Join to same table with Linq/EntityFramework I need to create a left-outer-join to the same table:
SELECT Top(20) s.Id as ParentId, CASE WHEN cr.Id IS NOT NULL THEN 'False' ELSE 'True' END AS HasChangeRequest
FROM [Platos.PRM.Dev].[dbo].[Section] s
left outer join [Section] cr on cr.ParentSectionId = s.Id

For this I wrote the following Linq statement:
var query = from section in this.prmDbContext.Sections
        join changeRequest in this.prmDbContext.Sections.Where(x => x.ParentSection != null && !x.IsInactive) on section.Id equals changeRequest.ParentSection.Id into changeRequestJoin
        from changeRequest in changeRequestJoin.DefaultIfEmpty()
        select new
        {
            Id = section.Id,
            HasChangeRequest = changeRequest != null
        };

var result = query.Take(20).ToList();

The linq statement works and deliver the correct result, but is very slow.
SQL statement: some millisconds - LINQ statement: 5 seconds
Could anyone tell me, why the performance with this linq statement is bad?
Thanks!
Update:
After adding a navigation property (ChangeRequests) I update the query to the following linq statement:
var query = from section in this.prmDbContext.Sections
select new
{
    Id = section.Id,
    HasChangeRequest = section.ChangeRequests.Any()
};
var result = query.Take(20).ToList();

Now the EntityFramework creates the following sql query:
SELECT
[Limit1].[C1] AS [C1],
[Limit1].[Id] AS [Id],
[Limit1].[C2] AS [C2]
FROM ( SELECT TOP (20)
    [Extent1].[Id] AS [Id],
    1 AS [C1],
    CASE WHEN ( EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[Section] AS [Extent2]
        WHERE [Extent1].[Id] = [Extent2].[ParentSectionId]
    )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C2]
    FROM [dbo].[Section] AS [Extent1]
)  AS [Limit1]

Now the query is faster, but still slower than the left-outer-join from the native sql query. So is it possible, to optimize the linq statement?


text:
Q: A Hamiltonian inequality using uniform convexity and Taylor's formula (Evans PDE, §3.3.3, Lemma 4, (36)) In the proof of Lemma 4 (Semiconcavity again) in section 3.3.3 of the book "Partial differential equations" written by Lawrence C. Evans, there's a claim

We note first using Taylor's formula that (35) implies
(36)       $ H(\frac{p_1+p_2}{2}) \leq \frac{1}{2}H(p_1)+\frac{1}{2}H(p_2)-\frac{\theta}{8}|p_1-p_2|^2 $.

How does uniform convexity and Taylor's formula imply this?
I know that by Taylor's formula,
$ H(\frac{p_1+p_2}{2}) = H(p_1)+DH(p_1)\cdot(\frac{p_2-p_1}{2})+(\frac{p_2-p_1}{2})^TD^2H(p_1)(\frac{p_2-p_1}{2})  $,
and
$ H(\frac{p_1+p_2}{2}) = H(p_2)+DH(p_2)\cdot(\frac{p_1-p_2}{2})+(\frac{p_1-p_2}{2})^TD^2H(p_2)(\frac{p_1-p_2}{2})  $,
add them and then divide by 2, we get
$ H(\frac{p_1+p_2}{2}) = \frac{H(p_1)}{2}+\frac{H(p_2)}{2}+(\frac{DH(p_2)-DH(p_1)}{2})\cdot(\frac{p_1-p_2}{2})+(\frac{p_1-p_2}{2})^T(\frac{D^2H(p_2)-D^2H(p_1)}{2})(\frac{p_1-p_2}{2})  $.
But I can NOT get the result.

A: A couple of mistakes of execution first: (1) Your invocation of Taylor's theorem isn't correct – the second-order term needs be an error term since we want an exact equality, and should have an additional factor of $\frac{1}{k!} = \frac{1}{2}$; (2) The sign of "$D^2 H(p_1)$" (in quotes as by (1) we shouldn't evaluate at $p_1$) in the last equation should be $+$, because double negatives.
Even with those corrections, we have an unwanted nonzero first-order term, and a sign on the second-order term that's opposite of what we want. But: we can resolve these issues by applying Taylor at $\boldsymbol{\frac{p_1+p_2}{2}}$ instead!
Proof. Let $\xi = \frac{p_1-p_2}{2}$. By Taylor ($C^2$ with Lagrange remainders) there exist points $e_1, e_2$ on the line segment $\overline{p_1p_2}$ such that
$$
\begin{align*}
H(p_1) &= H\left(\frac{p_1+p_2}{2}\right) + \sum_{i=1}^n H_i\left(\frac{p_1+p_2}{2}\right) \xi_i + \frac{1}{2} \sum_{i,j=1}^n H_{ij}(e_1) \xi_i \xi_j,
\\
H(p_2) &= H\left(\frac{p_1+p_2}{2}\right) + \sum_{i=1}^n H_i\left(\frac{p_1+p_2}{2}\right) (-\xi)_i + \frac{1}{2} \sum_{i,j=1}^n H_{ij}(e_2) (-\xi)_i (-\xi)_j.
\end{align*}
$$
Averaging the two equations and rearranging, then applying uniform convexity,
$$
\begin{align*}
H\left(\frac{p_1+p_2}{2}\right)
&= \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - \frac{1}{4} \sum_{i,j} H_{ij}(e_1) \xi_i \xi_j - \frac{1}{4} \sum_{i,j} H_{ij}(e_2) \xi_i \xi_j
\\
&\leq \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - 2 \cdot \frac{\theta}{4} \lvert \xi \rvert^2
\\
&= \frac{1}{2} H(p_1) + \frac{1}{2} H(p_2) - \frac{\theta}{8} \lvert p_1 - p_2 \rvert^2. \tag*{$\blacksquare$}
\end{align*}
$$

A: Only a small correction to the answer of @epimorphic. $ e_1 $ is NOT on the segment between $p_1$ and $p_2$ . Because $e_1 = \frac {p_1 + p_2 } {2} + \delta_1 \cdot \xi = \frac {p_1 + p_2 } {2} + \delta_1 \cdot \frac {p_1 - p_2 } {2} $  where $ 0<=\delta<=1 $ , so $e_1$ is on the line segment between $\frac {p_1 + p_2 } {2} $ and $ \frac {p_1 - p_2 } {2}$ . The similarity is in the case of $e_2$.


text:
Q: XCUITest : Is it possible to tap on element not using static texts present but identifier? I am currently trying to automate tests with XCUITest framework for a parking mobile app. The thing is, each time I click on a button, I don't want to click on the static text associated to the element (because the text changes) but on the ID. Is there a way to do that ?

A: You can match an element by its identifier using matching(identifier:) function
https://developer.apple.com/documentation/xctest/xcuielementquery/1500679-matching
Chain .firstmatch or .element to match the single element.


text:
Q: how to get multiple conditional operations after a Pandas groupby? consider the following example:
import pandas as pd
import numpy as np

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                         'foo', 'bar', 'foo', 'foo'],
                   'B' : [12,10,-2,-4,-2,5,8,7],
                   'C' : [-5,5,-20,0,1,5,4,-4]})

df
Out[12]:
     A   B   C
0  foo  12  -5
1  bar  10   5
2  foo  -2 -20
3  bar  -4   0
4  foo  -2   1
5  bar   5   5
6  foo   8   4
7  foo   7  -4

Here I need to compute, for each group in A, the sum of elements in B conditional on C being non-negative (i.e. being >=0,  a condition based on another column). And vice-versa for C.
However, my code below fails.
df.groupby('A').agg({'B': lambda x: x[x.C>0].sum(),
                     'C': lambda x: x[x.B>0].sum()})

AttributeError: 'Series' object has no attribute 'B'

So it seems apply would be preferred (because apply sees all the dataframe I think), but unfortunately I cannot use a dictionary with apply. So I am stuck. Any ideas?
One not-so-pretty not-so-efficient solution would be to create these conditional variables before running the groupby, but I am sure this solution does not use the potential of Pandas.
So, for instance, the expected output for the group bar and column B would be
+10 (indeed C equals 5 and is >=0)
-4 (indeed C equals 0 and is >=0)
+5 = 11

Another example:
group foo and column B
NaN (indeed C equals -5 so I dont want to consider the 12 value in B)
+ NaN   (indeed C= -20)
-2    (indeed C=1 so its positive)
+ 8
+NaN = 6

Remark that I use NaNs instead of zero because another function than a sum would give wrong results (median) if we were to put zeros.
In other words, this is a simple conditional sum where the condition is based on another column.
Thanks!

A: I think you can use:
print df.groupby('A').agg({'B': lambda x: df.loc[x.index, 'C'][x >= 0].sum(),
                           'C': lambda x: df.loc[x.index, 'B'][x >= 0].sum()})
      C   B
A
bar  11  10
foo   6  -5

Better for understanding are custom function what is same as above:
def f(x):
    s = df.loc[x.index, 'C']
    return s[x>=0].sum()
def f1(x):
    s = df.loc[x.index, 'B']
    return s[x>=0].sum()

print df.groupby('A').agg({'B': f, 'C': f1})
      C   B
A
bar  11  10
foo   6  -5

EDIT:
root's solution is very nice, but it can be better:
def my_func(row):
    b = row[row.C >= 0].B.sum()
    c = row[row.B >= 0].C.sum()
    return pd.Series({'C':b, 'B':c})

result = df.groupby('A').apply(my_func)
      C   B
A
bar  11  10
foo   6  -5

A: Another alternative is to precompute the values you will need before using groupby/agg:
import numpy as np
import pandas as pd

N = 1000
df = pd.DataFrame({'A' : np.random.choice(['foo', 'bar'], replace=True, size=(N,)),
                   'B' : np.random.randint(-10, 10, size=(N,)),
                   'C' : np.random.randint(-10, 10, size=(N,))})

def using_precomputation(df):
    df['B2'] = df['B'] * (df['C'] >= 0).astype(int)
    df['C2'] = df['C'] * (df['B'] >= 0).astype(int)
    result = df.groupby('A').agg({'B2': 'sum', 'C2': 'sum'})
    return result.rename(columns={'B2':'B', 'C2':'C'})

Let's compare using_precomputation with using_index and using_apply:
def using_index(df):
    result = df.groupby('A').agg({'B': lambda x: df.loc[x.index, 'C'][x >= 0].sum(),
                                  'C': lambda x: df.loc[x.index, 'B'][x >= 0].sum()})
    return result.rename(columns={'B':'C', 'C':'B'})

def my_func(row):
    b = row[row.C >= 0].B.sum()
    c = row[row.B >= 0].C.sum()
    return pd.Series({'B':b, 'C':c})

def using_apply(df):
    return df.groupby('A').apply(my_func)

First, let's check that they all return the same result:
def is_equal(df, func1, func2):
    result1 = func1(df).sort_index(axis=1)
    result2 = func2(df).sort_index(axis=1)
    assert result1.equals(result2)
is_equal(df, using_precomputation, using_index)
is_equal(df, using_precomputation, using_apply)

Using the 1000-row DataFrame above:
In [83]: %timeit using_precomputation(df)
100 loops, best of 3: 2.45 ms per loop

In [84]: %timeit using_index(df)
100 loops, best of 3: 4.2 ms per loop

In [85]: %timeit using_apply(df)
100 loops, best of 3: 6.84 ms per loop

Why is using_precomputation faster?
Precomputation allows us to take advantage of fast vectorized arithmetic on
entire columns and allows the aggregation function to be the simple builtin
sum. Builtin aggregators tend to be faster than custom aggregation functions
such as the ones used here (based on jezrael's solution):
def using_index(df):
    result = df.groupby('A').agg({'B': lambda x: df.loc[x.index, 'C'][x >= 0].sum(),
                                  'C': lambda x: df.loc[x.index, 'B'][x >= 0].sum()})
    return result.rename(columns={'B':'C', 'C':'B'})

Moreover, the less work you have to do on each little group, the better off you
are performance-wise. Having to do double-indexing for each group hurts performance.
Also a killer to performance is using groupby/apply(func) where the func
returns a Series. This forms one Series for each row of the result, and then
causes Pandas to align and concatenate all the Series. Since typically the
Series tend to be short and the number of Series tends to be big, concatenating
all these little Series tends to be slow. Again, you tend to get the best
performance out of Pandas/NumPy when performing vectorized operations on
big arrays. Looping through lots of tiny results kills performance.

A: You can use apply to return a tuple containing the fields you want, and then use zip to unpack them.
def my_func(row):
    b = row[row.C >= 0].B.sum()
    c = row[row.B >= 0].C.sum()
    return b, c

# Perform the groupby aggregation.
result = df.groupby('A').apply(my_func).to_frame()

# Unpack the resulting tuple and drop the extra column.
result['B'], result['C'] = zip(*result[0])
result.drop(0, axis=1, inplace=True)

This yields the following output:
      B   C
A
bar  11  10
foo   6  -5


text:
Q: Object of class Illuminate\Support\Collection could not be converted to int with json_encode() I have a multiple query with joins condition and I'm trying to pass an array from my controller to my model then pass the return result of the query. I get this error:

Object of class Illuminate\Database\Eloquent\Collection could not be converted to int

Can someone help me to find the cause of this?
Controller
  public function get_session_leave_tagv2()
     {
          $employee = [0 => 0];
          if(Session::has('employee_leave_tag'))
          {
               $employee = Session::get('employee_leave_tag');
          }
          $emps = Tbl_payroll_leave_employeev2::select('payroll_employee_id')->whereIn('payroll_leave_employee_id',$employee)->get();

          $emp = Tbl_payroll_leave_schedulev2::getallemployeeleavedata($emps)->get();

          $data['new_record'] = $emp;

          return json_encode($data);
     }

Tbl_payroll_leave_schedule.php
  public function scopegetallemployeeleavedata($query, $payroll_employee_id=0)
    {

            $query->join('tbl_payroll_leave_employee_v2','tbl_payroll_leave_schedulev2.payroll_leave_employee_id','=','tbl_payroll_leave_employee_v2.payroll_leave_employee_id')

             ->join("tbl_payroll_employee_basic","tbl_payroll_leave_employee_v2.payroll_employee_id","=","tbl_payroll_employee_basic.payroll_employee_id")
             ->join("tbl_payroll_leave_tempv2","tbl_payroll_leave_employee_v2.payroll_leave_temp_id","=","tbl_payroll_leave_tempv2.payroll_leave_temp_id")
             ->select(DB::raw('tbl_payroll_employee_basic.payroll_employee_id , tbl_payroll_employee_basic.payroll_employee_display_name, tbl_payroll_leave_tempv2.payroll_leave_type_id, tbl_payroll_leave_employee_v2.payroll_leave_temp_hours, sum(tbl_payroll_leave_schedulev2.consume) as total_leave_consume, (tbl_payroll_leave_employee_v2.payroll_leave_temp_hours - sum(tbl_payroll_leave_schedulev2.consume)) as remaining_leave'))
             ->groupBy('tbl_payroll_leave_employee_v2.payroll_leave_temp_id');

             if ($payroll_employee_id != 0)
             {
                $query->whereIn('tbl_payroll_leave_employee_v2.payroll_employee_id', $payroll_employee_id);
             }

        return $query;
    }

A: If you are using a controller, they avoid manual json_encode, prefer below way
public function get_session_leave_tagv2()
{
    $employee = [0 => 0];
    if(Session::has('employee_leave_tag'))
    {
       $employee = Session::get('employee_leave_tag');
    }
    $emps = Tbl_payroll_leave_employeev2::select('payroll_employee_id')->whereIn('payroll_leave_employee_id',$employee)->get();

    $emp = Tbl_payroll_leave_schedulev2::getallemployeeleavedata($emps)->get();

    $data['new_record'] = $emp;

    return response()->json($data);
}


text:
Q: azure linux has not default ipv6 route Environment

*

*VM: Linux Debian 10.10

*Virtual Network with ipv4 and ipv6 address space and subnets

*Public ipv4 address and public ipv6 address (standard SKU)

*VM NIC associate public ipv4 and public ipv6 address

*VM NIC assigned private ipv4 and ipv6 address (check with ip address)

Network Security Group:

Network NIC Effective routes

Problem
Cannot connect http://ipv6.google.com
# curl -v http://ipv6.google.com
*   Trying 2404:6800:4005:812::200e...
* TCP_NODELAY set
* Immediate connect fail for 2404:6800:4005:812::200e: Network is unreachable
* Closing connection 0
curl: (7) Couldn't connect to server

No ipv6 default route
# ip -6 r
::1 dev lo proto kernel metric 256 pref medium
fd00::/80 dev docker0 metric 1024 linkdown pref medium
fd00:4244:7016::4 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev docker0 proto kernel metric 256 linkdown pref medium
fe80::/64 dev br-a3568bc4adc5 proto kernel metric 256 pref medium
fe80::/64 dev veth907e563 proto kernel metric 256 pref medium
fe80::/64 dev vethdf50b7b proto kernel metric 256 pref medium
fe80::/64 dev veth1322b71 proto kernel metric 256 pref medium
fe80::/64 dev veth6d1b4d6 proto kernel metric 256 pref medium
fe80::/64 dev vethca17875 proto kernel metric 256 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium

No default route in ipv6 router advertisement
Router advertisement only contains prefix length
# tcpdump -i eth0 -vv icmp6
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
00:51:28.053407 IP6 (hlim 255, next-header ICMPv6 (58) payload length: 56) fe80::1234:5678:9abc > ip6-allnodes: [icmp6 sum ok] ICMP6, router advertisement, length 56
        hop limit 0, Flags [managed, other stateful], pref medium, router lifetime 9000s, reachable time 0ms, retrans timer 0ms
          source link-address option (1), length 8 (1): 12:34:56:78:9a:bc
            0x0000:  1234 5678 9abc
          prefix info option (3), length 32 (4): fd00:4244:7016::/64, Flags [onlink], valid time infinity, pref. time infinity
            0x0000:  4080 ffff ffff ffff ffff 0000 0000 fd00
            0x0010:  4244 7016 0000 0000 0000 0000 0000

IPV6 Address
# ip -6 address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 state UNKNOWN qlen 1000
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 fd00:4244:7016::4/128 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::20d:3aff:fe82:b7d3/64 scope link
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 state DOWN
    inet6 fe80::1/64 scope link tentative
       valid_lft forever preferred_lft forever
4: br-a3568bc4adc5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::42:5bff:fe7d:1e0d/64 scope link
       valid_lft forever preferred_lft forever
16: veth907e563@if15: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::44da:baff:fef3:c54d/64 scope link
       valid_lft forever preferred_lft forever
18: vethdf50b7b@if17: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::5c5d:93ff:fead:8190/64 scope link
       valid_lft forever preferred_lft forever
20: veth1322b71@if19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::f4a1:ceff:fe3e:55f4/64 scope link
       valid_lft forever preferred_lft forever
22: veth6d1b4d6@if21: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::60de:73ff:fe59:74ec/64 scope link
       valid_lft forever preferred_lft forever
24: vethca17875@if23: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP
    inet6 fe80::f47a:a6ff:febf:a444/64 scope link
       valid_lft forever preferred_lft forever

A: I fixed the problem. ipv6 forward is enabled by default and accept_ra is set to 1 which ignore router advertisement. Add following to /etc/sysctl.conf to turn off ipv6 forwarding:
net.ipv6.conf.all.forwarding=0

Update
The ipv6 forwarding is enable by docker ipv6 feature. So setting the interface accept_ra=2 for docker with ipv6 enabled.


text:
Q: Adding text from row in csv with some empty cells into a list in Python Right now my code adds the text from the required rows from 2 different csv files into one list:
import csv

res = []
with open('csvexample.csv') as f, open('csvexample1.csv') as a:
    reader=csv.reader(f)
    reader1=csv.reader(a)
    next(reader)
    next(reader1)
    for row in zip(reader, reader1):
        res.extend([row[0][0], row[1][1]])

print(res)

Let's say csvexample.csv looks like this:
ID Text
1  'good morning'
2  'good afternoon'
3  'good evening'
and csvexample1.csv looks like this:
Day Month
14  'Feb'
21  'Mar'
31  'May'
10
The outcome is as follows:
['1', 'feb', '2', 'mar', '3', '']

However, I want it to print out 'May' for the csvexample1.csv file was well, and just ignore the empty cells. What do I need to change about the current code to make sure that happens?

A: Just add a generator that filters out empty rows
for row in zip((row for row in reader if row),
    (row for row in reader1 if row)):


text:
Q: Binding Redirect for PresentationFramework? In Windows 11 22H2 and version 4.8.9093.0 of PresentationFramework.dll Microsoft kindly introducted a NullReferenceException within the CloseToolTip method.
Extract from Event Viewer:

Exception Info: System.NullReferenceException at System.Windows.Controls.PopupControlService.CloseToolTip(System.Windows.Controls.ToolTip)

This has caused some random crashes in my application. Note the issue only exists on machines running the latest Windows 11.
Now to resolve this issue I can replace the broken version of the DLL in C:\Windows\Microsoft.NET\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e35 with a working version. In this case 4.8.4536.0 and it works like a charm!
This is not really something I can just do on a client machine though, so I was going to add a binding redirect with a copy of the DLL in the installation folder, but this does not appear to be working as I still see the crash and using dnSpy I can see it loading the broken DLL from the GAC.
Here is the setup of my redirect. I have also tried adding publicKeyToken="31bf3856ad364e35" but this causes the application to not launch at all.
<dependentAssembly>
    <assemblyIdentity name="PresentationFramework" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.8.9093.0" newVersion="4.8.4536.0" />
    <codeBase version="4.8.4536.0" href="PresentationFramework.dll" />
 </dependentAssembly>

Any ideas of how I can overcome this?
EDIT:
I found this

If the assembly was referenced with a public key (which it will be if
you compiled against the GAC assembly) then the loader uses the GAC to
load it.  If it can't find it in the GAC then it uses probing of the
local directory to find the assembly.

So I think I will need to create a new build of my application with PresentationFramework referenced from a different location, as there appears to be no way to force the runtime to use a local version of a DLL over one in the GAC. Very annoying.

A: After many hours spent searching, I finally found a solution. It appears this was related to some new ToolTip changes, for WCAG 2.1 accessibility or something. I don't really understand it to be honest.
I added this line to my app.config and it works as expected.
<runtime>
    <AppContextSwitchOverrides value="Switch.System.Windows.Controls.ToolTip.OptOutOfWCAG21ToolTipBehavior=true"/>
</runtime>


text:
Q: Как в андроид пополнять таблицу через БД? У меня есть таблица в БД со значениями name , surname, email и т.д.
Мне в Андроид приложении нужно взять из этой таблицы Имя name и Фамилию surname и запихать в таблицу активити...
Метод взятия данных из БД в DatabaseHelper я написал и выглядит он так:
public Cursor getAllRegisteredPersons() {
    database = this.getReadableDatabase();
    return database.rawQuery(
    "SELECT " + COLUMN_NAME +
    " , " + COLUMN_SURNAME +
    " , " +
    "FROM " + TABLE_NAME, null);
}

В ListOfRegisteredActivity.java я написал такую конструкцию как:
dbHelper = new DBHelper(this);
Cursor regPersons = dbHelper.getAllRegisteredPersons();
if (regPersons.getCount() == 0) {
   //TODO Написать на экране что пользователей нету
} else {
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<String> surnames = new ArrayList<String>();
    while (regPersons.moveToNext()) {
        names.add(regPersons.getString(0));
        surnames.add(regPersons.getString(1));
    }
    Collections.sort(names);
    Collections.sort(surnames);
}

Вот тут дальше я уже не знаю что и как вывести в виде простой таблицы как на данном скриншоте

А вот и сам .xml для 1 пользователя

<TableRow
    android:background="#cccccc"
    android:padding="5dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/person_count"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/person_name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/person_surname"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<TableRow android:padding="5dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="1"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Эльмир"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Исмаилзаде"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>

Как сделать так, чтобы данная таблица генерировалась автоматически через базу данных?


text:
Q: undefined references in gcc link with udev on elux 5 I am trying to link some propetary code on eLux 5 (works on eLux 4) a special Linux distribution.
The command line is very long and contains: -ludev -lpenDriverApi (both dynamic libraries, penDriverApi ist the propetary code which depends on udev).
Now the linker tolds me that various references are undefined from udev like 'udev_monitor_unref'. With "nm" I verified that these references are available within the udev shared object - so this error messages are really strange to me.
Because I also tried various verbose/debug settings for the linker I am now at a point without having a clou how to find out what went wrong during linking of my cmake project.
Hopefully this picture is readable, because the damned vmware would allow copy/paste which is enabled (maybe the elux config is bad).

udev Version on eLux 4 is 0.6.1
udev Version in eLux 5 is 1.3.5

A: The solution to this problem was, that the third party shared library libpenDriverApi.so required recompilation with a libudev.so.1 as well as a change to the linker, so that ldd -r also shows the dependency to libudev.

A: In the linkage sequence any object file or library that requires symbol
definitions must appear before the library that provides the definitions,
or undefined reference errors will ensure. This is because the
linker by default will search a library only to find definitions of
symbols that it has observed are referenced, but not defined, in earlier
files.
So if libpenDriverApi depends on libudev then you have to link in the order:
-lpenDriverApi -ludev


text:
Q: alinhar imagem ao centro sobre outra imagem estou desenvolvendo um site como portifolio, estou usando wordpress e bootstrap, criei uma div e dentro desta coloquei uma tag img com a imagem de fundo dessa div, porem agora quero colocar uma imagem do meu logo sobreposta ao background, usando algumas propriedades do css ate consigo colocar ela sobreposta porem nao consigo alinha-la ao centro
meu codigo esta assim:

    <img class="img-logo" src="<?php bloginfo('template_directory') ?>/assets/images/logo.jpg" alt="">
    <img class="img-fundo img-responsive" src="<?php bloginfo('template_directory') ?>/assets/images/header.jpg" alt="">

css esta assim:
.img-fundo{
    display: block;
}

.img-logo{
    position: absolute;
    magin-left: auto;
    margin-right: auto;
}

ela sobrepoe mas nao alinha ao centro. como devo proceder?

A: Já tentou colocar uma div dentro da "img-fundo" e nela você por a imagem do seu logo? Creio que poderia dar certo, usando o CSS para centralizá-la e até mesmo uma class.

A: Você pode fazer isso usando jquery:

A: Uma das maneiras de centralizar um elemento com CSS, com a posição absoluta, usa-se o left com 50% e margin-left com metade negativa da largura do elemento, isso garante que sempre estará no centro.
Para alinhar a logo ao centro descubra a largura width desta imagem e altere a classe no CSS para algo desse tipo:
.img-logo{
    position: absolute;
    left: 50%;
    magin-left: -50px; //-50px se a logo tiver largura de 100px
}


text:
Q: Search for substrings in given order I want to write a function to search for given substrings in one or more strings in the order the substrings are given.  For example, if the substrings are

"the" "new" "store"

and strings are

"the new store is in san francisco", "the boy enters a new and cool
  store", "a new boy enters the store", "there is newton in the store"

then the function will match only the 1st, 2nd, and 4th sentences because they have the substrings are the specific order, whereas the 3rd has them in the wrong order.

A: You can use regular expressions. .+ matches 1 or more characters excluding \n. .* matches 0 or more characters.
import re

l = ["the new store is in san francisco", "the boy enters a new and cool store", "a new boy enters the store",
     "there is newton in the store"]

for i in l:
    m = re.search(r'the.+new.+store.*', i)
    if m:
        print(m.group())

A: The key idea is to use string.index(sub, start) for each substring, with start initially 0 and incremented past each substring found.  If this is homework, and perhaps even if not, you should try writing subs_in_strings(subs, strings) yourself, before reading my answer.
..
def subs_in_strs(subs, strings):
    '''Yield strings that contain subs in order, without overlap.

    strings: iterable of strings
    subs: reiterable sequence of substrings
    '''
    for string in strings:
        dex = 0
        try:
            for sub in subs:
                dex = string.index(sub, dex) + len(sub)
            yield string
        except ValueError:
            pass

Your test
for s in subs_in_strs(('the', 'new', 'store'),
        ("the new store is in san francisco",
         "the boy enters a new and cool store",
         "a new boy enters the store",
         "there is newton in the store",)):
    print(s)

The 3rd sentence is not printed.  Testing overlap condition:
for s in subs_in_strs(('sent', 'tense'),
        ('sent a tense note',
         'mispelled sentense',
         'another senttense')):
    print(s)

2nd is omitted, 3rd not, as per specification.


text:
Q: Kotlin completion with multiple parameters Imagine a method with a multiple parameter completion:
fun foo(completion : (p1 : Int, p2 : Int) -> Unit){
    completion(1, 2)
}

How to access p1 and p2 when calling foo?

A: You can call foo with a simple lambda like this:
foo { p1, p2 ->
    //do stuff
}


text:
Q: attachEvent gives trouble I am trying to do drop down horizontal menu in JavaScript. It's works fine on Firefox and Chrome, however giving me troubles in IE.
Here is the code I have:
function init(){

    hideAllSubMenu();

    var menuItem = document.getElementById("menu_wrap").getElementsByTagName("div");

    for(var index = 0; index < menuItem.length; index++)
    {
        // if firefox and all oother browsers
        if(typeof menuItem[index].addEventListener != "undefined")
        {
            menuItem[index].addEventListener("mouseover", ShowListener, false);
            menuItem[index].addEventListener("click", ShowListener, false);
        }
        else //IE
        {
            menuItem[index].attachEvent("onclick", ShowListener);
            menuItem[index].attachEvent("onmouseover", ShowListener);
        }
    }
}

function ShowListener(event)
{
    hideAllSubMenu();

    var menuItemIdStr = this.id;
    var menuItemIdNum = menuItemIdStr.replace(/menu/i, "");
    var subMenu = document.getElementById("submenu_wrap" + menuItemIdNum);

    subMenu.style.left = this.offsetLeft + "px";
    subMenu.style.top = this.offsetTop + this.offsetHeight + 2 + "px";
    subMenu.style.display = "block";
}

It's seems like its complaining about this.
I understand that in IE event listener function is not copy but a reference, and that's why this giving me a problem.
Is there a way around this problem?
I even tried to create separate function for attachEvent for IE and path there object directly, however it still complaining.
Something like that:
menuItem[index].attachEvent("onmouseover", ShowListenerIE(menuItem[index]));

Note: I do plan to rewrite this simple menu in feature to jQuery, but for now I am interested in learning JavaScript Core + DOM, and would like to find a way around this problem.

A: The target of an event in IE is in event.srcElement, and you can get similar information in other browsers from event.target. Note also that IE won't pass event as an argument to the handler - it's in window.event instead. So, a complete solution:
if (!event)
{
    event = window.event; //IE
}

var target;
if (event.target)
{
    target = event.target;
}
else if (event.srcElement)
{
    target = event.srcElement;
}

//From here on is your code, use target instead of this

See here for more gory details. Disclaimer: my code is untested.

A: As an addition to the answers above, I generally use this way of coding more JavaScript-y:
function eventHandler( event ){
    var event  = window.event || event;
    var target = event.srcElement || event.target;
}


text:
Q: Configure SDL2 with CMakeList.txt on CLion in a nice, portable way I know this has been asked before, but I'm not satisfied with the answers I'm finding online, so hopefully someone can provide me with the right insights.
I'm trying to configure SDL2 with CLion on Windows and I'm having some problems. I downloaded the SDL2 sources on linux before, built them succesfully and installed them, so I know it works. However, I don't have access to that computer now and I'm trying to set things up on Windows.

I downloaded http://libsdl.org/release/SDL2-devel-2.0.7-mingw.tar.gz and extracted its contents to E:\SDL2\SDL2-2.0.7 (with E:\SDL2\SDL2-2.0.7\x86_64-w64-mingw32\bin containing SDL2.dll). None of the guides I've found say anything about running configure, cmake, make or whatever and since it contains a DLL, I assume everything is pre-built (?)
This is my CMakeList.txt in my CLion project (named SDL_Project) in E:\repository\SDL_Project:
cmake_minimum_required(VERSION 3.6)
project(SDL_Project)

set(CMAKE_CXX_STANDARD 14)

add_executable(SDL_Project src/main.cpp)

find_package(SDL2 REQUIRED)
find_package(SDL2_image REQUIRED)
find_package(SDL2_ttf REQUIRED)

include_directories(${SDL2_INCLUDE_DIR}
        ${SDL2_IMAGE_INCLUDE_DIR}
        ${SDL2_TTF_INCLUDE_DIR})

target_link_libraries(SDL_Project ${SDL2_LIBRARY}
        ${SDL2_IMAGE_LIBRARIES}
        ${SDL2_TTF_LIBRARIES})

This alone does not work since CMake does not know where to look for SDL2 (which differs from my Linux experience.)
I've found several versions of FindSDL2.cmake online, which are enormous scripts that search for SDL2 in various locations, apparently.
Adding this script next to CMakeList.txt does not work for me:
CMake Error at CMakeLists.txt:8 (find_package):
  By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2", but
  CMake did not find one.

[...]

I have also added the SDL2 directory to PATH in Windows system environment variables through the control panel.
Here is my compiler message (when I comment out the SDL2 lines in CMakeList.txt which cause errors):
E:\repository\SDL_Project\src\main.cpp:1:17: fatal error: SDL.h: No such file or directory
 #include <SDL.h>
                 ^
compilation terminated.

I know this error is obvious, but I'm including it here anyway for completeness.

I have the following questions:

*

*How do I properly set this up for Windows in a clean way (adding SDL2 to System32 doesn't seem nice to me..)

*I would like to use the exact same CMakeList.txt file for building from multiple machines (linux, Windows..), so ideally this does not contain hardcoded paths or OS-specific code or configuration.

*Using a massive FindSDL2.cmake file with a large list of hardcoded locations to search, doesn't seem nice to me either..

*Ideally there's minimal configuration required to set up the build environment; a) clone repository, b) download/unzip SDL2, c) somehow tell the compiler where SDL2 is located.

So in other words; what is a nice, portable, minimal solution to this problem? Please motivate the answer where possible, I like to learn why this is a good solution as well as how to do it. Thanks!!

A: Finding libraries is complicated, even though Unix tries very hard to trick you into thinking it's not.
In the end, a library is just a file on the filesystem (anywhere on the filesystem) and you need to somehow tell your build scripts where to look for that file. Unix comes with a number of reasonable defaults here (eg. /usr/lib/), which Windows does not have, but the situation on Unix gets just as bad as on Windows as soon as you install your library to a non-standard location.
CMake has two answers to this problem, but in the case of SDL2 the more appropriate is arguably using find scripts.
The find script now is supposed to solve the problem of locating a library file that could be anywhere on your filesystem. There might be a few reasonable defaults, which it checks automatically for your convenience, but in the end, it can't get the job done without your help, because the file could be anywhere.
That's why, if we look at a typical find script, it will always provide you with a customization point to tell the build system where to find the library in question:
FIND_LIBRARY(SDL2_LIBRARY_TEMP
  NAMES SDL2
  HINTS
  $ENV{SDL2DIR}
  PATH_SUFFIXES lib64 lib
  PATHS ${SDL2_SEARCH_PATHS} ${SDL2_INCLUDE_DIR}/../..
)

Note the HINTS $ENV{SDL2DIR} here. This will make CMake search the directory specified in the environment variable SDL2DIR, as well as the subdirectories lib and lib64 in there, for a library file called SDL2 (in addition to the aforementioned default paths that are always searched)¹.
Note that this is a machine specific hint, so the directory is intentionally not hardcoded in any of the scripts, but instead retrieved from an environment variable. That way, the build script itself remains completely portable and it is the user's responsibility to configure the build environment accordingly.
So the setup process for you is: Obtain a binary of your favorite library (either by downloading the binary or by building it yourself), install it to a location of your choice and then make that library location somehow known the build, eg. by setting an environment variable in the build shell. Note that this process is always the same for all platforms, you may simply skip the last step if your library is already installed in a default location recognized by the find-mechanism, such as /usr/lib on Unix, or the CMake package registry on Windows.
There is one more detail missing. Whether using an external find script or a package config file for finding the library, CMake must also be able to find that very script before it can go on to search for the library. Here again, CMake already ships with a bunch of preinstalled scripts available for your convenience, but SDL2 is not one of them. Fortunately, if you have to provide your own find script, you usually just place it in the source tree, so making its location known to CMake is not a problem. For example, if you place the FindSDL2.cmake in a folder cmake under your project source root, simply call list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") to have CMake use the find script from that location.
¹ Note that since CMake 3.12 find_package(Foo) automatically considers the Foo_ROOT environment variable as a search hint for all relevant find_* calls, unless the script explicitly opts out of that behavior with the NO_PACKAGE_ROOT_PATH option.


text:
Q: Executable exiting preemptively when ranging over an empty channel I recently encountered a coding exercise which I solved in python in which I had to port an "algorithm". I don't know how it is called which is why I am describing it:
Each new line was a description of the previous line by the amount of the same number printed in sequence and the associated number.
Here is an example:
1
11
21
1211
111221
312211
etc

I started learning Go with its channels and concurrency features. So I came back to this exercise to try to solve it more efficiently in parallel with Go.
This is what I got so far:
package main

func main() {
    channel := make(chan uint8)
    go treeCalcRoutine(channel, 0)
    channel <- 1
    close(channel) //defer is not an option in this case because the channel has
    //to be closed before main exits
}

func treeCalcRoutine(in <-chan uint8, generation int) {
    if generation > 10 {
        return // return after 10 recursive iterations
    }
    out := make(chan uint8)
    defer close(out)
    num := uint8(1)
    previous := <-i
    go treeCalcRoutine(out, generation+1)
    for val := range in {
        switch {
        case val == previous:
            num++
        default:
            num = uint8(1)
            out <- num
            out <- val
        }
        previous = val
    }
    out <- num
    out <- previous
}

While trying to debug the program using Delve, I figured out the Program quits without an exception (and exit status 0) while trying to range over an empty/closed channel. I expected the program just to skip the for loop altogether in this case.
I still want to solve this challenge myself so I would appreciate if someone could just point me in the right direction instead of producing a functioning solution. Moreover, please point out any other issues/cases which could be done better (like the generation limit).
EDIT:
Since people asking me to post the error: There is no error at all for some reason. The program just exits once it reaches the for loop.

A: So the issue was not actually that the for loop was exiting when it was encountering the closed channel but the main routine exited at that exact time which caused every other goroutine to terminate as well. I was advised to use waitgroups in this case.


text:
Q: Sort collection by object attribute I have an ArrayList which consists in a collection of a complex object.
This object has a date field.
I want to sort my list from this date on.
In example
class Student{
 int ID;
 Date joinDate;

}

ArrayList <Student> students;

How can I sort this students collection from joinDate?

A: Implement Comparable interface in Student class
Then you have to override following method in your Student class
public int compareTo(Reminder o) {
        return getJoinDate().compareTo(o.getJoinDate());
}

Then you use in-built sort method of collections class to sort your objects by date
Collections.sort(students);

A: Implement Comparable and the method compareTo
public class Student implements Comparable<Student>{

    public int compareTo(Student otherStudent){
       // compare the two students here
    }

}

Collections.sort(studentsArrayList);

A: Write a Comparator and pass it to the sort function. It's a lot better than changing your data class just to provide one kind of ordering.
Collections.sort(students, new Comparator<Student>() {
   public int compare(Student e1, Student e2) {
       return e1.joinDate.compareTo(e2.joinDate);
   }
});

Or in java 8:
Collections.sort(students, (e1, e2) -> e1.joinDate.compareTo(e2.joinDate));

For more information check this tutorial.


text:
Q: dual GPUs? Both ATI and NVidia I'd like to install both an NVidia GPU and an ATI GPU.  Since I'm using OpenCL, I need the proprietary drivers for each.  I've had troubles updrading to proprietary drivers and doing it successfully twice with all the potential conflicts worries me.  (i.e.- after a reboot, the GUI never initializes, necessitating a recovery or rebuild.)
Can it be done successfully?


text:
Q: How do i get the argv[0]? In C++ i was getting the app path without the app name at the end by saying:
 std::string dir = dirname(argv[0]);

and it worked without any problems, but when i planned to use cocoa it said:
error: 'argv' was not declared in this scope and now i'm lost i have tried:
NSArray *args = [[NSProcessInfo processInfo] arguments];

std::string dir = dirname(args);

but without any luck, please help me out guys!
ps: i have changed the files from .m to .mm already in case you want to know

A: Here is how you get the app path:
[[NSBundle mainBundle] bundlePath];

A: Instead of saying
std::string dir = dirname(args);

try the following:
NSArray *args = [[NSProcessInfo processInfo] arguments];
NSString* arg0 = args[0];
std::string dir = dirname([arg0 fileSystemRepresentation]);

Hope that helps


text:
Q: Detect links to site's videos and show title I have a problem.
I have a Video and Comment model.
If the user inserted the link to video into the comment, it is link to replace with the title from video.
How should I write a method?
def to_show_title_instead_of_the_link
  body.gsub!(%r{(videos)\/([0-9])}) {|link| link_to link)}
end

We input:
http://localhost:3000/videos/1

We receive:
 test video

A: It sounds like you want to take a given URL on your site, and find the associated parameters for that route. This will let you get the id for the video in a clean, DRY way (without using a regex that might break later if your route changes). This will then let you look up the model instance and fetch its title field. The Rails method for this task is Rails.application.routes.recognize_path, which returns a hash with the action, controller, and path parameters.
In your view:
# app\views\comments\show.html.erb
# ...

  replace_video_url_with_anchor_tag_and_title(comment.text)

# ...

And here is the helper method:
# app\helpers\comments_helper.rb
def replace_video_url_with_anchor_tag_and_title(comment_text)
  # assuming links will end with a period, comma, exclamation point, or white space
  # this will match all links on your site
  # the part in parentheses are relative paths on your site
  # \w matches alphanumeric characters and underscores. we also need forward slashes
  regex = %r{http://your-cool-site.com(/[\w/]+)[\.,!\s]?}
  comment_text.gsub(regex) do |matched|
    # $1 gives us the portion of the regex captured by the parentheses
    params = Rails.application.routes.recognize_path $1

    # if the link we found was a video link, replaced matched string with
    # an anchor tag to the video, with the video title as the link text
    if params[:controller] == 'video' && params[:action] == 'show'
       video = Video.find params[:id]
       link_to video.title, video_path(video)

    # otherwise just return the string without any modifications
    else
       matched
    end
  end
end

I didn't know how to do this off the top of my head, but this is how I figured it out:
1) Google rails reverse route, and the first result was this stackoverflow question: Reverse rails routing: find the the action name from the URL. The answer mentions ActionController::Routing::Routes.recognize_path. I fired up rails console and tried this out, however it is deprecated, and didn't actually work.
2) I then google rails recognize_path. The first search result was the docs, which were not very helpful. The third search result was How do you use ActionDispatch::Routing::RouteSet recognize_path?, whose second solution actually worked.
3) Of course, I then had to go refresh my understanding of Ruby regex syntax and gsub!, and test out the regex I wrote above =)

A: I did refactoring code and used a gem rinku
def links_in_body(text)
  auto_link(text) do |url|
    video_id = url.match(/\Ahttps?:\/\/#{request.host_with_port}\/videos\/(\d+)\z/)
    if video_id.present?
      Video.find(video_id[1]).title
    else
      truncate(url, length: AppConfig.truncate.length)
    end
  end
end


text:
Q: How do I create a function that returns the first non-nil, non-empty string passed to it? I'm trying to implement a function that returns the first non-blank string from the variables passed to it. Unfortunately, some of these variables might be nil, so the naive approach
function first_non_empty(...)
    for i, item in ipairs({...}) do
        if item ~= nil and item ~= '' then
            return item
        end
    end
    return ''
end

doesn't work: ipairs quits out as soon as it encounters a nil value. This can be fixed by changing the requirements so that the variables can't be nil, or by passing the length to the function so table length doesn't have to rely on ipairs, or by wrapping all parameters in a function so that none of them are explicitly nil
function first_non_empty_func(...)
    for i, func in ipairs({...}) do
        local item = func()
        if item ~= nil and item ~= '' then
            return item
        end
    end
    return ''
end

function fn(p)
    local f = function() return p end
    return f
end

-- change callers to first_non_empty_func(fn(a), fn(b), fn(c))

However, both of these solutions complicate the function prototype. Does there exist a function taking an ordered list of parameters, some of which may be nil, which returns the first of those parameters which is both non-nil and not an empty string?

A: Use table.pack, which preserves all nil entries and returns the number of entries in the n field:
function first_non_empty_pack(...)
    local t = table.pack(...)
    for i = 1, t.n do
        local item = t[i]
        if item ~= nil and item ~= '' then
            return item
        end
    end
    return ''
end

A: select('#', ...) can be used to get the number of provided arguments, so here is an alternative that doesn't use table.pack:
function first_non_empty_pack(...)
    for i = 1, select('#', ...) do
        local item = select(i, ...)
        if item ~= nil and item ~= '' then
            return item
        end
    end
    return ''
end

A: Simpler approach is to use recursion. No extra tables created, etc:
function first_non_empty(item, ...)
    if item ~= nil and item ~= '' then return item end
    return first_non_empty(...)
end

But the list has to end with some ending marker. For example, boolean 'false', indicating there's no non-nil, nonempty strings.


text:
Q: adding home directory after -M option First off I'm new to Linux. I have created a new user called "ginny" with -M option.
Now I'm trying to assign a home directory with usermod -d /link/to/directory ginny but it doesn't assign a home directory to user ginny.
% su - ginny returns an error
su: warning : cannot chance directory to /abc: No such file or directory
-bash-3.2$:

The pwd command returns /root for user ginny (maybe because i haven't created her a home directory) but is there any switch that can now allow me to assign a home directory to user ginny?

A: The user's home directory doesn't exist. usermod changes the home directory field in /etc/passwd but doesn't create the directory. You need to create it manually.
cp -a /etc/skel /link/to/directory          # or mkdir /link/to/directory to create an empty home directory
chown ginny:ginnygroup /link/to/directory   # where ginnygroup is ginny's primary group
chmod 755 /link/to/directory                # or 711 or 700 or 751 or 750 as desired


text:
Q: How is it possible that Abra was 3 "when the colony was founded"? OK, when I was answering this question ("How to explain the ages of Valentine and Peter in Ender's game"), I posted a quote that now doesn't seem to make any sense to me:

He took one of the children along, an eleven-year-old boy named Abra; he had been only three when the colony was founded, and he remembered no other world than this. ("Ender's Game", Ch 15).

Now, as I have noted in the quotes in the answer, the colony was started 50 years before Ender got there, by the pilots who were fighting the buggers.
So, how could Abra be 11 years old 50+8=58 years after the colony was founded, but 3 years old when it was founded in the same sentence?
(the obvious guess would have been that he was one of the colonists sent with Ender, but I distinctly recall Card mentioning that he was NOT that and was born on the colony world somewhere else).

A: OK, figured it out (and while at it, answered the original question - will go update it now :)
It was one of the "didn't think it through in original book" things Card said in Chapter 15 that he discussed in Ender in Exile's afterword (quote below).
In Ender in Exile, Card explicitly elaborated on Abra:

*

*Abra was NOT born on Earth. He was on the colony when Ender arrived, and therefore could not have been 3 when it was founded.

In all eleven years of Abra's life, only one thing had ever happened that mattered: the arrival of Ender Wiggin.

*In the afterword to "Exile", Card explicitly admitted to "the details and the timeline are not exactly right" in Ender's Game Chapter 15, especially as pertaining to existence of 40 years of the colony preceding Ender's arrival:

Except for one tiny problem. When I wrote the novel Ender's Game back in 1984, my focus in the last chapter, chapter 15, was entirely on setting up Speaker for the Dead. I had no notion of any sequel between those two books. So I was rather careless and cavalier with my account of Ender's time on the first colony. I was so careless I completely forgot that on all but the last formic planet, there would have been human pilots and crew left alive. Where would they go? Of course they would begin colonizing the formic worlds. And those who sent them would have at least allowed for that possibility, sending people trained to do whatever jobs they anticipated would be necessary.
So while the meat of chapter 15 of Ender's Game is exactly right, the details and timeline are not. They aren't what they should have been then, and they certainly aren't what they need to be now. Since writing that chapter, I have written stories like "Investment Counselor" (in First Meetings), where Ender meets Jane (a major character in Speaker) when he is legally coming of age on a planet called Sorelledolce; but this contradicted the timeline stated in Ender's Game. All in all, I realized, it was chapter 15 that was wrong, not the later stories, which took more details into account and developed the story in a superior way.


text:
Q: I can't get a value from one of two feeders I have two feeders in my test scenario
When i use one of them in first request it works alright, however when I use it in the next request block it doesn't work
I have tried changing the feed(feederName) position but still having the same problem
Here is a snippet of my test scenario with some comment to explain what's not working
//the Two feeders
  val kmPerYearFeeder = Iterator.continually(
    Map("kmPerYear" -> Random.shuffle(List("10000", "15000", "20000", "25000", "30000", "35000", "40000", "45000", "50000")).head)
  )
  val customerTypes = Iterator.continually(
    Map("customerType" -> Random.shuffle(List("P","B")).head)
  )

//here the customerTypes feeder is working
val homepage = feed(customerTypes)
    .exec(http("homepage")
    .get("/?customer_type=${customerType}"))

//this block is not really important but working alright
  val pdp = exec(http("homepage")
     ....
// the feeder here doesn't work
  val calculate_rate  = feed(kmPerYearFeeder)
.exec(http("calculate_random_rate")
    .get(session => session("random_pdp_link").as[String] + "?inquiry_type=&km_per_year=${kmPerYear}")
    .check(status.is(200)))

  val pdp_scenario = scenario("PDP").exec(homepage).exec(pdp).exec(calculate_rate)

  setUp(
    pdp_scenario.inject(
      rampUsers(10) during (5 seconds),
    ).protocols(httpProtocol),
)

these are the get requests that are executed (got them from the logger)
GET ********?inquiry_type=&km_per_year=$%7BkmPerYear%7D
GET ********?inquiry_type=&km_per_year=$%7BkmPerYear%7D
GET ********?inquiry_type=&km_per_year=$%7BkmPerYear%7D

A: Your issue is that in where you attempt to use the Gatling EL to reference the kmPerYear session var in
.get(session => session("random_pdp_link").as[String] + "?inquiry_type=&km_per_year=${kmPerYear}")

this version of .get takes a session function (which you are using to get "random_pdp_link"), but the Gatling EL doesn't work in session functions.
You either need to get it manually using
session("kmPerYear").as[String]
or to reference "random_pdp_link" via the EL and not use the session function get. eg:
.get("${random_pdp_link}?inquiry_type=&km_per_year=${kmPerYear}")


text:
Q: Evaluating $\int _0^{\infty }W\left(\frac{1}{x^3}\right)\:\mathrm{d}x$ How can i evaluate $\displaystyle\int _0^{\infty }W\left(\frac{1}{x^3}\right)\:\mathrm{d}x$ in an easy manner i managed to end up with this
$$3\int _0^{\infty }\frac{W\left(\frac{1}{x^3}\right)}{W\left(\frac{1}{x^3}\right)+1}\:\mathrm{d}x$$
But how can i continue?.
$W(x)$ is the lambert w function

A: You can generalize this integral
$$\underbrace{\int _0^{\infty }W\left(\frac{1}{x^n}\right)\:dx}_{t=W\left(\frac{1}{x^n}\right)}$$
$$=\frac{1}{n}\int _0^{\infty }t^{1-\frac{1}{n}}e^{-\frac{t}{n}}\:dt+\frac{1}{n}\int _0^{\infty }t^{-\frac{1}{n}}e^{-\frac{t}{n}}\:dt=n^{1-\frac{1}{n}}\Gamma \left(2-\frac{1}{n}\right)+n^{-\frac{1}{n}}\Gamma \left(1-\frac{1}{n}\right)$$
$$=-n^{-\frac{1}{n}}\Gamma \left(-\frac{1}{n}\right)$$
So
$$\boxed{\int _0^{\infty }W\left(\frac{1}{x^n}\right)\:dx=-n^{-\frac{1}{n}}\Gamma \left(-\frac{1}{n}\right)}$$
So for your integral, letting $n=3$ gets
$$\int _0^{\infty }W\left(\frac{1}{x^3}\right)\:dx=-3^{-\frac{1}{3}}\Gamma \left(-\frac{1}{3}\right)=3^{\frac{2}{3}}\Gamma \left(\frac{2}{3}\right)\approx2.816678$$


text:
Q: Curious why some cells are shown in a different Z index in View Debugger in Xcode I was in the view debugger...debugging, and I was curious why certain cells seem to have a different Z index from the rest. I've seen this before but decided to ask about it. Is this just an Xcode, view debugger thing? Or is this actually what's happening?
I'm actually not too sure what the best way to find out is because sometimes it looks nice and flat like this image: .
Thanks!


text:
Q: What is the best regex for a mix of capitalised words and symbols? I'm trying to organise the following list:
list of gaming genre
I want to separate the concatenated words, but seems like they won't take the uppercase words that represents acronyms (e.g. PVP, MMORPG, MOBA, DeFi) properly.
Currently, my regex code is as follows:

re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in genre_list

As you can see below, it sometimes it works and sometimes it doesn't:

['Collectible Open-World Virtual-World', 'Breeding Card PV P', 'Auto-Battler Breeding Strategy', 'Minigame Open-World Virtual-World', 'Action Simulation Sports', 'Adventure MM OStrategy', 'Adventure Casual Puzzle', 'Sports', 'Collectible Sci-Fi Virtual-World', 'Battle-Royalee Sports MO BA', 'Action PV PShooter', 'P VP Sci-Fi Tower-Defense', 'Action Battle-Royale', 'P VP Sci-Fi Shooter', 'Breeding Collectible Mining', 'Collectible De Fie Sports', 'Action Adventure Shooter', 'City-Building Collectible Simulation', 'Action Strategy', 'Adventure Open-World', 'Breeding Racing Sports', 'Open-World Virtual-World', 'Collectible Idle', 'Action Adventure', 'Card Collectible PV P', 'Battle-Royale Fantasy MO BA', 'City-Building', 'Building MM OStrategy', 'Adventure MM OR PG', 'Action Adventure Idle', 'M OB AR PG Strategy', 'M MO RP GStrategy', 'Card Collectible Idle', 'Open-World PV PR PG', 'De Fi MM OSpace', 'Collectible', 'Card Collectible PV P', 'Auto-Battler De Fi RP G', 'Adventure MM OOpen-World', 'Collectible Open-World Virtual-World', 'Collectible Idle RP G', 'Card Collectible PV P', 'Action Adventure PV P', 'Sci-Fi Shooter Survival', 'Action Strategy', 'Arcade Minigame', 'Breeding PV PRacing', 'M OB AP VP', 'Action Sports', 'P VP Space Turn-based', 'M MO Strategy Tower-Defense']

Can you help me which regex would do best on this? Or regex just doesn't work for this list? Thanks!

A: Editing based on the comments:
You just need to add a '+' after the [A-Z] i.e. r"(\w)([A-Z]+)".
This will match 1 or more capital letters.

A: It is difficult because you have ALLCAPS words that may be glued. If you have such a list, it is solvable.
Here is a code you can use and enhance to get even better output precision:
import re
l = ['Collectible Open-World Virtual-World', 'Breeding Card PV P', 'Auto-Battler Breeding Strategy', 'Minigame Open-World Virtual-World', 'Action Simulation Sports', 'Adventure MM OStrategy', 'Adventure Casual Puzzle', 'Sports', 'Collectible Sci-Fi Virtual-World', 'Battle-Royalee Sports MO BA', 'Action PV PShooter', 'P VP Sci-Fi Tower-Defense', 'Action Battle-Royale', 'P VP Sci-Fi Shooter', 'Breeding Collectible Mining', 'Collectible De Fie Sports', 'Action Adventure Shooter', 'City-Building Collectible Simulation', 'Action Strategy', 'Adventure Open-World', 'Breeding Racing Sports', 'Open-World Virtual-World', 'Collectible Idle', 'Action Adventure', 'Card Collectible PV P', 'Battle-Royale Fantasy MO BA', 'City-Building', 'Building MM OStrategy', 'Adventure MM OR PG', 'Action Adventure Idle', 'M OB AR PG Strategy', 'M MO RP GStrategy', 'Card Collectible Idle', 'Open-World PV PR PG', 'De Fi MM OSpace', 'Collectible', 'Card Collectible PV P', 'Auto-Battler De Fi RP G', 'Adventure MM OOpen-World', 'Collectible Open-World Virtual-World', 'Collectible Idle RP G', 'Card Collectible PV P', 'Action Adventure PV P', 'Sci-Fi Shooter Survival', 'Action Strategy', 'Arcade Minigame', 'Breeding PV PRacing', 'M OB AP VP', 'Action Sports', 'P VP Space Turn-based', 'M MO Strategy Tower-Defense']
l = [''.join(s.split()) for s in l]
allcaps = ['RPG', 'MOBA', 'PVP', 'MMO']
rx_1 = re.compile(r'[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])')
rx_2 = re.compile( fr"\b(?:{r'|'.join(allcaps)})(?=[A-Za-z])" )
rx_3 = re.compile( fr"(?<=[A-Za-z])(?:{r'|'.join(allcaps)})\b" )
for s in l:
    print( r'{} => {}'.format(s, rx_3.sub(r" \g<0>", rx_2.sub(r"\g<0> ", rx_1.sub(r"\g<0> ", s)))) )

See the Python demo. Output:
CollectibleOpen-WorldVirtual-World => Collectible Open-World Virtual-World
BreedingCardPVP => Breeding Card PVP
Auto-BattlerBreedingStrategy => Auto-Battler Breeding Strategy
MinigameOpen-WorldVirtual-World => Minigame Open-World Virtual-World
ActionSimulationSports => Action Simulation Sports
AdventureMMOStrategy => Adventure MMO Strategy
AdventureCasualPuzzle => Adventure Casual Puzzle
Sports => Sports
CollectibleSci-FiVirtual-World => Collectible Sci-Fi Virtual-World
Battle-RoyaleeSportsMOBA => Battle-Royalee Sports MOBA
ActionPVPShooter => Action PVP Shooter
PVPSci-FiTower-Defense => PVP Sci-Fi Tower-Defense
ActionBattle-Royale => Action Battle-Royale
PVPSci-FiShooter => PVP Sci-Fi Shooter
BreedingCollectibleMining => Breeding Collectible Mining
CollectibleDeFieSports => Collectible De Fie Sports
ActionAdventureShooter => Action Adventure Shooter
City-BuildingCollectibleSimulation => City-Building Collectible Simulation
ActionStrategy => Action Strategy
AdventureOpen-World => Adventure Open-World
BreedingRacingSports => Breeding Racing Sports
Open-WorldVirtual-World => Open-World Virtual-World
CollectibleIdle => Collectible Idle
ActionAdventure => Action Adventure
CardCollectiblePVP => Card Collectible PVP
Battle-RoyaleFantasyMOBA => Battle-Royale Fantasy MOBA
City-Building => City-Building
BuildingMMOStrategy => Building MMO Strategy
AdventureMMORPG => Adventure MMO RPG
ActionAdventureIdle => Action Adventure Idle
MOBARPGStrategy => MOBA RPG Strategy
MMORPGStrategy => MMO RPG Strategy
CardCollectibleIdle => Card Collectible Idle
Open-WorldPVPRPG => Open-World PVP RPG
DeFiMMOSpace => De Fi MMO Space
Collectible => Collectible
CardCollectiblePVP => Card Collectible PVP
Auto-BattlerDeFiRPG => Auto-Battler De Fi RPG
AdventureMMOOpen-World => Adventure MMO Open-World
CollectibleOpen-WorldVirtual-World => Collectible Open-World Virtual-World
CollectibleIdleRPG => Collectible Idle RPG
CardCollectiblePVP => Card Collectible PVP
ActionAdventurePVP => Action Adventure PVP
Sci-FiShooterSurvival => Sci-Fi Shooter Survival
ActionStrategy => Action Strategy
ArcadeMinigame => Arcade Minigame
BreedingPVPRacing => Breeding PVP Racing
MOBAPVP => MOBA PVP
ActionSports => Action Sports
PVPSpaceTurn-based => PVP Space Turn-based
MMOStrategyTower-Defense => MMO Strategy Tower-Defense

The [a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]) regex (see its demo) matches

*

*[a-z](?=[A-Z]) - a lowercase letter that is immediately followed with an uppercase letter

*| - or

*[A-Z](?=[A-Z][a-z]) - an uppercase letter followed with an uppercase letter and a lowercase letter.

We add a space after these matches.
rx_2 and rx_3 regexes are built from the list of ALLCAPS words and add a space on the left or right, depending on which side another letter appears.


text:
Q: GPGPU programming in Python I want to start GPGPU programming in Python. Should I start with pyopencl or clyther? What's the difference?

A: It seems to me that PyOpenCL is closer to the C bindings for OpenCL than CLyther.
This means that if you already know OpenCL, or plan to port implementations from other languages to Python, then PyOpenCL might be for you.  On the other hand, CLyther seems more "pythonic" than PyOpenCL, so if you are more familiar with Python, then the idioms used might be easier for you to understand.
Both of them are in Beta, so you might not have all of the features you might want in either, and there might be bugs in either.
Good luck!

A: OpenCL consists of two parts. There is a host-side which is typically written in C, and a device-side which is written in a derivative of C defined by OpenCL. This code is compiled to the device (typically a GPU) at run-time.
CLyther attempts to abstract everything out. You write the host-side code in Python. You write the device-side code in a subset of Python (in a similar way to Cython). This is very high level and easy-to-use.
PyOpenCL is a comparatively low-level binding to the OpenCL API from Python. Device-side code is written in OpenCL's subset of C99. It gives you full access to and full control of OpenCL. Very little is abstracted away.
I have limited experience with both, but my impression is that, once both are mature, I would prefer to use Clyther for most projects. It is more user-friendly, which means you're more likely to use it, and to use it more. It is also easier to shift code back and forth between Clyther and Python than PyOpenCL and Python, so code maintenance and refactoring should be easier. For very performance-critical projects, I would prefer PyOpenCL. It gives better low-level control, and fewer layers between you and the hardware. The ultimate possible performance should be better with PyOpenCL than with Clyther.
I do not know if this will continue to be the case forever. It is likely that PyOpenCL will, eventually, add higher-level constructs, and that Clyther will, eventually, add lower-level control. In an ideal world, the Clyther developers would move the core such that it was built on top of PyOpenCL, so we wouldn't have to choose, and to avoid duplication of labor. I doubt that will ever happen, though.
At present, PyOpenCL appears to be more mature than Clyther. It was started first, and is less ambitious in scope. It has better documentation than Clyther, and appears to have a bigger user community. Both are fairly similar in code size -- Clyther is about 4KLOCs of Python and 4KLOCs of C. PyOpenCL is about 7KLOCs of Python code, and 9KLOCs of C++ code. This is approximate (includes build systems, examples, etc), so should not be treated as implying anything beyond approximate equality.

A: CLyther contains bindings at the C level similar to OpenCL and PyOpenCL.
clyther is 'pythonic' in the fact that is also allows you to pass and or use python functions as openCL device/kernel functions.
Inline in your python code you can write
@kernel
@bind('global_work_size' ,'a.size')
@bind('local_work_size' , 1)
def sum(a,b,ret):
    i = clrt.get_global_id(0)
    ret[i] = a[i] + b[i]

sum(clarray1,clarray2,clarray3)

A: I feel PyOpenCl is similar to PyCuda that it allows you to do the multitude of optimizations on the kernel side which is the fun part of GPGPU programming.
This is the kernel in C whereas the host code is pythonic:
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
  const int i = threadIdx.x;
  dest[i] = a[i] * b[i];
}
""")