text:
Q: Change file owner group under Linux with java.nio.Files I have a Linux server and I'm running an image resize job in Java for multiple websites on my server. The website files are owned by different OS users/groups. Newly created thumbnails/previews are owned by the user running the resize job. Now I was googleing around how to change the file owner of newly created previews/thumbnails in my resize program and came across this:
java.nio.file.Files.setOwner(Path path, UserPrincipal owner);

This would really solve my problem if it was Windows, but since a Linux file has a user and a group as owner I'm a bit in trouble. Unfortunately given method seems to only change the user ownership of the file. The group ownership remains with the group of the user running my Java resize job.
The websites are owned by different groups, so adding my resize job user to one group is no option. I also want to avoid system calls with ProcessBuilder and execute a chown on my files.
I do need to point out that the created files (preview/thumbnail) can be accessed via the website and it is not mission critical to change the group ownership, but I wanted it to be as clean as possible.
Any suggestions how I can change the group ownership of a file in Linux only using Java?

A: Thanks Jim Garrison for pointing me in the correct direction. Here the code, which finally solved the problem for me.
Retrieve the group owner of a file
File originalFile = new File("original.jpg"); // just as an example
GroupPrincipal group = Files.readAttributes(originalFile.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).group();

Set the group owner of a file
File targetFile = new File("target.jpg");
Files.getFileAttributeView(targetFile.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);

A: Take a look at the package java.nio.file.attributes and classPosixFilePermissions. This is where you can manipulate group permissions.

A: I missed a complete solution, here it comes (combination of other answers and comments):
Path p = Paths.get("your file's Path");
String group = "GROUP_NAME";
UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
GroupPrincipal group = lookupService.lookupPrincipalByGroupName(group);
Files.getFileAttributeView(p, PosixFileAttributeView.class,
                LinkOption.NOFOLLOW_LINKS).setGroup(group);

Be aware that only the owner of a file can change its group and only to a group he is a member of...

A: The purpose of this response is to elevate one of the comments received in response to the original posting to a full response level, so that it is more prominently displayed.
Here is what worked for us:
//  newUser and newGroup are strings.

UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(newUser);
GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(newgroup);

Files.setAttribute(filePath, "posix:owner", userPrincipal, LinkOption.NOFOLLOW_LINKS);
Files.setAttribute(filePath, "posix:group", groupPrincipal, LinkOption.NOFOLLOW_LINKS);

Additionally we had to run the Java program as a superuser.


text:
Q: Centering google maps on a placeholder Does anyone know if its possible to center a embedded map on an actual placeholder? I mean so that that when the map loads and is centered you can actually see the landmark and the marker in the the map?
    function initialize() {
        var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(51.515727, -0.141388),
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
    }

This is my initialise function that inputs the coordinates of the shop I want to have directions to. However there is not placeholder (pin marker) over the shop. Am I able to do that?
Thanks!

A: function initialize() {
            var map_canvas = document.getElementById('map_canvas');
        var map_options = {
          center: new google.maps.LatLng(51.515727, -0.141388),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(map_canvas, map_options);

         var point = new google.maps.LatLng(51.515727, -0.141388);
        var marker = new google.maps.Marker({
            position:point,
            map: map,
        });
        }

A: You need to explicitly specify the marker and set its position. Following your example...
var map_canvas = document.getElementById('map_canvas');
 var position = new google.maps.LatLng(51.515727, -0.141388);
 var mapOptions = {
                zoom: 16,
                center: position,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

var map = new google.maps.Map(map_canvas, map_options);

You have to then create the marker object...
var marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: "ANYTHING YOU WANT"
                });

That's all you need to do really, but notice that you can always change the center of the map at anytime...
map.setCenter(position);

For more info visit the Developer's Site API Reference

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between gem and require (require open-uri) I just wanted to understand for my self.
I'm using the nokogiri gem (for parsing HTML). If I got it right to open URLs I need to use a method from the gem 'open-uri'.
But when I include it in my Gemfile (on Windows developer's machine):
gem 'open-uri' - there is an error while bundle install that it can not find gem.
So If I use require 'open-uri' - its working.
So can some explain what is going on?

A: require is used to load another file and execute all its statements. This serves to import all class and method definitions in the file. require also keeps track of which files have been previously required so it doesn't execute it twice.
A RubyGem is a software package, commonly called a "gem". Gems contain a packaged Ruby application or library. The RubyGems software itself allows you to easily download, install, and manipulate gems on your system.
 - What is a Gem?:
The Gemfile is then used by bundler to install the specified gems.
open-uri is not a gem but part of the Ruby Standard Library so it just needs to be required.

A: You're using bundler for your gem dependecies and you're doing it right but OpenUri is part of the Ruby standard library. That's why you only need to require it if you want to use it in your code.


text:
Q: Insert records in many to many not working with Entity Framework I want to insert 2 new records in their tables and also to create the relation many to many.
There are a lot of questions with this topic, I tried many of the answers and now I have no idea why my code is not working.
Please help me!
This is the code:
class Program
{
    static void Main(string[] args)
    {
        MyContext db = new MyContext();

        var st1 = new Student() { Name = "Joe" };
        var c1 = new Course() { Name = "Math" };

        db.Courses.Attach(c1);
        st1.Courses.Add(c1);
        db.Students.Add(st1);

        db.SaveChanges();
    }
}
public class Student
{
 public Student()
    {
        Courses = new HashSet<Course>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}
public class MyContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasMany(p => p.Courses)
            .WithMany(d => d.Students)
            .Map(t =>
            {
                t.MapLeftKey("studentId");
                t.MapRightKey("courseid");
                t.ToTable("StudentCourse");
            });

        base.OnModelCreating(modelBuilder);
    }

}

Edit: Like sugested, I initialized the Courses:
 public Student()
    {
        Courses = new HashSet<Course>();
    }

and now I get this error on db.SaveChanges();

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

A: You're apparently trying to add a new Student to the database and associate it to an existing Course. The problem is that you attach a new Course entity to the context without a proper primary key.
It certainly is a good idea to use a so-called stub entity here, because it saves a roundtrip to the database to fetch an existing Course, but the primary key is required for EF to create a correct association record. It's  even the only property you need to set in this Course stub:
var st1 = new Student() { Name = "Joe" };
var c1 = new Course() { CourseId = 123 };

db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);

If you want to add a new course and a new student, you should Add both of them:
db.Courses.Add(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);

A: Your code isn't initialising the ICollection object in either class.
public class Student
{
    private Student()
    {
        Courses = new List<Course>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

Edit
Try changing your modelBuilder code to the following
modelBuilder.Entity<Student>()
            .HasMany<Course>(s => s.Courses)
            .WithMany(c => c.Students)
            .Map(cs =>
                    {
                        cs.MapLeftKey("StudentRefId");
                        cs.MapRightKey("CourseRefId");
                        cs.ToTable("StudentCourse");
                    });

Code sample taken directly from:
http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx


text:
Q: Functional WebDav client I need to edit remotely folders located on Windows Server 2003. I read that webdav seems to behave quite unexpectedly with different versions of windows. Do you have some fully working solution with Windows7 64bit + Windows Server 2003 ?
If you are not for webdav, what do you recommend in this situation ? What protocol / client software?
Thanks.

A: no client, just:
cmd net * use "https://server/webdav" /user:%username% %password%

works for me on my win7x64

A: There are several good WebDAV clients available.  Two that come to mind are WebDrive and Expandrive.  WebDrive is a native 64bit application.  Not sure about Expandrive.  Here are the reviews on Spiceworks: WebDrive and Expandrive
NOTE: Spiceworks doesn't have a review category for WebDAV clients; both of these are listed under the FTP client category, but they do support WebDAV.


text:
Q: Multiprocess with shared variable in bash I'm trying to achieve a dynamic progress bar in bash script, the kind we see when installing new packages. In order to do this, a randomtask would call a progressbar script as a background task and feed it with some integer values.
The first script uses a pipe to feed the second.
#!/bin/bash
# randomtask

pbar_x=0            # percentage of progress
pbar_xmax=100

while [[ $pbar_x != $pbar_xmax ]]; do
    echo "$pbar_x"
    sleep 1
done | ./progressbar &

# do things
(( pbar_x++ ))

# when task is done
(( pbar_x = pbar_xmax ))

Hence, the second script needs to constantly receive the integer, and print it.
#!/bin/bash
# progressbar

while [ 1 ]; do
    read x
    echo "progress: $x%"
done

But here, the second script doesn't receive the values as they are updated. What did I do wrong ?

A: That can't work, the while loop is running in a subprocess, changes in the main program will not affect it in any way.
There are several IPC mechanisms, here I use a named pipe (FIFO):
pbar_x=0            # percentage of progress
pbar_xmax=100
pipename="mypipe"

# Create the pipe
mkfifo "$pipename"

# progressbar will block waiting on input
./progressbar < "$pipename" &

while (( pbar_x != pbar_xmax )); do
     #do things
     (( pbar_x++ ))
     echo "$pbar_x"
     sleep 1
     # when task is done
     #(( pbar_x = pbar_xmax ))
done > "$pipename"

rm "$pipename"

I also modified progressbar:
# This exits the loop when the pipe is closed
while read x
do
    echo "progress: $x%"
done

With a third script you could use process substitution instead.

A: I'm on WSL, which means I can't use mkfifo. And coproc seemed to perfectly answer my need, so I searched and eventually found this:
coproc usage with exemples [bash-hackers wiki].
We start the process with coproc and redirect its output to stdout:
{ coproc PBAR { ./progressbar; } >&3; } 3>&1

Then we can access its in and out via file descriptors ${PBAR[0]}(output) and  ${PBAR[1]}(input)
    echo "$pbar_x" >&"${PBAR[1]}"

randomtask
#!/bin/bash

pbar_x=0            # percentage of progress
pbar_xmax=100

{ coproc PBAR { ./progressbar; } >&3; } 3>&1

while (( pbar_x <= 10)); do
    echo $(( pbar_x++ )) >&"${PBAR[1]}"
    sleep 1
done

# do things
echo $(( pbar_x++ )) >&"${PBAR[1]}"

# when task is done
echo $(( pbar_x = pbar_xmax )) >&"${PBAR[1]}"

progressbar
#!/bin/bash

while read x; do
    echo "progress: $x%"
done

Please note that :

The coproc keyword is not specified by POSIX(R).
The coproc keyword appeared in Bash version 4.0-alpha


text:
Q: Spring JPA Hibernate query cache doesn't work I use Spring Boot 1.4.1 AND spring-boot-starter-data-jpa
When query my custom method like 'findByName(String name)' it's not cache.
But when query default method like 'findOne(Interger id)' it's work.
application.properties:
spring.jpa.properties.hibernate.cache.use_query_cache=true

Repository:
@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
    Author findByName(String name);
}

Tests:
public class RepositoryTests {
    @Autowired
    private AuthorRepository authorRepository;

    @Test
    @Transactional
    public void test() {
        authorRepository.save(new Author("admin"));

        // ***Not work. query **5** times.
        Author author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");
        author = authorRepository.findByName("admin");

        // ***It's work. query **1** times.
        Author author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
        author = authorRepository.findOne(1);
    }
}

A: @Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
    @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
    Author findByName(String name);
}

Should do the trick. (Note: the @Repository is not needed because you already extend CrudRepository)


text:
Q: How to save data for each loop? I want to save the dictionary  in Csv or mat file for each loop, the code is from the link FHN equations
   import scipy.io as sio
    trajectory_nonauto = {}
    file_out = f"out_{i}.mat"
    for i, param in enumerate(step_sc):
        flow = partial(non_autonomous_fitzhugh_nagumo, **param)
        for j, ic in enumerate(initial_conditions):
            trajectory_nonauto[i, j] = scipy.integrate.odeint(flow,y0=ic,t=time_span)
            sio.savemat(file_out, { trajectory_nonauto[i, j]})
            data = trajectory_nonauto
            print(trajectory_nonauto)

I was getting this error

TypeError: unhashable type: 'numpy.ndarray

at sio.savemat

A: By the looks of it savemat takes a dict as its second argument.
The thing you are trying to pass, { trajectory_nonauto[i, j]}, is not a dict.
The error you are seeing is because {x} creates a set with element x, and all elements of a set must be hashable.

A: instead of sio.savemat(file_out, { trajectory_nonauto[i, j]})
try sio.savemat(file_out, {"x-axis": trajectory_nonauto[i, j]})


text:
Q: What makes metric spaces have balls always containing points other than its center, too? Let $M$ be a metric space, $x\in M$, $\varepsilon>0$. What do we need from $M$ to guarantee
$$ \mathbb{B}(x,\varepsilon)\setminus\{x\} \neq\emptyset?$$
E.g., would it suffice to have $M$ be polish?

A: For any $x \in (M,d)$, there is some $r_x>0$ such that $\Bbb B(x,r_x)=\{x\}$ iff $x$ is an isolated point (i.e. $\{x\}$ is open).
So if you want this for all $x$, $M$ needs to be crowded (i.e. have no isolated points). Polish spaces can have isolated points, but a connected metric space will not have them, if it has more than one point of course. So if you want an easily quotable condition, just use "let $M$ be a crowded metric space" or a connected non-trivial metric space instead. Of course a space like $[0,1] \cup [2,3]$ we have disconnected crowded space, so the first condition is more to the point and exactly what you'd need.


text:
Q: How to select all in WHERE IN if parameter value is null? So, I have a stored procedure which receives a list of IDs, or no IDs at all.
If procedure receives no IDs, the select should return all rows as if WHERE IN isn't even there.
I've tried the following but I get a query with very long execution duration so clearly I'm not doing it right. Here's what I've tried.
-- some select
WHERE someId IN
(CASE
    WHEN @list IS NOT NULL
        THEN (SELECT col1 FROM fnIdArrayToTable (@list,','))
    ELSE
        someId
END)

Note: fnIdArrayToTable takes multiple IDs and returns a table containing those IDs

A: I would suggest trying exists:
where @list is null or
      exists (select 1
              from fnIdArrayToTable(@list, ',') l
              where l.col1 = ?.someId
             )

Note:  I don't know what your function is doing, so it might be impossible to speed up.
Assuming you have no duplicates in @list, then it might be better to move the logic to the from clause:
select . . .
from t left join
     fnIdArrayToTable(@list, ',') l
     on t.someid = l.col1
where l.col1 is not null or @list is null'


text:
Q: How can i query on embedded document using Spring data mongodb? My document structure looks like
{
   "users":[
            {
           "email":"user@company.com"
            "messages":[
                        {
                          "id":"1",
                          "text":"A",
                          "from":"Jessy",
                          "isDeleted":"false"
                        },{
                          "id":"2",
                          "text":"B",
                          "from":"Jessy",
                          "isDeleted":"false"
                        },{
                          "id":"3",
                          "text":"C",
                          "from":"Alan",
                          "isDeleted":"false"
                        },{
                          "id":"4",
                          "text":"D",
                          "from":"Amy",
                          "isDeleted":"true"
                        },{
                          "id":"5",
                          "text":"E",
                          "from":"Amy",
                          "isDeleted":"false"
                        }

            ]

            }
    ]

}

I want to query on sub document using or & and operations.So my query can be as follow.
select all those messages from the users collection having from as "Amy" and text is "E" or some other Criteria.
I have an idea about the Aggregation Framework supported by Spring data
AggregationOperation match =Aggregation.match(Criteria.where("from").is("Amy").and("text").is("E"));

AggregationOperation unwind = Aggregation.unwind("messages");

Aggregation aggregation = Aggregation.newAggregation(match);

AggregationResults<User> result = this.mongoTemplate.aggregate(aggregation, "users", User.class);

But my problem is that i want to dynamically populate the Criteria like Criteria is at clients end he or she can pass any query to the database i gonna parse that query into Criteria. Any help will be appreciated.


text:
Q: replace comma followed by a character by semicolon while keeping the same character Provided a vector like this: test = "Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other" I would like to replace all commas that are followed by alhpa character (not space) while preserving original alpha character, so I can later split multiple values within a cell by splitting by semicolon.
So far, I have used the following code:
> gsub(",\\S", ";", test)
[1] "Education & research;on-Profit (NGOs, foundations, associations...);overnment (local, regional, national);ndividuals;ther"

As you can see, I have replaced all commas (that's fine!) but I also deleted the first letter of the word following them! (that's wrong!). I get the same result if I type gsub(",[A-Z]", ";", test)
That's why I tried with
> gsub(",[A-Z]", ";[A-Z]", test)
[1] "Education & research;[A-Z]on-Profit (NGOs, foundations, associations...);[A-Z]overnment (local, regional, national);[A-Z]ndividuals;[A-Z]ther"

But the replacement doesn't seem to accept [A-Z] as replacement token for the original character.
Is there any way to achieve what I am looking for?

A: Brief
You can use a positive lookahead. Positive lookaheads assert that the given subpattern can be matched at that position without consuming characters.
Regex replacements are fairly literal in how they replace. So, as you've seen, a replacement of ;[A-Z] is literally used. Another way to achieve what you want is to make the next character part of a capture group such that your regex becomes ,([A-Z]) and you use the replacement of ;$1 (here $1 is a reference to the most recently matched text inside capture group 1). Although it's possible with groups, it's usually better to use assertions for things you don't actually want to replace (in this case the uppercase character) as my answer provides below.

Code
See regex in use here
,(?=[A-Z])

For Unicode support you can use ,(?=\p{Lu}). \p{Lu} means any uppercase character in any script/language. This will match, for example, É whilst [A-Z] will not.
Replacement: ;
Usage
gsub(",(?=[A-Z])",";","Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other", perl=TRUE)

Note: This regex uses a positive lookahead and, as such, gsub requires perl=TRUE to be passed.

Results
Input

Education & research,Non-Profit (NGOs, foundations,
  associations...),Government (local, regional,
  national),Individuals,Other

Output
Education & research;Non-Profit (NGOs, foundations, associations...);Government (local, regional, national);Individuals;Other

Explanation

*

*, Match a literal comma

*(?=[A-Z]) Positive lookahead ensuring what follows matches an uppercase ASCII letter


text:
Q: Compression of Binary file If we are given a binary file of length n, where each bit independently is one with probability 1/3 and zero else. We want to construct a method that the expected length of the compressed sequence is less than 10 percent more than Shannon's lower bound (for all n large enough).
    I've got the lower bound is 0.918. I tried to use tuples of size 2, but it gives me an expected length of 1.88 by Huffman coding. Am I going in the right direction?

*

*What if we want to get a 3% margin ?

A: The Shannon entropy bound is 0.918 output bits per input bit.
If you just write the bits you're given, you'll spend 1 output bit per input bit.
This is already less than 10% more than the bound, so no compression is required.

A: You can use Arithmetic compressor or Rangecoder.
There is explanation with code for Arithmetic compressor and open-source implementation of Rangecoder.
I personally recommend to use Rangecoder, because of it works fastest, and has never been patented (patent for arithmetic compressor already expired).


text:
Q: changing from inner joins to left joins to include null values? I need to have this query return all NULL Values for hours for each jobcode. I have tried to change the inner joins to left joins, but the output is the same (only showing the 1 jobcode for one date in the range). Do I need to change the cross join to an outer join as well?
SELECT EmployeeNumber,
   JobCode,
   [Date],
   SUM(Hours) as [Hours]
FROM
(
SELECT        tServiceReps.EmployeeNumber,
              tServiceHours.JobCode,
              tServiceReports.[Date],
              tServiceHours.[Hours]

FROM          AdjustUserRoleRequestStatusLookup
CROSS JOIN    tServiceJobCodes
INNER JOIN    tServiceHours
ON            tServiceJobCodes.ServiceJobCodes = tServiceHours.JobCode
INNER JOIN    tServiceReports
ON            tServiceHours.ReportNo = tServiceReports.ReportNo
INNER JOIN    tServiceReps
ON            tservicereports.employee = tservicereps.repid
INNER JOIN    tRegions
ON            tServiceReports.Region = tRegions.RegionCode

WHERE         Date between '2017-01-01' and '2017-01-05'

GROUP BY      tServiceReps.EmployeeNumber,
              tServiceHours.JobCode,
              tServiceReports.[Date],
              tServiceHours.[Hours]
) ctHours
GROUP BY EmployeeNumber, JobCode, [Date];

Output for inner select query

EmployeeNumber  JobCode      Date               Hours
10203             82    2017-01-03 00:00:00.000 3.00
10203             82    2017-01-04 00:00:00.000 3.50
10203             82    2017-01-05 00:00:00.000 3.00
10203             86    2017-01-02 00:00:00.000 8.00
10203            210    2017-01-03 00:00:00.000 5.00
10203            210    2017-01-05 00:00:00.000 5.00
10203            215    2017-01-04 00:00:00.000 4.50

@DominiqueBoucher  i understand your confusion. this was built by non-dba admins. servicehours and servicereports both contain the ReportNo column. servicehours also contains the jobcode column.
The query works where there is data to report against, the issue is, I need to see Null where no data exist.
an example of this, would be if I pull from 2018/01/05, no records should exist, but I need to see:
 employee#     jobcode      date             Hours
 12345                1              01/05/2018        0
 12345                2              01/05/2018        0

A: As I don't have the table definition and values Inside them, here's the code I used to do something "similar".
You can use it as inspiration... You may be able to adapt it to your situation.
 /*------------------------------------------------------------------ */
--create table tservicehours ([hours] float,jobcode int, reportno int);
--create table tServiceJobCodes (Servicejobcode int);
--create table tServiceReports (ReportNo int, [date] date, employee int);

--insert into tServiceReports values (1, '2017-01-03',10204), (2, '2017-01-04',10203), (3, '2017-01-05',10203), (4, '2017-01-02',10203), (5, '2017-01-03',10203), (6, '2017-01-05',10203), (7, '2017-01-04',10203);
--insert into tServiceJobCodes values (82),(86),(210),(215);
--insert into tservicehours values (3,82,1),(3.5,82,2),(3,82,3),(8,86,4),(5,210,5),(5,210,6),(4.5,215,7);

create table #date ([date] date);
insert into #date values ('2017-01-01'),('2017-01-02'),('2017-01-03'),('2017-01-04'),('2017-01-05');

select distinct #date.[date],tServiceJobCodes.Servicejobcode, tServiceReports.employee  into #temp from #date cross apply tServiceJobCodes cross apply tServiceReports;

with datas as (
select  date, [hours],  jobcode, employee
from tServiceReports r
join tservicehours h on h.reportno = r.reportno)

select distinct #temp.employee, #temp.[date], #temp.servicejobcode, datas.[hours] from #temp
left join datas on jobcode = #temp.Servicejobcode and datas.[date] = #temp.[date] and #temp.employee=datas.employee
where #temp.[date] between '2017-01-01' and '2017-01-05'
order by employee, servicejobcode;

drop table #date;
drop table #temp;
/* ----------------------------------------------------------------- */

*

*The general idea here is to create a temp table containing each day for every jobcode/employee and then use that table to join on the actual data.

I hope it will help.

A: Is there a way to make this top part loop 13 times after the initial run? only included the first 3 to save space.
DECLARE              @BegDate AS DATE, @EndDate as Date
SET                  @BegDate = '2017-11-19'
SET                  @EndDate = DATEADD(day, 13, @BegDate)

IF OBJECT_ID('tempdb..#TEMPLIST') IS NOT NULL DROP TABLE #TEMPLIST

SELECT *
INTO #TEMPLIST
FROM
   (      SELECT               tRegions.Region, COALESCE(tSubregions.Description,'') as SubRegion, tServiceReps.[Service Rep] as Service_Rep, tServiceReps.EmployeeNumber,
                                     DATEADD(day, 0, @BegDate) as Date, DATENAME(dw,@BegDate) as DOW
          FROM                 UnitDatabase.dbo.tServiceReps as tServiceReps
          LEFT OUTER JOIN      UnitDatabase.dbo.tSubregions as tSubregions on tServiceReps.Subregion = tSubregions.ID
          LEFT OUTER JOIN      UnitDatabase.dbo.tRegions as tRegions on tServiceReps.RegionCode = tRegions.RegionAcctCode and tRegions.Deactivated = 0
          Where                tServiceReps.RepID IN
                              (      SELECT        SR.RepID
                                     FROM          tServiceReps SR
                                     LEFT JOIN     tServiceReports SREP ON SR.RepID = SREP.Employee AND SREP.Date between @BegDate and @EndDate
                                     LEFT JOIN     tServiceHours AS SREPHRS ON SREP.ReportNo = SREPHRS.ReportNo
                                     WHERE         (SR.Deactivated = 0 AND SR.AllowUserToCreateServiceReport = 1)
                                            OR            (COALESCE(SREPHRS.Hours,0) + COALESCE(SREPHRS.OTHours,0)) > 0
                                     GROUP BY      SR.RepID      )
          ) AS TMP

INSERT
INTO #TEMPLIST (Region, Subregion, Service_Rep, EmployeeNumber, Date, DOW)
   (      SELECT               tRegions.Region, COALESCE(tSubregions.Description,'') as SubRegion, tServiceReps.[Service Rep] as Service_Rep, tServiceReps.EmployeeNumber,
                                     DATEADD(day, 1, @BegDate) as Date, DATENAME(dw,DATEADD(day, 1, @BegDate)) as DOW
          FROM                 UnitDatabase.dbo.tServiceReps as tServiceReps
          LEFT OUTER JOIN      UnitDatabase.dbo.tSubregions as tSubregions on tServiceReps.Subregion = tSubregions.ID
          LEFT OUTER JOIN      UnitDatabase.dbo.tRegions as tRegions on tServiceReps.RegionCode = tRegions.RegionAcctCode and tRegions.Deactivated = 0
          Where                tServiceReps.RepID IN
                              (      SELECT        SR.RepID
                                     FROM          tServiceReps SR
                                     LEFT JOIN     tServiceReports SREP ON SR.RepID = SREP.Employee AND SREP.Date between @BegDate and @EndDate
                                     LEFT JOIN     tServiceHours AS SREPHRS ON SREP.ReportNo = SREPHRS.ReportNo
                                     WHERE         (SR.Deactivated = 0 AND SR.AllowUserToCreateServiceReport = 1)
                                            OR            (COALESCE(SREPHRS.Hours,0) + COALESCE(SREPHRS.OTHours,0)) > 0
                                     GROUP BY      SR.RepID      ))

INSERT
INTO #TEMPLIST (Region, Subregion, Service_Rep, EmployeeNumber, Date, DOW)
   (      SELECT               tRegions.Region, COALESCE(tSubregions.Description,'') as SubRegion, tServiceReps.[Service Rep] as Service_Rep, tServiceReps.EmployeeNumber,
                                     DATEADD(day, 2, @BegDate) as Date, DATENAME(dw,DATEADD(day, 2, @BegDate)) as DOW
          FROM                 UnitDatabase.dbo.tServiceReps as tServiceReps
          LEFT OUTER JOIN      UnitDatabase.dbo.tSubregions as tSubregions on tServiceReps.Subregion = tSubregions.ID
          LEFT OUTER JOIN      UnitDatabase.dbo.tRegions as tRegions on tServiceReps.RegionCode = tRegions.RegionAcctCode and tRegions.Deactivated = 0
          Where                tServiceReps.RepID IN
                              (      SELECT        SR.RepID
                                     FROM          tServiceReps SR
                                     LEFT JOIN     tServiceReports SREP ON SR.RepID = SREP.Employee AND SREP.Date between @BegDate and @EndDate
                                     LEFT JOIN     tServiceHours AS SREPHRS ON SREP.ReportNo = SREPHRS.ReportNo
                                     WHERE         (SR.Deactivated = 0 AND SR.AllowUserToCreateServiceReport = 1)
                                            OR            (COALESCE(SREPHRS.Hours,0) + COALESCE(SREPHRS.OTHours,0)) > 0
                                     GROUP BY      SR.RepID      ))

INSERT
INTO #TEMPLIST (Region, Subregion, Service_Rep, EmployeeNumber, Date, DOW)
   (      SELECT               tRegions.Region, COALESCE(tSubregions.Description,'') as SubRegion, tServiceReps.[Service Rep] as Service_Rep, tServiceReps.EmployeeNumber,
                                     DATEADD(day, 3, @BegDate) as Date, DATENAME(dw,DATEADD(day, 3, @BegDate)) as DOW
          FROM                 UnitDatabase.dbo.tServiceReps as tServiceReps
          LEFT OUTER JOIN      UnitDatabase.dbo.tSubregions as tSubregions on tServiceReps.Subregion = tSubregions.ID
          LEFT OUTER JOIN      UnitDatabase.dbo.tRegions as tRegions on tServiceReps.RegionCode = tRegions.RegionAcctCode and tRegions.Deactivated = 0
          Where                tServiceReps.RepID IN
                              (      SELECT        SR.RepID
                                     FROM          tServiceReps SR
                                     LEFT JOIN     tServiceReports SREP ON SR.RepID = SREP.Employee AND SREP.Date between @BegDate and @EndDate
                                     LEFT JOIN     tServiceHours AS SREPHRS ON SREP.ReportNo = SREPHRS.ReportNo
                                     WHERE         (SR.Deactivated = 0 AND SR.AllowUserToCreateServiceReport = 1)
                                            OR            (COALESCE(SREPHRS.Hours,0) + COALESCE(SREPHRS.OTHours,0)) > 0
                                     GROUP BY      SR.RepID      ))
--repeats 14 times total

select TMPLST.Region, TMPLST.Subregion, TMPLST.Service_Rep,
TMPLST.EmployeeNumber, TMPLST.Date, TMPLST.DOW, COALESCE(REST.REGWORK,0) AS
REGWORK, COALESCE(REST.OTWORK,0) AS OTWORK, COALESCE(REST.PTO,0) AS PTO,
COALESCE(REST.HOL,0) AS HOL, COALESCE(REST.SICK,0) AS SICK,
COALESCE(REST.JURY,0) AS JURY, COALESCE(REST.MIL,0) AS MIL,
COALESCE(REST.OTHERPTO,0) AS OTHERPOT, COALESCE(REST.TOTALWORK,0) AS
TOTALWORK, COALESCE(REST.TOTALOFF,0) AS TOTALOFF

FROM   #TEMPLIST TMPLST
LEFT JOIN (

SELECT Region, SubRegion, Service_Rep, EmployeeNumber, Date, DOW,
SUM(REGWORK) AS REGWORK, SUM(OTWORK) AS OTWORK, SUM(PTO) AS PTO, SUM(HOL) AS
HOL, SUM(SICK) AS SICK, SUM(JURY) AS JURY, SUM(MIL) AS MIL, SUM(OTHERPTO) AS
OTHERPTO, SUM(REGWORK) + SUM(OTWORK) AS TOTALWORK, SUM(PTO) + SUM(HOL) +
SUM(SICK) + SUM(JURY) + SUM(MIL) + SUM(OTHERPTO) AS TOTALOFF
FROM (
                 Select tRegions.Region
                       ,      COALESCE(tSubregions.Description,'') as
SubRegion
                       ,      tServiceReps.[Service Rep] as Service_Rep
                       ,      tServiceReps.EmployeeNumber
                       ,      CAST(tServiceReports.Date AS DATE) DATE
                       ,      DATENAME(dw,tServiceReports.Date) as DOW
                       ,      CASE WHEN JobCode = 85 THEN
SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS PTO
                       ,      CASE WHEN JobCode = 86 THEN
SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS HOL
                       ,      CASE WHEN JobCode = 92 THEN
SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS JURY
                       ,      CASE WHEN JobCode = 93 THEN SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS MIL
                       ,      CASE WHEN JobCode = 89 THEN SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS OTHERPTO
                       ,      CASE WHEN JobCode = 88 THEN SUM(COALESCE(tServiceHours.Hours,0) + COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS SICK
                       ,      CASE WHEN JobCode NOT IN (85,86,92,93,89,88) THEN SUM(COALESCE(tServiceHours.Hours,0)) ELSE 0 END AS REGWORK
                       ,      CASE WHEN JobCode NOT IN (85,86,92,93,89,88) THEN SUM(COALESCE(tServiceHours.OTHours,0)) ELSE 0 END AS OTWORK
                 From   UnitDatabase.dbo.tServiceReps as tServiceReps
                 LEFT OUTER JOIN      UnitDatabase.dbo.tServiceReports as tServiceReports ON (tServiceReports.Employee = tServiceReps.RepID) AND (tServiceReports.Date between @BegDate and @EndDate)
                 LEFT OUTER JOIN UnitDatabase.dbo.tServiceHours as tServiceHours on (tServiceReports.ReportNo = tServiceHours.ReportNo)
                 LEFT OUTER JOIN UnitDatabase.dbo.tServiceJobCodes as tServiceJobCodes on (tServiceHours.JobCode = tServiceJobCodes.ServiceJobCodes)
                 LEFT OUTER JOIN      UnitDatabase.dbo.tSubregions as tSubregions on tServiceReps.Subregion = tSubregions.ID
                 LEFT OUTER JOIN      UnitDatabase.dbo.tRegions as tRegions on tServiceReps.RegionCode = tRegions.RegionAcctCode and tRegions.Deactivated = 0
                 GROUP BY      tRegions.Region, COALESCE(tSubregions.Description,''), tServiceReps.[Service Rep], tServiceReps.EmployeeNumber, tServiceReports.Date, DATENAME(dw,tServiceReports.Date), JobCode
          ) TMP
GROUP BY      Region, SubRegion, Service_Rep, EmployeeNumber, Date, DOW
) AS REST ON TMPLST.Service_Rep = REST.Service_Rep AND TMPLST.Date = REST.Date
Order by      TMPLST.Region,
                 TMPLST.Service_Rep,
                 TMPLST.Date


text:
Q: relative order, sort change
The rendering order of images can be changed by user. I want to recalculate the pixels only if two images changed position between them.
The images can change position in groups(without changing inner order). Which is a gaps and islands problem.
indexing groups
SUM(CASE WHEN lagged_new_sort_mines_old_sort = new_sort - old_sort)
grouping vectoral geometry and placements
 MIN(new_sort), MIN(old_sort), ST_UNION(geom)
then used DENSE_RANK to have ordered view
 DENSE_RANK() OVER (ORDER BY new_sort) AS new_order
 DENSE_RANK() OVER (ORDER BY old_sort) AS old_order
The problem: When an order changes it shifts the queue.
Pay attention to row 17. The old third took the place of old second.
Pay attention to row 31. It looks like unchanged but its relative placement dropped by 15 image groups (old_order of [1-4] is above 200)
I got stuck and lost my view.
I need the indexes of group geometries that I need to get overlaped area


text:
Q: Get downloaded file from submit button requests python I want to save locally the configuration file from my cable modem. I already have logged into the html admin page of the modem and inside the backup page, there is a button to backup the configuration file. Inside the event, there is a POST method on the form that leads to the next url:
https://192.168.1.1/goform/BackUp
The response headers are:
HTTP/1.0 200 OK
Server: GoAhead-Webs
Pragma: no-cache
Cache-control: no-cache
Content-Type: application/download
Content-Disposition: attachment; filename=cmconfig.cfg // This is the file that is downloaded when I click in the BackUp button

And this are the parameters that I pass to the POST function:
dir: admin/
file: cmconfig.cfg

So far, I have this code:
with requests.Session() as s:  # To login into the modem
    pagePostBackUp = 'https://192.168.1.1/goform/BackUp'
    s.post(urlLogin, data=loginCredentials, verify=False, timeout=5)
    dataBackUp = {'dir': 'admin/','file': 'cmconfig.cfg'}
    resultBackUp = s.post(pagePostBackUp, data=dataBackUp, verify=False, timeout=10)

What should be the next line to save the cmconfig.cfg file locally?

A: Your resultBackUp is a response object, so you could use its text or json methods.
print(resultBackUp.text)


text:
Q: Hiding hardware button of Android Devices my mobile device(Xperia TX) have three Buttons.
Now , Is it possible to hide the mobile's buttons? (Buttons in white border in below image) :

A: use this code in your onCreate() method :
    View bView = getWindow().getDecorView();
    bView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

A: Try below code.
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}


text:
Q: How to draw a polyline in kivy garden mapview? I'm doing a project related to routes and lines of buses.
If I have a list of coordinates describing the route of the line, how can I connect Cordianta and Corradeta and draw a small line connecting them?
Each bus route has about 500 coordinates that describe the route of the line.
For those who did not understand, this is a kind of MOOVIT application
I will thank anyone who helps!


text:
Q: 406 Error when receiving String I am using this code to send a request from Android to a Spring server. The method in Spring must return a String, but doesnt works:
idstringtoparse=CustomHttpClient.executeHttpPost(urlGetUserIdByUsername, params);

Being the method executeHttpPost this way:
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {

     BufferedReader in = null;
     try{
         HttpClient client = getHttpClient();
         HttpPost request = new HttpPost(url);
         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters,"UTF-8");
         formEntity.setContentEncoding(HTTP.UTF_8);
         request.setEntity(formEntity);
         request.setHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
         HttpResponse response = client.execute(request);
         in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
         StringBuffer sb = new StringBuffer("");
         String line = "";
         String NL = System.getProperty("line.separator");
         while ((line = in.readLine()) != null) {
              sb.append(line + NL);
         }

         String result = sb.toString();

         return result;
     }
}

In the server, the code is like this:
@RequestMapping ("usuario/getIdUserByUsername")
@ResponseBody
public Long getUserIdByUsername(@RequestParam String username){

    Long id=(long)usuarioService.getUserIdByUsername(username);
    usuarioService.getUserIdByUsername(username);
    return id;
}

This way, I am receiving a 406 error saying "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers"
Its a bit strange, since I am using that very same method in my app before this point to log ing the server, and it is working perfectly.

A: This looks suspicious
request.setHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");

Try this
request.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");

Along with
@RequestMapping(value = "usuario/getIdUserByUsername", method = RequestMethod.POST, headers = {"Accept=application/x-www-form-urlencoded"})


text:
Q: Different reference returned from Process.Start ProcessStartInfo psi = new ProcessStartInfo(BatchFile)

Process p = Process.Start(psi)

Why p.ID is different than process id visible in WindowsTaskManager
(BatchFile is path to external program with appropriate parameters)

A: I assume BatchFile is some kind of cmd or bat file that runs other processes one by one.
So in Windows Task Manager you actually see ids of those processes that are run by batch file.
Examples
If I do this
 var p = Process.Start("notepad.exe");

p.Id will match to the PID from Task Manager.
However, if I do this:
 var p = Process.Start("test.cmd"); // test.cmd has notepad.exe call inside

p.Id will be different from PID shown in the Task Manager.

A: I would assume that it's because p.ID is the id of the process that's running the batch file rather than the id of the process started by the batch file.
You can start the executable directly by Process.Start by using the correct overload

A: A process ID is only meaningful while the process is alive. The first thing to check is .HasExited - if this is true, ignore the process ID; it no longer has any meaning.
There are a number of ways you can start something and have no process left even though you can apparently see it still on screen:

*

*if it is a script/bat/cmd that spawns something and exits (remember: you are watching the script, not the "something")

*if the exe does some inter-exe voodoo internally - for example, most of the office apps and internet explorer do this; if there is an existing process, it forwards the args to that process to handle, and exits immediately


text:
Q: MYSQL,PHP,MEMCACHED - Display recent 20 posts along with recent four comments I am analyzing different approaches to display the recent 20 posts along with latest 4 comments for each post . This is some what like facebook wall , but won't have likes,share and any other
Example Table Structure

posts

*

*p_id = the number of that post

*user_id = user they are posting about

*poster_user_id = the person making the post

*post

comments

*

*comment_id = the number of that comment

*post_id = the number of the post the comment is related to

*commenter_user_id = the person who is making that comment

*comment
The approaches comes to my mind
1) Query POST table and get the recent 20 posts , send the post ID's to the database and get the comments from COMMENT table. But for this total calls will be
1(posts)+20(comments)=21 DB calls
2)  Join POST and COMMENT table and get all the comments for the recent 20 posts and when displaying check for the previous POST_ID and if it is same do not display the post , but only the comment . But this approach
gets lot of unnecessary data
3) Query POST table and get the recent 20 posts,get post IDs, construct comments query dynamically (in PHP that creates below kind of query)
 SELECT comment FROM comments WHERE post_id=<1st latest_id> ORDER BY comment_id desc LIMIT 4
UNION ALL
 SELECT comment FROM comments WHERE post_id=<2nd latest_id> ORDER BY comment_id desc LIMIT 4
UNION ALL
 SELECT comment FROM comments WHERE post_id=<3rd latest_id> ORDER BY comment_id desc LIMIT 4
....................up to 20

Here you will have only
1(posts)+1(comment ) = two database calls
This approach looks OK
4) Use the third approach and store the result in memcached for one minute or in 30 seconds . In case user makes any comment or new post,  use jquery and update his entry in the browser . In case if he presses refresh send a flag to the server to query the database again and store them in memcached .
This approach only requires 1 or 2 database calls in a minute, but again user gets the data that was posted one minute ago , not recent one .. this is fine for regular forums
5) Even instead of querying database for every minute , very first time get the top 20 posts from database and keep them in memcached along with comments  . Whenever user writes a new post , remove the 20th post from memcached and add the new post as 1st top post . Also for comments remove the 4th comment and attach the new comment to the post . But this requires a development work . Of course we have to save the record to database ( or can follow some group commit in case required) .
This looks like best approach for me , if we code perfectly
Any one has any other approaches or any good links to implement 5th approach ? ( updating memcached )
Thanks all for your help

A: Using user variable trickery:
SELECT   post_id, comment_id
FROM     (
  SELECT   post_id, comment_id,
           @i := IF(@type <=> post_id, @i+1, 0) AS comment_number,
           @p := post_id
  FROM     comments NATURAL JOIN (SELECT * FROM (
             SELECT p_id AS post_id FROM posts ORDER BY p_id DESC LIMIT 20
           ) z) z, (SELECT @type:=NULL) init
  ORDER BY post_id DESC, comment_id DESC
) t
WHERE    comment_number < 4
ORDER BY post_id DESC, comment_id DESC

This still requires that a temporary table t be populated from all of those posts' comments, then filtered (in the outermost query) for only the top 4.  One could avoid this with a suitably ordered compound index on (post_id, comment_id):
SELECT   post_id, comment_id,
         @i := IF(@type <=> post_id, @i+1, 0) AS comment_number,
         @p := post_id
FROM     comments FORCE INDEX (index_name) NATURAL JOIN (SELECT * FROM (
           SELECT   DISTINCT post_id
           FROM     comments
           ORDER BY post_id DESC
           LIMIT    20
         ) z) z, (SELECT @type:=NULL) init
GROUP BY post_id DESC, comment_id DESC
HAVING   comment_number < 4


text:
Q: Use QR factorizations to find intersection of two planes This question is Problem $7.4$ in Numerical Linear Algebra by Lloyd N. Trefethen and David Bau, III.

Problem $7.4$: Let $\newcommand{\1}{^{(1)}}
\newcommand{\2}{^{(2)}}
\newcommand{\ip}[1]{\left \langle #1 \right \rangle}
x\1,y\1,x\2,$ and $y\2$ be nonzero vectors in $\mathbb{R}^3$ with the property that $x\1$ and $y\1$ are linearly independent and so are $x\2$ and $y\2$. Consider the two planes in $\mathbb{R}^3$,
$$
P\1 = \ip{x\1,y\1} \qquad P\2 = \ip{x\2,y\2}
$$
Suppose we wish to find a nonzero vector $v \in \mathbb{R}^3$ which lies in the intersection of the planes, $P = P\1 \cap P\2$, the intersection of the planes. Devise a method for solving this problem by reducing it to the computation of the QR factorizations of three $3 \times 2$ matrices.

I can numerically compute the $QR$ factorization but I don't see how I could find the three matrices and how that would help me find the intersection of $P^{(1)}$ and $P^{(2)}$.

A: Consider matrices $\newcommand{\nc}{\newcommand}
\nc{\para}[1]{\left( #1 \right)}
\nc{\abs}[1]{\left| #1 \right|}
\nc{\br}[1]{\left[ #1 \right]}
\nc{\set}[1]{\left\{ #1 \right\}}
\nc{\ip}[1]{\left \langle #1 \right \rangle}
\nc{\n}[1]{\left\| #1 \right\|}
\nc{\norm}[1]{\left\| #1 \right\|}
\nc{\floor}[1]{\left \lfloor #1 \right \rfloor}
\nc{\ceil}[1]{\left \lceil #1 \right \rceil}
\nc{\setb}[2]{\set{#1 \, \middle| \, #2}}
\nc{\dd}{\mathrm{d}}
\nc{\dv}[2]{\frac{\dd #1}{\dd #2}}
\nc{\p}{\partial}
\nc{\pdv}[2]{\frac{\partial #1}{\partial #2}}
\nc{\a}{\alpha}
\nc{\b}{\beta}
\nc{\g}{\gamma}
\nc{\d}{\delta}
\nc{\ve}{\varepsilon}
\nc{\t}{\theta}
\nc{\m}[1]{\begin{bmatrix} #1 \end{bmatrix}}
\nc{\C}{\mathbb{C}}
\nc{\N}{\mathbb{N}}
\nc{\R}{\mathbb{R}}
\nc{\P}{\mathbb{P}}
\nc{\Q}{\mathbb{Q}}
\nc{\Z}{\mathbb{Z}}
\nc{\AA}{\mathcal{A}}
\nc{\BB}{\mathcal{B}}
\nc{\CC}{\mathcal{C}}
\nc{\FF}{\mathcal{F}}
\nc{\GG}{\mathcal{G}}
\nc{\II}{\mathcal{I}}
\nc{\JJ}{\mathcal{J}}
\nc{\KK}{\mathcal{K}}
\nc{\PP}{\mathcal{P}}
\nc{\RR}{\mathcal{R}}
\nc{\SS}{\mathcal{S}}
\nc{\TT}{\mathcal{T}}
\nc{\1}{^{(1)}}
\nc{\2}{^{(2)}}
\nc{\i}{^{(i)}}
M\1,M\2$ where
$$
M\i := \br{ x\i \, \middle| \, y\i }
$$
and generate corresponding full QR factorizations $M\i = Q\i R\i$.
Recall that $M\i \in \C^{3 \times 2}$, so in the QR factorization, for $Q\i$ to be square, it needs to be "padded out" with an additional column (one that is missing from the other two one would find in the reduced QR factorization via, say, Gram-Schmidt).
Call this extra column  $q\i$. By the orthogonality of the other two, it holds that $q\i \perp P\i$. Form a new matrix,
$$
\widetilde{M} := \br{ q\1 \, \middle| \, q\2 }
$$
Each column is a unit normal for its respective plane. Of course, this matrix also has a full QR factorization, $\widetilde{M} = \widetilde{Q} \widetilde{R}$. If a vector $v$ lies in $P\1 \cap P\2$, it must be perpendicular to the normals of both planes, to the first two columns of $\widetilde{Q}$.
It is then easy to see that the line containing $v$ must be perpendicular to those columns - hence, in the span of third column of $\widetilde{Q}$.


text:
Q: Joomla unable to update in localhost I'm working with Joomla 3 on localhost
but when i change something in administrator nothing changes in site.
tried changing menu,edititing article even disabling modules .nothing works.
template:JA-NEX
what do you guys think?

A: I used this to setup Joomla 3 as local host and it worked fine.
http://magazine.joomla.org/issues/issue-mar-2013/item/1110-free-e-book-%E2%80%93-introducing-joomla-30-made-easy
hope it helps. sorry but dont have reputation to add comments, so had to be answer.


text:
Q: Cannot set quota for user - numerical result out of range When running following command:
setquota -ua username 4718592 5242880 0 0

I get this error:
setquota: Cannot set quota for user 1002 from kernel on /dev/mapper/hostname--vg-root: Numerical result out of range

The command is called by a script on a webserver, which manages the users (websites). This system has been used for the last year without any problems. There are 183 users, which have set quotas (15gb each). I was thinking that the cause might were the sum of the quotas that exceeded the space on the disk, but its around 240gb, so the problem should have started at a lower usercount.
I have tried to set quotas on one of the users to just a little more space than he's using atm, but I got the same error.
What to do?
Thanks in advance

A: I know it is an antediluvian question but I stumbled on the same problem recently and here is the solution that worked for me.
For large quotas (for me >4Tb) one needs to use the 64 bits format of quotas vfsv1:
In /etc/fstab after "defaults" or whatever options you already set, insert:
grpjquota=quota.group,usrjquota=quota.user,jqfmt=vfsv1
Then:
$ sudo mount -o remount /home
$ quotacheck -cug -F vfsv1 /home


text:
Q: Can webpack import staticly with a dynamic path I have a project using TypeScript, Webpack, React and Gatsby, and I want to import a whole bunch of images of different resolutions and webp versions for performance.
I've started importing my images:
import Project1Screenshot640 from './images/projects/screenshots/640/project1.jpg'
import Project1Screenshot1280 from './images/projects/screenshots/1280/project1.jpg'
import Project1Screenshot1526 from './images/projects/screenshots/1526/project1.jpg'
import Project1Screenshot640Webp from './images/projects/screenshots/640/project1.webp'
import Project1Screenshot1280Webp from './images/projects/screenshots/1280/project1.webp'
import Project1Screenshot1526Webp from './images/projects/screenshots/1526/project1.webp'
// ... I've skipped the rest because it is a long list of imports.

const projects = {
  'project-1': {
    title: 'Project 1',
    screenshot: {
      640: [Project1Screenshot640, Project1Screenshot640Webp],
      1280: [Project1Screenshot1280, Project1Screenshot1280Webp],
      1526: [Project1Screenshot1526, Project1Screenshot1526Webp],
    },
  },
  // ...
}

But I've realised this is highly unmaintainable and it would be much better to generate these imports at compile time.
Something like the following would be better...
const generateProject = (id, title) => {
  import Screenshot640 from `./images/projects/screenshots/640/${id}.jpg`
  // ...
  import Screenshot640Webp from `./images/projects/screenshots/640/${id}.webp`
  // ...

  return {
    title,
    screenshot: [
      640: [Screenshot640, Screenshot640Webp],
      // ...
    ],
  }
}

const projects = {
  'project-1': generateProject('project-1', 'Project 1')
}

But unfortunately you cant import with a dynamic path (that I know of) without doing it asynchronously with const Screenshot640 = await import('...').

If there anyway I can generate this list of project imports using webpack/gatsby during build which will be available in the compiled code?

A: You can use require instead of import which will lazy load at compile time.

*

*require: lazy load at compile time.

*import: lazy load at runtime.
Source: https://github.com/webpack/webpack/issues/6125#issuecomment-351642743


text:
Q: Why the number of blocks is always a multiple of 8? $ stat -c %s,%o,%b foo.txt
631,4096,8
$ stat -c %s,%o,%b bar.txt
5952,4096,16

Why the number of blocks is always a multiple of 8? I thought the number of blocks of a file is the smallest integer that satisfies filesize <= blocksize * blockcount.

A: %b returns the number of blocks on the filesystem that are allocated for the file, where each block is 512 bytes. Since the smallest block on the filesystem is 4kB, the number of blocks returned by stat will always be a multiple of 8 (4096 ÷ 512 = 8).


text:
Q: What is the entry point of a Django app similar to main.py? Where do I set up parameters? I want to set up some parameters and initialize the Injector object, because I want to use a dependency injection and singletons in my Django app.
Usually I do that in the main.py of my app but with Django I don't see where the first entry point of the application is when it runs. Where shoud I initialize the injector and pass it my views and services?
I have a view like this:
from uuid import UUID
from django.shortcuts import render
from django.http.response import JsonResponse
from django.http.request import HttpRequest
from rest_framework import viewsets, status
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from Instruments.services import InstrumentsService
from rest_framework.decorators import api_view
from Instruments.services import InstrumentsService
from injector import singleton, inject

# Application views live here
@singleton
class InstrumentViewSet(viewsets.ModelViewSet):
    @inject
    def __init__(self, instrument_service: InstrumentsService, **kwargs):
        self.instrument_service = instrument_service
        super().__init__(**kwargs)

    def list(self, request: HttpRequest):
        data = {}

        try:
            data = self.instrument_service.get_instruments()
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_400_BAD_REQUEST,
                safe=False,
            )

    def create(self, request):
        instrument_data = JSONParser().parse(request)
        data = {}

        try:
            data = self.instrument_service.add_instrument(instrument_data)
            return JsonResponse(data, status=status.HTTP_201_CREATED, safe=False)
        except Exception as exc:
            return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST, safe=False)

    def retrieve(self, request, pk: UUID = None):
        data = {}

        try:
            data = self.instrument_service.get_instrument_by_id(pk)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

    def update(self, request, pk: UUID = None):
        instrument_data = JSONParser().parse(request)
        data = {}

        try:
            data = self.instrument_service.update_instrument_by_id(pk, instrument_data)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

    def destroy(self, request, pk: UUID = None):
        data = {}
        try:
            data = self.instrument_service.delete_instrument_by_id(pk)
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_404_NOT_FOUND,
                safe=False,
            )

and a service like this:
import uuid
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework import status
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer
from django.shortcuts import get_object_or_404
from injector import inject, singleton

@singleton
class InstrumentsService:
    @inject
    def __init__(self, instruments: Instrument):
        self.instruments = instruments.objects.all()

    def get_instrument_by_id(self, id: uuid.UUID):
        try:
            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        return serializer.data

    def update_instrument_by_id(self, id: uuid.UUID, instrument_data: dict):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments, data=instrument_data)

            if serializer.is_valid():
                serializer.save()

            else:
                raise ValidationError(
                    "The data provided for updating an instrument are not valid"
                )

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def delete_instrument_by_id(self, id: uuid.UUID):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)
            instruments.delete()

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def get_instruments(self):
        serializer = InstrumentsSerializer(self.instruments, many=True)

        return serializer.data

    def add_instrument(self, instrument_data: Instrument):

        serializer = InstrumentsSerializer(data=instrument_data)

        if serializer.is_valid():
            serializer.save()
        else:
            raise ValidationError(
                "The data provided for registering a new instrument are not valid"
            )

        self.instruments = Instrument.objects.all()
        return serializer.data

where would someone inilialize the injector to create the dependencies?

A: Maybe you can look at Django Applications
In you application folder, you probably have an apps.py file:
from django.apps import AppConfig

class MyApp(AppConfig):

    def ready(self):
        # do stuff here

This is the entry point of your application.
Edit:
There is a project that already do that: django-injector

A: OK I made the dependency injection work the problem was not the injector it was the fact that in the class InstrumentsService: posted above I was trying to do :
def __init__(self, instruments: Instrument):
    self.instruments = instruments.objects.all()

but the object manager is not accesible for Django object thourgh objects (clas instances) but directly through the class. SO if I correct the class InstrumentsService: to this and also use this django-injector module Django injector everything works:
import uuid
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework import status
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer
from django.shortcuts import get_object_or_404

class InstrumentsService:
    def __init__(self):
        self.instruments = Instrument.objects.all()

    def get_instrument_by_id(self, id: uuid.UUID):
        try:
            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        return serializer.data

    def update_instrument_by_id(self, id: uuid.UUID, instrument_data: dict):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments, data=instrument_data)

            if serializer.is_valid():
                serializer.save()

            else:
                raise ValidationError(
                    "The data provided for updating an instrument are not valid"
                )

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def delete_instrument_by_id(self, id: uuid.UUID):
        try:

            instruments = get_object_or_404(self.instruments, pk=id)
            serializer = InstrumentsSerializer(instruments)
            instruments.delete()

        except Instrument.DoesNotExist as exc:
            raise NotFound(f"No items where found with the given id {id}")

        self.instruments = Instrument.objects.all()
        return serializer.data

    def get_instruments(self):
        serializer = InstrumentsSerializer(self.instruments, many=True)

        return serializer.data

    def add_instrument(self, instrument_data: Instrument):

        serializer = InstrumentsSerializer(data=instrument_data)

        if serializer.is_valid():
            serializer.save()
        else:
            raise ValidationError(
                "The data provided for registering a new instrument are not valid"
            )

        self.instruments = Instrument.objects.all()
        return serializer.data


text:
Q: Why do most X keyboard layouts only use the right alt as a modifier key? I've been typing in a language that requires use of the modifier key a lot lately, and I noticed it was starting to hurt my right hand from the weird contortions required to simultaneously press the right alt (Alt Gr) while typing keys on the right side of the keyboard. So I set up my layout to use both alts as modifier keys, which was easy and worked perfect, but it did make me wonder: why do most of the default keyboard layouts only use the right alt anyway? Is it just for historical reasons? If so, what are they?
xkb provides several options for what to use as a modifier keys. Here's what /usr/share/X11/xkb/symbols/level3 has to say about the option to use both alts:
// Either Alt key (while pressed) chooses the third shift level.
// (To be used mostly to imitate Mac OS functionality.)
partial modifier_keys
xkb_symbols "alt_switch" {
  include "level3(lalt_switch)"
  include "level3(ralt_switch)"
};

If that's how it works in Mac OS, then I like it! Why not copy it?
I did a quick search of both options in my /usr/share/X11/xkb/symbols and I found 344 keyboard layouts that use ralt_switch, and only 4 that use both.
Edit 1:
In the process of researching this question I discovered one possible answer: it breaks all the keyboard shortcuts that used to use the left alt key! Though it seems one could get around that by making those shortcuts accept either alt key too... I'm still playing with this, and it may yet prove that this is actually worse overall for some reason, but in principle my question stands (if this is really how it works in Mac OS, presumably Apple figured out a way to get around all these potential problems that arise, and we could do whatever they do).


text:
Q: Script finds the necessary file when running through IDLE, but cannot find the file when running through terminal I have a python script that uses Selenium to get my grades for my classes every hour and sends me an email if my grades have been changed.
I have an external file that gets referenced to see if there has been any change since the last write.
When I test the program by pressing F5 when in the IDLE, it works just as intended. But when I go to my terminal and type python3 /home/pi/Desktop/gradesNotification/script.py it works all the way up until it needs to open the text file with my grades. I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'grades'

The text file is in the same folder as the script. The program works when ran through IDLE, but does not work when started from terminal.

A: File names are given with respect to cwd, the current working directory.  It's possible that your cwd in IDLE is the directory where the grades reside, but that your terminal window is elsewhere.  Try changing to the proper directory, or specify the full path of the grades file.
Another way is to have your program check its own location, and try to open grades from there.

A: I suppose the easiest fix to your problem would be specifying an absolute path to the grades file in your code:
"/home/pi/Desktop/gradesNotification/grades"

However, it would not be very pretty or flexible - here is a great article on handling file system access from Python using pathlib library.


text:
Q: Deleted File, Available Space Did Not Return On CentOS linux, I just deleted a large log file over 3gb on XFS file system. After deleting the file, the available file space did not return to the drive seen via df -h. Is there anything I can do to find the missing free space?

A: You can either reboot or terminate the process that has the file open. So long as the file is still in use, its space cannot be freed.


text:
Q: Django connection to Postgresql using cert authentication In Django 1.9, what changes do I have to make in settings.py in order to connect to a postgresql database using cert authentication?

A: Adding this to settings.py worked for me:
import os

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '<name>',
        'USER': '<user>',
        'PASSWORD': '<password>',
        'HOST': '<host>',
        'PORT': '25060',
        'OPTIONS': {
            'sslmode': 'verify-full',
            'sslrootcert': os.path.join(BASE_DIR, 'ca-certificate.crt'),
        },
    },
}

A: To my knowledge, django uses psycopg2, which in turn uses libpq.  This means you shouldn't need to make any changes to settings.py.
You have to configure the server properly so it asks for and knows how to validate the certificate, and on the client side you need to put the crt and the key in the correct directory (e.g. ~/.postgresql) so that libpq knows how to find them.  Once that is done properly, it should just work with no changes to any Django-specific code.


text:
Q: What kind of reshape is this and why use it? Sorry for a very unintelligent question. I've been trying to find an answer for it for some time.
So I was skimming through a guide on "Convolutional Neural Networks" and found it using a numpy.reshape function looking like this:
testX.reshape([-1, 28, 28, 1])

This is chinese to me as I can't imagine it having to do with four dimensions, nor being some sort of a reverse function.
Edit: This is the context of the function. Now I'm not even sure it's a numpy function or not:
import tflearn.datasets.mnist as mnist
X, Y, testX, testY = mnist.load_data(one_hot=True)
X = X.reshape([-1, 28, 28, 1])
testX = testX.reshape([-1, 28, 28, 1])

A: In your example (MNIST) the [-1, 28, 28, 1] stands for
[training_examples, hight, width, channels]

-1 for the training examples, as the number is unknown, hight and width should be clear.
Number of channels: Grayscale pics use 1 channel, RBG uses 3 channels.
As MNIST has grayscale pics, here you have 1 (values from 0 to 256).

A: I am assuming you are working with MNIST, or a dataset similar to this with a set of 28 x 28 images.  Perhaps these images are presented in an array of length 784.
x = []
for _ in range(10):
    x.append(range(28 ** 2))
np.array(x).reshape([-1, 28, 28, 1])

This will convert your dataset into a set of 28 x 28 x 1 matrices, which would be useful if you're trying to learn on an image that is 28 x 28 and only has a single color.
it will also determine that you have 10 images, and convert your array to 10 matrices with shape 28 x 28 x 1.
np.array(x).reshape([-1, 28, 28, 1]).shape == (10, 28, 28, 1)

The reason it's 28 x 28 x 1 instead of 28 x 28 is sometimes this is a cleaner way to interpret that there are 28 x 28 squares and a single color.  It's not necessary to add the single dimensional width if it's confusing you, you could just as easily map it to a matrix with shape 28 x 28.  But imagine you had a dataset of colored images, you'd probably map it to 28 x 28 x 3 to indicate that it's an image with 28 x 28 squares, and each square has a value for each of the three colors.
Therefore, it's a set of -1 images, where -1 means calculate the correct number of images (10), and each image has 28 * 28 values, and give each value it's own dimension (1).


text:
Q: SQL query for Pricing analysis Facing issue to find the Min and Max pricing status on the column YearMonth,
Below is my table data
   YearMonth    STATE   ProductGroup    LocaProdname    Price
    201407      MH      AIRTEL          AIRTEL-3G       10,000
    201208      GJ      IDEA            IDEA-3G         1,200
    201406      WB      AIRCEL          AIRCEL PERPAID  5,866
    201407      DL      TATA DOCOMA     TATA LANDLINE   8,955
    201207      KAR     VODAFONE        VODAFONE-3G     7,899
    201312      MH      AIRTEL          AIRTEL-3G       15,000
    201408      GJ      IDEA            IDEA-3G         25,000

I require below output:
YearMonth   STATE   ProductGroup    LocaProdname    Price   Indictor-YEAR
201407      MH      AIRTEL          AIRTEL-3G       10,000  MAX
201312      MH      AIRTEL          AIRTEL-3G       15,000  MIN
201408      GJ      IDEA            IDEA-3G         25,000  MAX
201208      GJ      IDEA            IDEA-3G         1,200   MIN

I need the Max yearmonth  and min Year values values.

A: If I understand correctly, you can do this with row_number():
select YearMonth, STATE, ProductGroup, LocaProdname, Price,
       (case when seqnum_asc = 1 then 'MIN' else 'MAX' end) as Indicator
from (select d.*,
             row_number() over (partition by state, productgroup, localprodname
                                order by price asc) as seqnum_asc,
             row_number() over (partition by state, productgroup, localprodname
                                order by pricedesc) as seqnum_desc
      from data
     ) d
where seqnum_asc = 1 or seqnum_desc = 1;

EDIT:
Does this do what you want?
select YearMonth, STATE, ProductGroup, LocaProdname, Price,
       (case when seqnum_asc = 1 then 'MIN' else 'MAX' end) as Indicator
from (select d.*,
             row_number() over (partition by YearMonth
                                order by price asc) as seqnum_asc,
             row_number() over (partition by YearMOnth
                                order by pricedesc) as seqnum_desc
      from data
     ) d
where seqnum_asc = 1 or seqnum_desc = 1;

A: This can be done by finding the MAX/MIN values associated with the LocaProdname,ProductGroup and State then joining in on the table where everything matches. See below, or view the fiddle at http://sqlfiddle.com/#!3/4d6bd/2
NOTE: I've added in HAVING COUNT(*) > 1 as you seem to only want ones which have changed price. (Ie. Have more than 1 entry)
SELECT p.YearMonth
    ,p.State
    ,p.ProductGroup
    ,p.LocaProdname
    ,p.Price
    ,CASE
        WHEN p.Price = a.MaxPrice
            THEN 'MAX'
        WHEN p.Price = a.MinPrice
            THEN 'MIN'
        END AS [Indicator-YEAR]
FROM PricingTest p
INNER JOIN (
    SELECT LocaProdname
        ,ProductGroup
        ,State
        ,MAX(Price) AS MaxPrice
        ,MIN(Price) AS MinPrice
    FROM pricingTest
    GROUP BY LocaProdname
        ,ProductGroup
        ,State
    HAVING COUNT(*) > 1
    ) a ON a.LocaProdname = p.LocaProdname
    AND a.ProductGroup = p.ProductGroup
    AND a.State= p.State
    AND (
        a.MaxPrice = p.Price
        OR a.MinPrice = p.Price
        )
ORDER BY LocaProdname

EDIT: Or I just noticed it's the max/min YearMonth the user might be looking, if this is the case check out http://sqlfiddle.com/#!3/4d6bd/4 It is basically just replacing all references to Price to YearMonth.

A: Once you get the last and first record you can UNION results:
SELECT t.*, 'MIN' AS Indicator
FROM
  myTable t LEFT JOIN
  myTable t2 ON t.YearMonth = t2.YearMonth AND t2.price < t.price
WHERE t2.YearMonth IS NULL
UNION
SELECT t.*, 'MAX' AS Indicator
FROM
  myTable t LEFT JOIN
  myTable t2 ON t.YearMonth = t2.YearMonth AND t2.price > t.price
WHERE t2.YearMonth IS NULL

If you have several records with same highest price, above query will return all of them. Also if you only have one record in a month, it will be returned twice as both MIN and MAX.

A: Please use Row_number with partition BY and remove unwanted code as per your need,
SELECT yearmonth,state,productgroup,locaprodname,price,operation
    FROM   (
    SELECT * FROM   (SELECT p.yearmonth,p.state,p.productgroup,p.locaprodname,p.price,'MAX' AS Operation,
                           Row_number() OVER( partition BY p.productgroup, p.locaprodname
                               ORDER BY p.price DESC) AS Row
                    FROM   pricingtest p) AS Maxx
            WHERE  Maxx.row = 1

    UNION ALL

    SELECT * FROM   (SELECT p.yearmonth,p.state,p.productgroup,p.locaprodname,p.price,'MIN' AS Operation,
                           Row_number() OVER( partition BY p.productgroup, p.locaprodname
                               ORDER BY p.price ASC) AS Row
                    FROM   pricingtest p) AS Minn
            WHERE  Minn.row = 1

    ) AS whole
    ORDER  BY yearmonth,productgroup


text:
Q: Save IP in remote host every time connection is up (as non-root-user) I have a dynamic local Lan IP at work (temporarily), but in order to connect from home, I ssh to the host A (static IP) and from there to my machine.
However, since the IP changes, I would like to save in host A frequently, for instance every time the connection is up (I often loose my ethernet connection due to poor cables).
I'm using NetowrkManager so I created a file in /etc/NetworkManager/dispatcher.d/90exportIP which runs the following:
 ssh hostA "echo $(date)  enp4s0f2 IP: $(/sbin/ifconfig enp4s0f2 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://') >> todaysElanIP";

This gets my IP and saves it in file todaysElanIP in host A.
The problem is this script is run as root, and my keys are not there. I sometimes just run this command on bash and it works. But I would like it to run automatically every time the network is up.
I tried runuser -l myUser, but ssh-agent is not accessible like that.
It doesn't has to work every time. For instance, at boot time I haven't yet added my key to ssh-agent. If next time the network is down and then up again the export happens, that would work for me.
It's a bit confusing how I can easily do something with a non-root user and it seems so hard as root.


text:
Q: Animate NSLayoutConstraint created programmatically Something special has to be done to animate a constraint instantiated programmatically?
I instantiate a constraint programmatically as a lazy variable:
private lazy var topConstraint: NSLayoutConstraint = {
    let constraint = view.topAnchor.constraint(equalTo: otherView.topAnchor, constant: otherView)
    return constraint
}()

Then, I animate a change in the constant of this constraint:
topConstraint.constant = newValue
view.setNeedsLayout()
UIView.animate(withDuration: 1) {
    self.view.layoutIfNeeded()
}

It is not working... I also have tried putting the constant setting into the block:
UIView.animate(withDuration: 1) {
    self.topConstraint.constant = newValue
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
}

But I achieved nothing at all, I've tried almost all the combinations. The constraint constant is properly changed, but always without animation.
PD: I also gave a shot to UIViewPropertyAnimator.

A: No need for setNeedsLayout().
self.topConstraint.constant = 0.0
UIView.animate(withDuration: 1.0) {[weak self] in
    self?.topConstraint.constant = 10.0
    self?.view.layoutIfNeeded()
}


text:
Q: Calculate seconds between two dates including business hours, excluding holidays, start hour 08:30 When looking for a solution for my question I found the following sql (Calculate business hours between two dates).
However, I want the starting point to be 8:30 instead of 9 and the end point 17:30 instead of 17. Currently I am using an integer. Can anyone help me with this? Thanks in advance!
    Create Function GetWorkingMin(@StartDate DateTime, @EndDate DateTime, @Country Varchar(2)) Returns Int
AS
Begin
Declare @WorkMin int = 0   -- Initialize counter
Declare @Reverse bit       -- Flag to hold if direction is reverse
Declare @StartHour int = 9   -- Start of business hours (can be supplied as an argument if needed)
Declare @EndHour int = 17    -- End of business hours (can be supplied as an argument if needed)
Declare @Holidays Table (HDate DateTime)   --  Table variable to hold holidayes

-- If dates are in reverse order, switch them and set flag
If @StartDate>@EndDate
Begin
    Declare @TempDate DateTime=@StartDate
    Set @StartDate=@EndDate
    Set @EndDate=@TempDate
    Set @Reverse=1
End
Else Set @Reverse = 0

-- Get country holidays from table based on the country code (Feel free to remove this or modify as per your DB schema)
Insert Into @Holidays (HDate) Select HDate from HOLIDAY Where COUNTRYCODE=@Country and HDATE>=DateAdd(dd, DateDiff(dd,0,@StartDate), 0)

If DatePart(HH, @StartDate)<@StartHour Set @StartDate = DateAdd(hour, @StartHour, DateDiff(DAY, 0, @StartDate))  -- If Start time is less than start hour, set it to start hour
If DatePart(HH, @StartDate)>=@EndHour+1 Set @StartDate = DateAdd(hour, @StartHour+24, DateDiff(DAY, 0, @StartDate)) -- If Start time is after end hour, set it to start hour of next day
If DatePart(HH, @EndDate)>=@EndHour+1 Set @EndDate = DateAdd(hour, @EndHour, DateDiff(DAY, 0, @EndDate)) -- If End time is after end hour, set it to end hour
If DatePart(HH, @EndDate)<@StartHour Set @EndDate = DateAdd(hour, @EndHour-24, DateDiff(DAY, 0, @EndDate)) -- If End time is before start hour, set it to end hour of previous day

If @StartDate>@EndDate Return 0

-- If Start and End is on same day
If DateDiff(Day,@StartDate,@EndDate) <= 0
Begin
    If Datepart(dw,@StartDate)>1 And DATEPART(dw,@StartDate)<7  -- If day is between sunday and saturday
        If (Select Count(*) From @Holidays Where HDATE=DateAdd(dd, DateDiff(dd,0,@StartDate), 0)) = 0  -- If day is not a holiday
            If @EndDate<@StartDate Return 0 Else Set @WorkMin=DATEDIFF(MI, @StartDate, @EndDate) -- Calculate difference
        Else Return 0
    Else Return 0
End
Else Begin
    Declare @Partial int=1   -- Set partial day flag
    While DateDiff(Day,@StartDate,@EndDate) > 0   -- While start and end days are different
    Begin
        If Datepart(dw,@StartDate)>1 And DATEPART(dw,@StartDate)<7    --  If this is a weekday
        Begin
            If (Select Count(*) From @Holidays Where HDATE=DateAdd(dd, DateDiff(dd,0,@StartDate), 0)) = 0  -- If this is not a holiday
            Begin
                If @Partial=1  -- If this is the first iteration, calculate partial time
                Begin
                    Set @WorkMin=@WorkMin + DATEDIFF(MI, @StartDate, DateAdd(hour, @EndHour, DateDiff(DAY, 0, @StartDate)))
                    Set @StartDate=DateAdd(hour, @StartHour+24, DateDiff(DAY, 0, @StartDate))
                    Set @Partial=0
                End
                Else Begin      -- If this is a full day, add full minutes
                    Set @WorkMin=@WorkMin + (@EndHour-@StartHour)*60
                    Set @StartDate = DATEADD(DD,1,@StartDate)
                End
            End
            Else Set (at)StartDate = DATEADD(HOUR, (at)StartHour, CAST(CAST(DATEADD(DD,1,(at)StartDate) AS DATE) AS DATETIME))
        End
        Else Set (at)StartDate = DATEADD(HOUR, (at)StartHour, CAST(CAST(DATEADD(DD,1,(at)StartDate) AS DATE) AS DATETIME))
    End
    If Datepart(dw,@StartDate)>1 And DATEPART(dw,@StartDate)<7  -- If last day is a weekday
        If (Select Count(*) From @Holidays Where HDATE=DateAdd(dd, DateDiff(dd,0,@StartDate), 0)) = 0   -- And it is not a holiday
            If @Partial=0 Set @WorkMin=@WorkMin + DATEDIFF(MI, @StartDate, @EndDate) Else Set @WorkMin=@WorkMin + DATEDIFF(MI, DateAdd(hour, @StartHour, DateDiff(DAY, 0, @StartDate)), @EndDate)
End
If @Reverse=1 Set @WorkMin=-@WorkMin
Return @WorkMin

End

A: Use TIME for start time. Then create INT variable to put converted value to minute to use for conditions.
I have created sample for you.
DECLARE @StartDate  DATETIME='2018-12-10 10:00'
DECLARE @ExpectedStartTime  TIME='08:30'

DECLARE @ExpectedStartMin   INT=DATEPART(HOUR,@ExpectedStartTime)*60+DATEPART(MINUTE,@ExpectedStartTime)
DECLARE @ActualStartMin     INT=DATEPART(HOUR,@StartDate)*60+DATEPART(MINUTE,@StartDate)

--Check before change the StartDate
SELECT @ExpectedStartMin, @ActualStartMin, @StartDate

If @ExpectedStartMin<@ActualStartMin Set @StartDate = CAST(CAST(@StartDate AS DATE) AS DATETIME)+@ExpectedStartTime
-- same way to the other conditions.
--
--

--Check after change the StartDate
SELECT @ExpectedStartMin, @ActualStartMin, @StartDate


text:
Q: Office 365 Management API: Filter using StartTime and EndTime does not work I am trying to fetch the audit logs of SharePoint tenant for a certain time period (suppose for half an hour today earlier) but if use startTime and endTime filter it doesn't work. It always shows me content from around 24 hours ago which is not useful. Isn't this API useless if any filter does not work?
Sample URL I have used in the script:
"https://manage.office.com/api/v1.0/$tenant/activity/feed/subscriptions/content?contentType=Audit.SharePoint&startTime=2020-02-12T23:00&endTime=2020-02-12T23:15"
No matter what timestamp I put data is always around 24 hours before. Did anybody encounter it before? Is there any resolution for that? Please help.

A: Okay looks like you can only get logs older than 24 hours. If you put a timestamp less than 24 hours old, it just provides you the latest log, and ignores the timestamp.


text:
Q: Errno::ENOENT: Error running rspec test, says file doesn't exist but it does So I am trying to test for a controller but am running into problems. Part of the code requires a file to be loaded, but I am receiving this error:
Errno::ENOENT:
       No such file or directory - ./public/licenses/58efcffc3d8441fcc0627164a8b1350aFCV5Hmashup_lic.xml

However, the file does exit. When I run it in the browser, it works just fine with no problems (but i still want to write a test).
I don't know if this has anything to do with it, but I am using a database when running the test. I know this isn't actually how I should do it, but I don't know any other way.
Any help would be awesome. Thanks.

A: Most likely because your assumption about where the current working directory is when running the tests is wrong. try putting a puts File.dirname('.') in there to make sure you're running from the directory you think you are.

A: As a debugging tool:
In your test, just before the statement that checks for the file, try adding
puts "list dir " + `ls ./public/licenses/`

to see if the file is really there.
Could be a permissions problem from the test user id
Could also be that the file isn't actually there...


text:
Q: GridLayout for secondery panels in the main panel JAVA Swing I create this program and use panels for every info the user insert.
But al the panels sit side by side . i want to get all the smalls panels like Gender,Weight and Body Frame one below the other and the Height and Personal Data panels side by side.
And under to all of this panels i want to put the Calculate button.
itried some types of gridlayout but nothing is like what i want.
Photo of how it looks now:

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Hashtable;

public class bmi {
    private static JFrame testFrame;
    private JPanel mainPanel;
    private final String[] genderComboTexts={"Male","Female"};
    private JComboBox genderChoices=null;
    private JSlider ageSlider;
    private JSlider heightSlider;
    private final String[] bodyComboTexts={"Small","Medium","Large"};
    private JComboBox bodyFrame=null;

    private JTextField nameTF;
    private JTextField fnameTF;
    private JTextField ageTF;
    private JTextField weightTF;

    public bmi() {

        mainPanel = new JPanel();
        mainPanel.add(initPersonalDataAndPanel());
        mainPanel.add(initGenderPanel());
        mainPanel.add(initHeightSlider());
        mainPanel.add(initWeightPanel());
        mainPanel.add(initBodyFrame());
        JButton calc = new JButton("Calculate");
        mainPanel.add(calc);

        calc.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                double height = heightSlider.getValue();
                double age =Double.parseDouble(ageTF.getText());
                double weight=Double.parseDouble((weightTF.getText()));

                double heightM=height/100;
                double bmi = weight/(Math.pow(heightM,2));
                System.out.println("BMI: "+new DecimalFormat("0.00").format(bmi));

                if(bmi<15){
                    System.out.println("You are Anorexic");
                }
                else if(bmi>15 && bmi<18.5){
                    System.out.println("You are Underweight");
                }
                else if(bmi>18.5 && bmi<24.9){
                    System.out.println("You are Normal");
                }
                else if(bmi>25.0 && bmi<29.9){
                    System.out.println("You are Overweight");
                }
                else if(bmi>30.0 && bmi<35){
                    System.out.println("You are Obese");
                }
                else if(bmi>35){
                    System.out.println("You are Extreme Obese");
                }

            }
        });

    }

    private JPanel initWeightPanel(){
        JPanel panel =new JPanel();
        weightTF=new JTextField();
        weightTF.setPreferredSize(new Dimension(100,20));
        panel.add(weightTF);
        panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Weight"),
                BorderFactory.createEmptyBorder(5,50,5,50)));
        return panel;
    }
    private JPanel initHeightSlider(){
        JPanel panel=new JPanel();
        JLabel weight=new JLabel("160");
        heightSlider=new JSlider(JSlider.VERTICAL,140,190,160);
        heightSlider.setMinorTickSpacing(1);
        heightSlider.setMajorTickSpacing(5);
        heightSlider.setPaintTicks(true);
        Hashtable<Integer,JLabel> labels=new Hashtable<>();
        labels.put(140, new JLabel("140"));
        labels.put(150, new JLabel("150"));
        labels.put(160, new JLabel("160"));
        labels.put(170, new JLabel("170"));
        labels.put(180, new JLabel("180"));
        labels.put(190, new JLabel("190"));
        heightSlider.setLabelTable(labels);
        heightSlider.setPaintLabels(true);
        panel.add(weight);
        panel.add(heightSlider);
        panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Height"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        heightSlider.addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {

                weight.setText(""+heightSlider.getValue());
            }

            @Override
            public void mouseMoved(MouseEvent e) {

            }
        });
        return panel;
    }

    private JPanel initBodyFrame(){

        JPanel panel=new JPanel();
        bodyFrame=new JComboBox(bodyComboTexts);
        panel.add(bodyFrame);
        panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Body Frame"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        return panel;
    }
    private JPanel initGenderPanel(){
        JPanel panel=new JPanel();
        genderChoices=new JComboBox(genderComboTexts);
        panel.add(genderChoices);
        panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Gender"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        return panel;
    }
    private JPanel initPersonalDataAndPanel(){
        JPanel panel=new JPanel();
        JLabel name=new JLabel("Name");
        JLabel fname=new JLabel("Last Name");
        JLabel age=new JLabel("Age");
        nameTF=new JTextField();
        fnameTF=new JTextField();
        ageTF= new JTextField();
        JButton print=new JButton("Print");

panel.setLayout(new GridLayout(4,2,10,10));
        panel.add(name);
        panel.add(nameTF);
        panel.add(fname);
        panel.add(fnameTF);
        panel.add(age);
        panel.add(ageTF);
        panel.add(print);
        panel.add(new JLabel());
        panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Personal Data"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        print.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double height = heightSlider.getValue();
                double age =Double.parseDouble(ageTF.getText());
                double weight=Double.parseDouble((weightTF.getText()));

                System.out.println("Name: "+nameTF.getText());
                System.out.println("Last Name: "+fnameTF.getText());
                System.out.println("Age: "+ageTF.getText());
                System.out.println("Height: "+heightSlider.getValue());
                System.out.print("Weight: "+weightTF.getText());

                if (bodyFrame.getSelectedItem() == "Small") {
                    double idealWeight = ((height - 100 + (age / 10)) * 0.9 * 0.9);
                    System.out.println(" ====== Ideal Weight: "+new DecimalFormat("0.00").format(idealWeight));
                } else if (bodyFrame.getSelectedItem() == "Medium") {
                    double idealWeight = ((height - 100 + (age / 10)) * 0.9 * 1);
                    System.out.println(" ====== Ideal Weight: "+new DecimalFormat("0.00").format(idealWeight));
                } else if (bodyFrame.getSelectedItem() == "Large") {
                    double idealWeight = ((height - 100 + (age / 10)) * 0.9 * 1.1);
                    System.out.println(" ====== Ideal Weight: "+new DecimalFormat("0.00").format(idealWeight));
                }

                System.out.println("Gender: "+genderChoices.getSelectedItem());
                System.out.println("Body Frame: "+bodyFrame.getSelectedItem());

            }
        });
        return panel;
    }

    public static void main(String[] args){
        bmi bmi_1 =new bmi();
        testFrame=new JFrame("Test");
        testFrame.setContentPane(bmi_1.mainPanel);
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testFrame.pack();
testFrame.setVisible(true);

    }
}

A: So, you should do something like this
Create BorderLayout. South of the border layout should be the button Calculate.
Next, create BoxLayout JPanel with vertical allign like this.
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

Add Gender, Weight and BodyFrame inside it.
And create another JPanel with FlowLayout. Add Height and Personal Data inside it.
Depening on how you want this to panels to show up, you can either wrap them in FlowLayout JPanel or BoxLayout JPanel and add that to center of firstly created BorderLayout.


text:
Q: Download iOS Twitter Kit Quite irritatingly, the documentation for the Twitter Api (https://dev.twitter.com/twitter-kit/ios) is quite complete with lots of example and all, but in the whole site I wasn't able to find a single "Download" button.
Now, where can I download the TwitterKit? Thanks

A: TwitterKit is part of Fabric, which can be downloaded from https://dev.twitter.com
Follow the link that says "Download".

A: You need to download fabric tool, register, choose your project and install TwitterKit from this interface.
Sing up now here:
https://fabric.io/sign_up
Fabric Docs:
https://dev.twitter.com/fabric/overview

A: You can sign up for and download Fabric via https://get.fabric.io (which is linked from the Fabric section of https://dev.twitter.com as stated in other responses).