text:
Q: Trouble with an auto-submitting form I'm working on an intermediary form that will gather some data from the user submitted form, and then re-build the form and send it to our authorizer in the appropriate format. Everything is working fine except that I cannot get it to submit this secondary form automatically. I have read several other posts on SO regarding this issue, but they all seem to be requiring a trigger to then submit the form, which mine does not. I simply require it to submit, and my jQuery seems to be taking a nap.
...data gathered here...

echo "";

echo "<form id='forwarderForm' method='post' action='https://www.beanstream.com/scripts/process_transaction.asp'>";

    //rebuild the form to send to beanstream
    $keys = array_keys($_POST);
    for($i = 0; $i < count($_POST); $i++) {
        $currentKey = $keys[$i];
        $currentPost = $_POST[$currentKey];
        echo "<INPUT TYPE='hidden' NAME='" .$currentKey. "' VALUE='" .$currentPost. "'>";
    }
echo "</form>

  ";

I have also tried removing the jQuery from the PHP echo, but this does not work either. when using a standard submit button to send the form, everything works fantastic, but I can't get it to submit by itself.
I added the HTML/HEAD/BODY tags later because I was unsure if they mattered for the purposes of a simple form construct/submit, but this did not appear to change anything.
any comments, suggestions and advice is greatly appreciated. I know it's probably something very simple that's eluding me, so your help is appreciated.

A: You will need to add this in a document.ready clause, like this


text:
Q: Move a Windows Server domain into an existing forest I'm a developer who occasionally needs to do server stuff just to get the environment he needs for working.
I have an AD domain (all servers are 2008 R2) with, presumably, a default forest. Works fine. Built a second domain elsewhere, in which I created a SharePoint farm. Now I want to move that domain (which uses a Server Core DC) into the existing forest.
Lots of instructions (and notes about child domains and tree domains), but I'm getting the feeling that all those instructions presume that the new domain is being created within that existing forest. In my case, I want to move the new domain into the old forest (to preserve the various user and service accounts).
What are my options?
[added after a couple responses]
Looking at the first two responses, let me add a wee bit about why I even consider doing this.
I built the SharePoint domain (using virtualized Server Core for the domain controller and one virtual machine for SharePoint, which then uses the Sql Server of the host server for its data store (and I wanted to have a Kerberos environment)) "away" from my "production" environment but using the same ISP. So, all machines are running IPs within the same 256-group. Performance was just fine.
I then built a Windows 7 machine just to connect with that new domain and on which to do whatever development doesn't need to be done directly on the SharePoint server. Works fine.
But upon then connecting with the server machines in the new domain via Remote Desktop Connections, I found that any action taken on the remote server required about 5 seconds to be seen from the Win7 machine. Completely unacceptable for the purpose intended.
Went back to my existing equipment to check its performance, and connecting to those servers via a different Win7 machine show the usual instantaneous response.
So, I concluded (without any real evidence) that the new domain was conflicting with the old domain (even though the old domain isn't affected at all).
I'm now getting the feeling that I can leave the two domains separate (there is certainly no need for them to communicate). But what could be causing the unacceptable performance of Remote Desktop between the Win7 and server machines?

A: I think it runs down into reinstall. I do not think forests can be merged, which is what you ask for.

A: It is possible to merge elements of one domain into another. MS supply migration tools  - but its definitely not for the faint of heart and you would need a very good understanding of the mechanism and working of AD.
Migrating a domain into another is days or weeks of work and would leave you with loads of security related issues in sharepoint if it worked at all after migrating... better forget the idea.
You can backup and restore a sharepoint installation in minutes - assuming you have a web server and sql server ready and waiting. This I have done on numerous occasions and it just works.

A: I don't think this has anything to do with multi domain, permissions or anything else.  I would verify the remote desktop settings are right, that the network connectivity is solid and the Win7 box has a healthy network connection. Maybe try another remote access tool (like VNC) to prove that the domain is not involved.
\\Greg

redpajama_set_name: RedPajamaStackExchange


text:
Q: Libs folder vs build path dependency (ANDROID) I have some jar libraries on which my app depends.
When I copy and paste the jars in the project/libs folder, it builds, compiles and executes correctly.
However, if I right click my project -> Build path -> Configure build path -> Libraries tab -> Add external JARs, and add exactly the same jars, it still gives me no error, it allows me to build and compile, but when the app is executed it crashes.
Why?

A: If you put jars in libs folder it will automatically add those JARs to your compile-time build path. More importantly, it will put the contents of the JARs into your APK file, so they will be part of your run-time build path.
Adding jar to build path with lib manually will solve the compile-time problem, but then your JAR contents are not in your APK and therefore will not be available to you at runtime.

A: Don't use add external jar this will add as Absolute path instead of this use the relative path by adding jar, with this you must put all the jar files into the libs directory.
If you using Add External Jar it will search for that jar file based on Absolute path so on device that path was not find and you getting Force Close.
Try with adding same jar file by using Add Jar and Add External Jar option.
check the difference here https://stackoverflow.com/a/10679344/760489


text:
Q: Calculating due date using business hours and holidays I need to calculate due date / end date for SLAs.  As input values I have the start date and a timespan (in minutes).  This calculation needs to take into account business hours, weekends, and holidays.
I've seen a lot of examples where the input is start date and end date, but have been struggling finding anything similar to the above input values.
Is there an elegant solution to this problem?  Is there a way to calculate due date without using a loop?  I can't think of a way to do the calculation without doing something similar to the following terrible algorithm:

*

*Create a return variable "due date" and set it to input variable
"start date"

*Create a control variable "used minutes" and set it to 0

*Create a loop with the condition "used minutes" <= "input timespan"

*Inside the loop, add a second to the "due date" return variable

*Inside the loop, check if the second is within hours of operation
(checking business hours, weekends, and holidays).  If so, increment
control variable "used minutes" by 1.

*Upon exiting the loop, return variable "due date"

A: You need a table with valid business hours, with the weekends and holidays excluded (or marked as weekend/holiday so you can skip them.)  Each row represents one day and the number of working hours for that day. Then you query the business hours table from your start date to the first (min) date where the sum(hours*60) is greater than your minutes parameter, excluding marked weekend/holiday rows.  That gives you your end date.
Here's the day table:
CREATE TABLE [dbo].[tblDay](
    [dt] [datetime] NOT NULL,
    [dayOfWk] [int] NULL,
    [dayOfWkInMo] [int] NULL,
    [isWeekend] [bit] NOT NULL,
    [holidayID] [int] NULL,
    [workingDayCount] [int] NULL,
 CONSTRAINT [PK_tblDay] PRIMARY KEY CLUSTERED
(
    [dt] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

here's how I populate the table with days:
CREATE PROCEDURE [dbo].[usp_tblDay]
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE
        @Dt datetime ,
        @wkInMo int,
        @firstDwOfMo int,
        @holID int,
        @workDayCount int,
        @weekday int,
        @month int,
        @day int,
        @isWkEnd bit

    set @workDayCount = 0
    SET @Dt = CONVERT( datetime, '2008-01-01' )
    while @dt < '2020-01-01'
    begin
        delete from tblDay where dt = @dt

        set @weekday = datepart( weekday, @Dt )
        set @month = datepart(month,@dt)
        set @day = datepart(day,@dt)

        if @day = 1  -- 1st of mo
            begin
                set @wkInMo = 1
                set @firstDwOfMo = @weekday
            end

        if ((@weekday = 7) or (@weekday = 1))
            set @isWkEnd = 1
        else
            set @isWkEnd = 0

        if @isWkEnd = 0 and (@month = 1 and @day = 1)
            set @holID=1        -- new years on workday
        else if @weekday= 6 and (@month = 12 and @day = 31)
            set @holID=1        -- holiday on sat, change to fri
        else if @weekday= 2 and (@month = 1 and @day = 2)
            set @holID=1        -- holiday on sun, change to mon

        else if @wkInMo = 3 and @weekday= 2 and @month = 1
            set @holID = 2      -- mlk

        else if @wkInMo = 3 and @weekday= 2 and @month = 2
            set @holID = 3      -- President's

        else if @wkInMo = 4 and @weekday= 2 and @month = 5 and datepart(month,@dt+7) = 6
            set @holID = 4      -- memorial on 4th mon, no 5th
        else if @wkInMo = 5 and @weekday= 2 and @month = 5
            set @holID = 4      -- memorial on 5th mon

        else if @isWkEnd = 0 and (@month = 7 and @day = 4)
            set @holID=5        -- July 4 on workday
        else if @weekday= 6 and (@month = 7 and @day = 3)
            set @holID=5        -- holiday on sat, change to fri
        else if @weekday= 2 and (@month = 7 and @day = 5)
            set @holID=5        -- holiday on sun, change to mon

        else if @wkInMo = 1 and @weekday= 2 and @month = 9
            set @holID = 6      -- Labor

        else if @isWkEnd = 0 and (@month = 11 and @day = 11)
            set @holID=7        -- Vets day on workday
        else if @weekday= 6 and (@month = 11 and @day = 10)
            set @holID=7        -- holiday on sat, change to fri
        else if @weekday= 2 and (@month = 11 and @day = 12)
            set @holID=7        -- holiday on sun, change to mon

        else if @wkInMo = 4 and @weekday= 5 and @month = 11
            set @holID = 8      -- thx

        else if @holID = 8
            set @holID = 9      -- dy after thx

        else if @isWkEnd = 0 and (@month = 12 and @day = 25)
            set @holID=10       -- xmas day on workday
        else if @weekday= 6 and (@month = 12 and @day = 24)
            set @holID=10       -- holiday on sat, change to fri
        else if @weekday= 2 and (@month = 12 and @day = 26)
            set @holID=10       -- holiday on sun, change to mon
        else
            set @holID = null

        insert into tblDay select @dt,@weekday,@wkInMo,@isWkEnd,@holID,@workDayCount

        if @isWkEnd=0 and @holID is null
            set @workDayCount = @workDayCount + 1

        set @dt = @dt + 1
        if datepart( weekday, @Dt ) = @firstDwOfMo
            set @wkInMo = @wkInMo + 1
    end
END

I also have a holiday table, but everyone's holidays are different:
holidayID   holiday rule description
1   New Year's Day  Jan. 1
2   Martin Luther King Day  third Mon. in Jan.
3   Presidents' Day third Mon. in Feb.
4   Memorial Day    last Mon. in May
5   Independence Day    4-Jul
6   Labor Day   first Mon. in Sept
7   Veterans' Day   Nov. 11
8   Thanksgiving    fourth Thurs. in Nov.
9   Fri after Thanksgiving  Friday after Thanksgiving
10  Christmas Day   Dec. 25

HTH

A: This is the best I could do, still uses a loop but uses date functions instead of incrementing a minutes variable. Hope you like it.

--set up our source data
declare @business_hours table
(
    work_day    varchar(10),
    open_time   varchar(8),
    close_time  varchar(8)
)
insert into @business_hours values ('Monday',   '08:30:00', '17:00:00')
insert into @business_hours values ('Tuesday',  '08:30:00', '17:00:00')
insert into @business_hours values ('Wednesday', '08:30:00', '17:00:00')
insert into @business_hours values ('Thursday', '08:30:00', '17:00:00')
insert into @business_hours values ('Friday',   '08:30:00', '18:00:00')
insert into @business_hours values ('Saturday', '09:00:00', '14:00:00')

declare @holidays table
(
    holiday varchar(10)
)
insert into @holidays values ('2015-01-01')
insert into @holidays values ('2015-01-02')

--Im going to assume the SLA of 2 standard business days (0900-1700) = 8*60*2 = 960
declare @start_date datetime = '2014-12-31 16:12:47'
declare @time_span int = 960-- time till due in minutes

declare @true bit = 'true'
declare @false bit = 'false'

declare @due_date datetime --our output

--other variables
declare @date_string varchar(10)
declare @today_closing datetime
declare @is_workday bit = @true
declare @is_holiday bit = @false

--Given our timespan is in minutes, lets also assume we dont care about seconds in start or due dates
set @start_date = DATEADD(ss,datepart(ss,@start_date)*-1,@start_date)

while (@time_span > 0)
begin

set @due_date       = DATEADD(MINUTE,@time_span,@start_date)
set @date_string    = FORMAT(DATEADD(dd, 0, DATEDIFF(dd, 0, @start_date)),'yyyy-MM-dd')
set @today_closing  = (select convert(datetime,@date_string + ' ' + close_time) from @business_hours where work_day = DATENAME(weekday,@start_date))

if exists((select work_day from @business_hours where work_day = DATENAME(weekday,@start_date)))
    set @is_workday = @true
else
    set @is_workday = @false

if exists(select holiday from @holidays where holiday = @date_string)
    set @is_holiday = @true
else
    set @is_holiday = @false

if  @is_workday = @true and @is_holiday = @false
begin
    if @due_date > @today_closing
        set @time_span = @time_span - datediff(MINUTE, @start_date, @today_closing)
    else
        set @time_span = @time_span - datediff(minute, @start_date, @due_date)
end

set @date_string = FORMAT(DATEADD(dd, 1, DATEDIFF(dd, 0, @start_date)),'yyyy-MM-dd')
set @start_date = CONVERT(datetime, @date_string + ' ' + isnull((select open_time from @business_hours where work_day = DATENAME(weekday,convert(datetime,@date_string))),''))

end

select @due_date

A: Sql to Calculate due date excluding holidays and considering business hour  as below :- < note : - It's working correctly Business hour (8-5) Maintain holiday table
CREATE TABLE [dbo].[holiday](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [region] [nvarchar](10) NULL,
    [Hdate] [date] NULL,
)

>
declare @start datetime= getdate()
declare @slamins int =960 --- SLA time in mins
declare @Country varchar(2)='NA'
declare @start_hour int = 8 -- business start hour
declare @end_hour int = 17 -- business end hour
declare @true bit = 'true'
declare @false bit = 'false'
declare @is_workday bit = @true
declare @is_holiday bit = @false
declare @due_date datetime
declare @today_closing datetime
declare @temp int = 0
declare  @holidays table (HDate DateTime)   --  Table variable to hold holidayes

---- 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 date from HOLIDAY Where region=@Country and Hdate>=DateAdd(dd, DateDiff(dd,0,@start), 0)

--check for weekends
set @start =  case(datepart(dw,@start)+@@datefirst-1)%7
      when 0 then Convert(dateTime,CONVERT(varchar,@start+1,101)+' 08:00:00')
      when 6 then Convert(dateTime,CONVERT(varchar,@start+2,101)+' 08:00:00')
      else @start end

-- check if start time is before business hour
if datepart(hh, @start) < @start_hour set @start = Convert(dateTime,CONVERT(varchar,@start,101)+' 08:00:00')

-- check if start time is after business hour
if datepart(hh, @start) >= @end_hour set @start = Convert(dateTime,CONVERT(varchar,@start+1,101)+' 08:00:00')

-- loop start
while (@slamins > 0)
begin
 -- prepared closing date time based on start date
 set @today_closing = Convert(dateTime,CONVERT(varchar,@start,101)+' 17:00:00')
 set @due_date      = @start
 -- calculate number of Minute between start date and closing date
 set @temp = DATEDIFF(N, @start , @today_closing);

 --check for weekends
if (DATEPART(dw, @start)!=1 AND DATEPART(dw, @start)!=7)
    set @is_workday = @true
else
    set @is_workday = @false
--check for holidays
if (Select Count(*) From @Holidays Where HDATE=DateAdd(dd, DateDiff(dd,0,@start), 0)) = 0
    set @is_holiday =@false
else
    set @is_holiday = @true
if  @is_workday = @true and @is_holiday = @false
begin

    if(@temp  <  @slamins)
    begin
        set @slamins = @slamins - @temp
    end
else
    begin
        set @due_date = DATEADD(MINUTE,@slamins,@start)
        set @slamins = 0
        print @due_date
    end
end
set @start = Convert(dateTime,CONVERT(varchar,@start+1,101)+' 08:00:00')
end

select @due_date

A: Here is an option using a WorkSchedule table, which will contain the business hours that are available to count towards the SLA.  To account for weekends and holidays, just do not insert records for these days into the WorkSchedule table.
This solution also uses a "Tally" table aka numbers table in the due date calc. I also included debug output to help you see what is going on, so just comment out or uncomment any debug sections to see less/more info.
I used SQL temp tables in this example so that you can run it without messing up your current database schema, but you should replace with physical tables if you use this solution.
Test Data setups:
CREATE TABLE #WorkSchedule(WorkStart datetime not null primary key, WorkEnd datetime not null);
GO
CREATE TABLE #Tally (N int not null primary key);
GO

--POPULATE TEST DATA
--populate Tally table
insert into #Tally (N)
select top 10000 N = row_number() over(order by o.object_id)
from sys.objects o cross apply sys.objects o2
;
go

--POPULATE WITH DUMMY TEST DATA
INSERT INTO #WorkSchedule(WorkStart, WorkEnd)
SELECT
     workStart = dateadd(hour, 8, t.workDate)
    , workEnd = dateadd(hour, 17, t.workDate)
FROM (
    SELECT top 10000 workDate = dateadd(day, row_number() over(order by o.object_id), '2000-01-01')
    FROM sys.objects o cross apply sys.objects o2
) t
--Exclude weekends from work schedule
WHERE datename(weekday, t.workDate) not in ('Saturday','Sunday')
;

GO

Code to calculate Due Date:
SET NOCOUNT ON;
DECLARE @startDate datetime;
DECLARE @SLA_timespan_mins int;

DECLARE @workStartDayOne datetime;
DECLARE @SLA_Adjusted int;
DECLARE @dueDate datetime;

--SET PARAM VALUES HERE FOR TESTING TO ANY DATE/SLA TIMESPAN YOU WANT:
SET @startDate = '2014-01-04 05:00'; --Saturday
SET @SLA_timespan_mins = 10 * 60 ; --10 hrs.

--get the info day 1, since your start date might be after the work start time.
select top 1 @workStartDayOne = s.WorkStart
    --increase the SLA timespan mins to account for difference between work start and start time
    , @SLA_Adjusted = case when @startDate > s.WorkStart then datediff(minute, s.WorkStart, @startDate) else 0 end + @SLA_timespan_mins
from #WorkSchedule s
where s.WorkEnd > @startDate
    and s.WorkStart <> s.WorkEnd
order by s.WorkStart asc
;

--DEBUG info:
select 'Debug Info' as DebugInfo, @startDate AS StartDate, @workStartDayOne as workStartDayOne, @SLA_timespan_mins as SLA_timespan_mins, @SLA_Adjusted as SLA_Adjusted;

--now sum all the non work hours during that period and determine the additional mins that need added.
;with cteWorkMins as
(
    SELECT TOP (@SLA_Adjusted)
          s.WorkStart, s.WorkEnd
        , WorkMinute = dateadd(minute, t.N, cast(s.WorkStart as datetime))
        , t.N as MinuteOfWorkDay
        , RowNum = row_number() over(order by s.WorkStart, t.N)
    FROM #WorkSchedule s
        INNER JOIN #Tally t
            ON t.N between 1 and datediff(minute, s.WorkStart, s.WorkEnd)
    WHERE s.WorkStart >= @workStartDayOne
    ORDER BY s.WorkStart, t.N
)
/**/
SELECT @dueDate = m.WorkMinute
FROM cteWorkMins m
WHERE m.RowNum = @SLA_Adjusted
--*/
/**
--DEBUG: this query will show every minute that is accounted for during the Due Date calculation.
SELECT m.*
FROM cteWorkMins m
--WHERE m.RowNum = @SLA_Adjusted
ORDER BY m.WorkMinute
--*/
;

select @dueDate as DueDate;
GO

Test Cleanup:
IF object_id('TEMPDB..#WorkSchedule') IS NOT NULL
DROP TABLE #WorkSchedule;
GO
IF object_id('TEMPDB..#Tally') IS NOT NULL
DROP TABLE #Tally;

GO

A: as I understood from your question, what you need is as follow

*

*You have given start date and number of minutes added to it, then you need to get the due date

*To get the due date, you need to exclude the holidays and the due date should be during business day

here is what you can do
declare @start datetime,
        @min int,
        @days int

set @start= '28 Dec 2014'
set @min = 2200

-- get the number of days
set @days=datediff(day,@start,dateadd(minute,@min,@start))

-- get the due date
select max(Date)
from
    (select row_number() over( order by t.Id)-1 as Id,t.Date
     from DateMetadata t
     inner join BusinessDays b on Day(t.Date) = b.Day
     where t.Date > = @start and not exists(select 1 from Holidays h
                      where h.Day=Day(t.Date)
                      and h.Month=Month(t.Date))) as p
where p.Id < @days

Note :that DateMetadata table you will setup it in your database once
the setup for the above code :
create table Holidays(Id int identity(1,1),
                      Name nvarchar(50),
                      Day int,
                      Month int)
create table BusinessDays(Id int identity(1,1),
                           Name nvarchar(20),
                           Day int)

-- i am putting some days that are known,
--  it depends on you to define which holidays you want
insert into Holidays (Name,Day,Month) values('Christmas',25,12)
insert into Holidays(Name,Day,Month) values('New Year',31,12)
insert into Holidays(Name,Day,Month) values('Valentine',14,2)
insert into Holidays(Name,Day,Month) values('Mothers day',21,3)
insert into Holidays(Name,Day,Month) values('April fools day',1,4)

-- i am assuming that the business days are from monday till friday and
--  saturday and sunday are off days
insert into BusinessDays(Name,Day) values ('Monday',1)
insert into BusinessDays(Name,Day) values('Tuesday',2)
insert into BusinessDays(Name,Day) values('Wednesday',3)
insert into BusinessDays(Name,Day) values('Thursday',4)
insert into BusinessDays(Name,Day) values('Friday',5)

this table is needed and you will setup it once
-- set up a table that contains all dates from now till 2050 for example
-- and you can change the value of 2050 depending on your needs
-- this table you will setup it once
create table DateMetadata(Id int identity(1,1),
                          Date datetime)

declare @date datetime
set @date='01 Jan 2014'
while @date < '31 Dec 2050'
begin
   insert into DateMetadata(Date) values(@date)
   set @date = @date + 1
end

here a working DEMO
if you need any explanation, i am ready
hope it will help you

A: I created a function to calculate due date from the table, once it's populated as per Beth's and others' approaches (various similar methods for doing this, as you can see -- it only took me about an hour to think about all the UK holidays and populate the table including Easter dates up to 2029 without using these exact guides).
Note that my table contains SLA in business hours (8 hours in a normal day, 5 days in a normal week), your business hours may vary but you can amend this easily, just make sure your business hours are set the same for both the SLA table and the function below.
Code below is T-SQL (written in SSMS v17.8.1)
CREATE FUNCTION [JIRA].[Fn_JIRA_Due_Date] (
    @CreatedDate DATETIME, @SLA_Business_Hours INTEGER
) RETURNS DATETIME
AS
-- SELECT [JIRA].[Fn_JIRA_Due_Date]('2019-12-28 08:00:00', 24)

/*

baldmosher™
2019-03-25

* Function returns the DueDate for a JIRA ticket, based on the CreatedDate and the SLA (based on the Issue Type, or the Epic for Tasks) and business hours per date (set in [JIRA].[Ref_JIRA_Business_Hours])
* Called by IUP to store this at the time the ticket is loaded
* Can only consider SLA in Business Hours:
    * <24hrs calendar = <8hrs business
    * =24hrs calendar =  8hrs business
    * >24hrs calendar =  8hrs business * business days

*/

BEGIN

    IF @CreatedDate IS NULL OR @SLA_Business_Hours IS NULL RETURN NULL;

    DECLARE @SLA_Hours_Remaining SMALLINT = @SLA_Business_Hours;

    --SET DATEFIRST 1;
    DECLARE @DueDate DATETIME;
    DECLARE @BusHrsStart DECIMAL(18,10) = 8                         ; -- start of Business Hours (8am)
    DECLARE @BusHrsClose DECIMAL(18,10) = 16                        ; -- close of Business Hours (4pm)
    --DECLARE @WkndStart DECIMAL(18,10) = 6                         ; -- start of weekend (Sat)
    DECLARE @Hours_Today SMALLINT                                   ; -- # hours left in day to process ticket

    -- PRINT 'Created ' + CAST(CAST(@CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(@CreatedDate AS TIME) AS VARCHAR(8))

    --!!!! extend to the next whole hour just to simplify reporting -- need to work on fixing this eventually
    SET @CreatedDate = DATEADD(MINUTE,60-DATEPART(MINUTE,@CreatedDate),@CreatedDate)
    -- PRINT 'Rounded ' + CAST(CAST(@CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(@CreatedDate AS TIME) AS VARCHAR(8))

--check if created outside business hours and adjust CreatedDate to start the clock first thing at the next business hours start of day (days are checked next)
    IF DATEPART(HOUR,@CreatedDate) < @BusHrsStart
    --created before normal hours, adjust @CreatedDate later to @BusHrsStart same day
        BEGIN
        SET @CreatedDate = DATEADD(HOUR,@BusHrsStart,CAST(CAST(@CreatedDate AS DATE) AS DATETIME))
        END

    IF DATEPART(HOUR,@CreatedDate) >= @BusHrsClose
    --created after normal hours, adjust @CreatedDate to @BusHrsStart next day
        BEGIN
        SET @CreatedDate = DATEADD(HOUR,@BusHrsStart,CAST(CAST(@CreatedDate+1 AS DATE) AS DATETIME))
        --adjust CreatedDate to start the clock the next day with >0 business hours (i.e. extend if it falls on a weekend or holiday)
        SET @CreatedDate = CAST(@CreatedDate AS DATE)
        StartNextWorkingDay:
        IF (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = @CreatedDate ORDER BY [Date]) = 0
            BEGIN
            SET @CreatedDate = DATEADD(DAY,1,@CreatedDate)
            GOTO StartNextWorkingDay
            END
            --DATEADD(DAY, DATEDIFF(DAY,0,@CreatedDate+7)/7*7,0);  -- midnight, Monday next week
        SET @CreatedDate = DATEADD(HOUR,@BusHrsStart,@CreatedDate);  -- BusHrsStart
        END
    -- PRINT 'Started ' + CAST(CAST(@CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(@CreatedDate AS TIME) AS VARCHAR(8))

--third, check the business hours for each date from CreatedDate onwards to determine the relevant DueDate
    SET @DueDate = @CreatedDate
    -- PRINT 'SLA Hrs ' + CAST(@SLA_Hours_Remaining AS VARCHAR(2))
    SET @Hours_Today = @BusHrsStart + (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = CAST(@DueDate AS DATE) ORDER BY [Date]) - DATEPART(HOUR, @CreatedDate)
    -- PRINT 'Hrs Today ' + CAST(@Hours_Today AS VARCHAR(2))
    DueNextWorkingDay:
    IF @SLA_Hours_Remaining > @Hours_Today
        BEGIN
        -- PRINT 'Due another day'
        SET @SLA_Hours_Remaining = @SLA_Hours_Remaining - @Hours_Today            --adjust remaining time after today's hours
        SET @Hours_Today = (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = CAST(@DueDate AS DATE) ORDER BY [Date])
        -- PRINT 'SLA Hrs ' + CAST(@SLA_Hours_Remaining AS VARCHAR(2))
        -- PRINT 'Hrs Today ' + CAST(@Hours_Today AS VARCHAR(2))
        SET @DueDate = DATEADD(DAY,1,DATEADD(HOUR,@BusHrsStart,CAST(CAST(@DueDate AS DATE) AS DATETIME)))              --adjust DueDate to first thing next day
        END
    IF @SLA_Hours_Remaining <= @Hours_Today
        BEGIN
        -- PRINT 'Due today'
        SET @DueDate = DATEADD(HOUR,@SLA_Hours_Remaining,@DueDate)
        END
    ELSE
        BEGIN
        GOTO DueNextWorkingDay
        END

    -- PRINT 'DueDate ' + CAST(CAST(@DueDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(@DueDate AS TIME) AS VARCHAR(8))

    RETURN @DueDate

END

GO

Table for SLAs:
CREATE TABLE [JIRA].[Ref_JIRA_SLAs](
    [SLA_SK] [SMALLINT] IDENTITY(1,1) NOT NULL,
    [Project] [VARCHAR](20) NULL,
    [Issue_Type] [VARCHAR](50) NULL,
    [Epic_Name] [VARCHAR](50) NULL,
    [SLA_Business_Hours] [SMALLINT] NULL,
    [Comments] [VARCHAR](8000) NULL
) ON [PRIMARY] WITH (DATA_COMPRESSION = PAGE)
GO


text:
Q: How to verify the characteristic polynomial? I am computing the characteristic polynomial of a matrix over a number field, using the minimal polynomial of it. Is there a fast way to verify the characteristic polynomial of a big matrix ?

A: You can pick $n+1$ numbers and evaluate the determinant $det(A-tE)$ at these values. This gives you a garantee, but if you just want a rough check, you can pick smaller amount of (random) numbers and evaluate the determinants modulo some prime numbers (which is usually faster).


text:
Q: cakephp user/login redirects to users/login automatically I have a model called "user" and a controller for "user" with an action "login".
The controller is empty right now as I'm simply testing the page, however, going to www.mysite.com/user/login redirects me automatically to www.mysite.com/user*s*/login and then says that the users controller does not exist.
I know it doesn't exist but I'm not TRYING to access the page, why is it redirecting me there?
I also have a /user/register page which works fine.
function login()
{

}

Is this due to some form of cakephp's built in functionality?

A: You should always have
www.mysite.com/users/login

Because your models are always pluralized. Remember, you should have:
model/user.php
controller/users_controller.php
views/users/...

A: it's for this code in the app_controller.php:
 class AppController extends Controller
    {
      var $components = array('Auth');
    }

you "should" have login() function.


text:
Q: Images being frozen/delayed using VLCj and Java Swing I'm making a mosaic for viewing videos. I build a JFrame with some components, including Canvas. I place an instance of a MediaPlayer on each Canvas and play the video. But I'm having problems with frame loss, delayed display and even complete freezing of images. Is there anything that can be done to solve this problem??
Mosaic:

(Images have been hidden to protect software integrity)

Code:
public class ViewerController {

    private List<EmbeddedMediaPlayer> playerList = new ArrayList<>();

    private List<Canvas> canvasList = new ArrayList<>();

    public ViewerController() {
        gerarTela();
    }

    private void gerarTela() {
        String[] args = {
                "--rtsp-tcp",
                "--network-caching=1000",
                "--file-caching=300",
                "--clock-jitter=0",
                "--clock-synchro=0"
        };
        JFrame janela = geraJframe();
        var painelDaJanela = new JPanel(new GridLayout(0, 4, 5, 5));
        var factory = new MediaPlayerFactory(args);

        for (int i = 0; i < 16; i++) {
            var containerDoVideo = new Canvas();
            containerDoVideo.setBackground(Color.BLACK);

            JPanel painelDoContainer = new JPanel();
            painelDoContainer.setBackground(new Color(31, 27, 36));
            painelDoContainer.setLayout(new BorderLayout());
            painelDoContainer.add(containerDoVideo, BorderLayout.CENTER);

            var player = factory.newEmbeddedMediaPlayer();
            player.setVideoSurface(factory.newVideoSurface(containerDoVideo));

            playerList.add(player);
            painelDaJanela.add(painelDoContainer);
            canvasList.add(containerDoVideo);
        }

        painelDaJanela.setBackground(new Color(31, 27, 36));
        janela.add(painelDaJanela, BorderLayout.CENTER);
        janela.setResizable(true);
        janela.setExtendedState(JFrame.MAXIMIZED_BOTH);
        janela.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowEvent) {
                stop();
                super.windowClosing(windowEvent);
            }
        });
        janela.setVisible(true);
    }

    public void play(List<Camera> lista) {
        int limiteLista = lista.size();

        for (int i = 0; i < 16; i++) {
            if (!(i < limiteLista)) {
                canvasList.get(i).setBackground(new Color(31, 27, 36));
            } else {
                Camera camera = lista.get(i);
                playerList.get(i).playMedia(camera.getUrl_video());
            }
        }
    }

    private void stop() {
        playerList.forEach(MediaPlayer::stop);
    }

    private JFrame geraJframe() {
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        JFrame jFrame = new JFrame();
        jFrame.setMinimumSize(new Dimension(d.width, d.height));
        jFrame.setLayout(new BorderLayout());
        jFrame.setIconImage(tk.getImage(getClass().getResource("/imgs/icon.png")));
        jFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        return jFrame;
    }
}


text:
Q: how to ignore line break in text search? Using sed, I want to search a string and replace that with other in maven pom.xml
<groupId>com.abc</groupId>
<version>3.1</version>

with
<groupId>com.abc</groupId>
<version>4.1</version>

I wrote
find . -name 'pom.xml' -type f -exec sed -i "s!"<groupId>com.abc</groupId>\n
<version>3.1</version>"!"<groupId>com.abc</groupId>\n    <version>4.1</version>!" '{}' \;

But it never works!

A: Don't use sed for this. linebreaks are part of who sed is. This is a job for xslt.
The following code snippet was borrowed and tweaked from http://chrisdail.com/2009/05/17/changing-maven-pom-versions-with-groovy-and-xslt/
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="version[../groupId='com.abc']">
        <version>4.1</version>
    </xsl:template>
</xsl:stylesheet>

Just do xsltproc thisfile.xsl pom.xml

A: You need to use the N command to read the next line. Take a look at the excellent Sed and Awk book for more details on handling multiline pattern spaces. It is a bit fiddly.
Save this sed command to a file e.g cmd.txt
/<groupId>com.abc<\/groupId>/{
N
s/<groupId>com.abc<\/groupId>\n<version>3.1<\/version>/<groupId>com.abc<\/groupId>\n<version>4.1<\/version>/
}

Then run:
$ sed -f cmd.txt pom.xml

A: Try this ... Hope it helps.
sed -e 's/3.1/4.1/g' pom.xml > pom1.xml


text:
Q: Batch file to move all subfolder files up then delete empty subfolders? I have a folder that contains many subfolders, each with different files in them:
C:/folder/subfolder1/file1.jpg,
C:/folder/subfolder2/file2.jpg,
C:/folder/subfolder3/file3.jpg,
etc.

How can I create a batch file that moves the files in the subfolders to the folder, then deletes the empty subfolders.
ie. After the bat file is run, the folder structure should be as follows:
C:/folder/file1.jpg
C:/folder/file2.jpg
C:/folder/file3.jpg
etc.

A: try this
@echo off
for /f "tokens=*" %%f in ('dir /a:-D /s /b') do move "%%f" .
for /f "tokens=*" %%f in ('dir /a:D /s /b') do rd "%%f"

A: This will go through every folder in %root% (C:\folder) and copy the contents to %root% -
@echo off
set root=c:\folder
for /f %%a in ('dir /b /ad %root%') do (
    for /f %%b in ('dir /b %root%\%%a') do move "%root%\%%a\%%b" "%root%\%%b"
    rmdir "%root%\%%a"
)

A: I used this as a batch file to move all files from subfolders in the current folder then delete the empty folders.
rem Copy all files from subfolders in the current folder to the current folder.
for /R %cd% %%G IN (*.*) DO move /Y "%%G"
rem Move all directories into a temp folder in the current folder.
for /D %%I in (*) do move /y %%I %cd%\temp
rem Remove the temp folder including empty folders.
rmdir /s/q %cd%\temp


text:
Q: Wake computer from sleep every hour? I need my computer to wake up from sleep, and go back to sleep, hourly.
Now i've created tasks in the Task Scheduler, and so far I haven't managed to get the exact behaviour i want.
To keep it simple, i want it to wake up, go back to sleep - and do that every hour.
I use Windows 10
Thanks for help in advance

A: If you want to do some stuff in your way try creating batch file. For your second question I hope this may help you https://www.raymond.cc/blog/automatically-wake-up-from-windows-stand-by-and-hibernation/.


text:
Q: Iterate over list of Functions in R I'm currently writing a utility to run a series of test on a set of data. I have the data in a data.frame and would like to run N tests on each row of data. (Apologies if my terminology isn't all there: I've been using R for all of five hours).
In my utility, I would like to split the tests into different files and in the main program, load all those tests and run them once for each data.frame row. Here's what I'm doing to source the relevant files:
file.sources = list.files(pattern="validator-.*.R$")
sapply(file.sources,source,verbose = TRUE)

This works well, and if I do this in each matched file:
b <- function(a) {
  if(grep("^[[:blank:]]*$", a)) {
    return(FALSE)
  } else {
    return(TRUE)
}

test.functions <- append(test.functions, b)

Then I end up with a test.function list which accurately contain all the test functions to run, but this is now where I get stuck. I've tried variations of sapply() and I think do.call() is also relevant in this. This is my current attempt:
process.entry <- function(a) {
  lapply(test.functions,do.call,a)
}
sapply(all.data,process.entry)

My attempt here was to create a function which takes one row of data as its argument, iterates over test.functions and calls do.call() with the function and row of data as arguments. This doesn't seem to work quite, and the error thrown is:
Error in FUN(X[[i]], ...) : second argument must be a list

However, I'm not entirely sure where this error occurs, and quite possibly: there are other, cleaner, ways of doing what I intend!

A: # I would
process.entry <- function(a) {
    # call each function to a
    # I think a anonymous function is easier here;
    lapply(test.functions, function(f) f(a))
}

# sapply iterate over column of data.frame by default,
# if you want to iterate over rows, use for or apply;
apply(all.data, 1, process.entry)


text:
Q: A little assistance with my GUI programming integrated with recursion in Java Please I need some help with my GUI program in Java. My program uses GUI interface to take in the nth term from the user; it then calculates the Fibonacci number of that term and prints it in the interface. Please have a look at my program. I would like to know two things:

*

*How do I assign a variable to the return value in the fib function?

*After setting a variable to the return value, I want to have an access to that variable in my actionPerformed method, so I can print it to the interface.

Program
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class GUIwithRecursion extends Applet implements ActionListener
{
public static TextField numberTF = new TextField ();
public static TextField fibTF    = new TextField();

int result = fib(numberN);

public void init()
{
setBackground(Color.magenta);
Label     numberLB = new Label("n= ");
Button    calcBN   = new Button("Calculate");
Label     fibLB    = new Label("fib(n)= ");

setLayout(null);
numberLB.setBounds(10, 30, 100, 20);
numberTF.setBounds(10, 50, 100, 20);
numberTF.setBackground(Color.yellow);
fibLB.setBounds(10, 70, 100, 20);
fibTF.setBounds(10, 90, 100, 20);
fibTF.setBackground(Color.red);
calcBN.setBounds(10, 110, 100, 20);

add(numberLB);
add(numberTF);
add(fibLB);
add(fibTF);
add(calcBN);

calcBN.addActionListener(this);
}

public static int fib(int numberN)
{
    if (numberN<=1)
    {return 1;}

    else
    {return fib(numberN-1)+fib(numberN-2);}
}

public void actionPerformed(ActionEvent e)
{

    int result = fib(numberN);
    fibTF.setText(Integer.toString(result));

}
}

A:
1) How do I assign a variable to the return value in the fib function?

int number = Integer.parseInt(numberTF.getText());
int result = fib(number);

2) After setting a variable to the return value, I want to have an access to that variable in my actionPerformed function, so I can print it to the interface.

A better solution would be to perform the calculation in the actionPerformed method
public void actionPerformed(ActionEvent e) {
    int number = Integer.parseInt(numberTF.getText());
    int result = fib(number);
    fibTF.setText(Integer.toString(result));
}

The next question would be, why Applet and why the AWT library?  Both have been superseded by Swing (and now JavaFX) and applets are now been actively blocked by most browsers.
You will generally get better support for Swing and JavaFX and most people are using those libraries for development of pure AWT now days
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design.  There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Take a look at Laying Out Components Within a Container for more details


text:
Q: Basic camera system for my pygame platformer Hi I am currently trying to create a platformer and I tried creating a camera system for it. But after many tries I still cannot find a good way to do it even after having tried everything I saw online. I would really like the camera to work a bit like this animation I found here Any advices on how I should approach this?
import pygame,sys

pygame.init()

# Settings
tile_size = 64
fov = 10
screen_width = 1200
screen_height = tile_size * fov

level_data = [
'                       ',
'                       ',
'                  XX   ',
'XX    XXX              ',
'XX                   XX',
'XXXX        XX         ',
'XXXX  P   XX           ',
'XX    X  XXX    XX  X  ',
'      X  XXX    XX  XX ',
'   XXXX  XXXXX  XX  XXX',
'XXXXXXX  XXXXX  XX  XXX']

# Classes
class Game():
    def __init__(self):
        self.level = Level(screen)
        self.status = 'level'

    def run(self):
        if self.status == 'level':
            self.level.run()

class Level:
    def __init__(self,display_surface):
        # Basic setup
        self.setup_level()
        self.display_surface = display_surface

        # Movement
        self.x_shift = 0
        self.y_shift = 0

    def setup_level(self):
        self.tiles = pygame.sprite.Group()
        self.player = pygame.sprite.GroupSingle()
        for row_index,row in enumerate(level_data):
            for col_index,col in enumerate(row):
                x = col_index * tile_size
                y = (row_index * tile_size) - ((len(level_data) - fov) * tile_size)
                if col == 'X':
                    tile = Tile((x,y))
                    self.tiles.add(tile)
                if col == 'P':
                    player = Player((x,y))
                    self.player.add(player)

    def vertical_movement_collision(self):
        player = self.player.sprite
        player.apply_gravity()

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.y > 0:
                    player.rect.bottom = sprite.rect.top
                    player.on_ground = True
                elif player.direction.y < 0:
                    player.rect.top = sprite.rect.bottom
                player.direction.y = 0

        if player.on_ground and player.direction.y > 1 or player.direction.y < 0:
            player.on_ground = False

    def horizontal_movement_collision(self):
        player = self.player.sprite
        player.rect.x += player.direction.x * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.x > 0:
                    player.rect.right = sprite.rect.left
                elif player.direction.x < 0:
                    player.rect.left = sprite.rect.right

    def run(self):
        self.vertical_movement_collision()
        self.horizontal_movement_collision()

        # Tiles
        self.tiles.update(self.x_shift,self.y_shift)
        self.tiles.draw(self.display_surface)

        # Player
        self.player.update()
        self.player.draw(self.display_surface)

class Tile(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        self.image = pygame.Surface((tile_size,tile_size))
        self.image.fill('grey')
        self.rect = self.image.get_rect(topleft = pos)
        self.x = self.rect.x
        self.y = self.rect.y

    def update(self,x_shift,y_shift):
        self.x += x_shift
        self.y -= y_shift
        self.rect.topleft = round(self.x), round(self.y)

class Player(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        # Image
        self.image = pygame.Surface((32,64))
        self.image.fill('red')
        self.rect = self.image.get_rect(topleft = pos)

        # Movement
        self.direction = pygame.math.Vector2(0,0)
        self.speed = 8
        self.gravity = 0.8
        self.jump_speed = -20

        # Status
        self.on_ground = False

    def get_inputs(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_SPACE]:
            self.jump()
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.direction.x = 1
        elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0

    def apply_gravity(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y

    def jump(self):
        if self.on_ground:
            self.direction.y = self.jump_speed

    def update(self):
        self.get_inputs()

# Game setup
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Platformer')
clock = pygame.time.Clock()
game = Game()

# Main
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('black')
    game.run()

    pygame.display.update()
    clock.tick(60)

A: In basic camera system you keep player in center. So camera depends on player position and screen size
camera_x = -self.player.sprite.rect.centerx + self.display_surface.get_rect().centerx
camera_y = -self.player.sprite.rect.centery + self.display_surface.get_rect().centery

camera = (camera_x, camera_y)

and later you have to add camera to all sprites when you blit it - but not add this to sprite position.
    def draw(self, screen, camera):
        screen.blit(self.image, self.rect.move(camera))

But it needs to run draw() for every sprite separatelly because group.draw() runs directly blit(self.image, self.rect)

For more complex camera system you have to write more complex code which checks player position and change it in different way (using if/else)

Minimal working code:
import pygame,sys

# Classes
class Game():
    def __init__(self):
        self.level = Level(screen)
        self.status = 'level'

    def run(self):
        if self.status == 'level':
            self.level.run()

class Level:
    def __init__(self,display_surface):
        # Basic setup
        self.setup_level()
        self.display_surface = display_surface

        # Movement
        self.x_shift = 0
        self.y_shift = 0

    def setup_level(self):
        self.tiles = pygame.sprite.Group()
        self.player = pygame.sprite.GroupSingle()
        for row_index,row in enumerate(level_data):
            for col_index,col in enumerate(row):
                x = col_index * tile_size
                y = (row_index * tile_size) - ((len(level_data) - fov) * tile_size)
                if col == 'X':
                    tile = Tile((x,y))
                    self.tiles.add(tile)
                if col == 'P':
                    player = Player((x,y))
                    self.player.add(player)

    def vertical_movement_collision(self):
        player = self.player.sprite
        player.apply_gravity()

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.y > 0:
                    player.rect.bottom = sprite.rect.top
                    player.on_ground = True
                elif player.direction.y < 0:
                    player.rect.top = sprite.rect.bottom
                player.direction.y = 0

        if player.on_ground and player.direction.y > 1 or player.direction.y < 0:
            player.on_ground = False

    def horizontal_movement_collision(self):
        player = self.player.sprite
        player.rect.x += player.direction.x * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.x > 0:
                    player.rect.right = sprite.rect.left
                elif player.direction.x < 0:
                    player.rect.left = sprite.rect.right

    def run(self):
        self.vertical_movement_collision()
        self.horizontal_movement_collision()

        # Tiles
        self.tiles.update(self.x_shift,self.y_shift)
        self.player.update()

        camera_x = -self.player.sprite.rect.centerx + self.display_surface.get_rect().centerx
        camera_y = -self.player.sprite.rect.centery + self.display_surface.get_rect().centery
        camera = (camera_x, camera_y)
        print(camera)

        for item in self.tiles:
            item.draw(self.display_surface, camera)

        self.player.sprite.draw(self.display_surface, camera)

class Tile(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        self.image = pygame.Surface((tile_size,tile_size))
        self.image.fill('grey')
        self.rect = self.image.get_rect(topleft = pos)
        self.x = self.rect.x
        self.y = self.rect.y

    def update(self,x_shift,y_shift):
        self.x += x_shift
        self.y -= y_shift
        self.rect.topleft = round(self.x), round(self.y)

    def draw(self, screen, camera):
        screen.blit(self.image, self.rect.move(camera))

class Player(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        # Image
        self.image = pygame.Surface((32,64))
        self.image.fill('red')
        self.rect = self.image.get_rect(topleft = pos)

        # Movement
        self.direction = pygame.math.Vector2(0,0)
        self.speed = 8
        self.gravity = 0.8
        self.jump_speed = -20

        # Status
        self.on_ground = False

    def get_inputs(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_SPACE]:
            self.jump()
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.direction.x = 1
        elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0

    def apply_gravity(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y

    def jump(self):
        if self.on_ground:
            self.direction.y = self.jump_speed

    def update(self):
        self.get_inputs()

    def draw(self, screen, camera):
        screen.blit(self.image, self.rect.move(camera))

# --- main ---

pygame.init()

# Settings
tile_size = 64
fov = 10
screen_width = 1200
screen_height = tile_size * fov

level_data = [
'                       ',
'                       ',
'                  XX   ',
'XX    XXX              ',
'XX                   XX',
'XXXX        XX         ',
'XXXX  P   XX           ',
'XX    X  XXX    XX  X  ',
'      X  XXX    XX  XX ',
'   XXXX  XXXXX  XX  XXX',
'XXXXXXX  XXXXX  XX  XXX']

# Game setup
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Platformer')
clock = pygame.time.Clock()
game = Game()

# Main
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('black')
    game.run()

    pygame.display.update()
    clock.tick(60)

EDIT:
More complex camera system - it doesn't move map when player is near the border of map.
    def run(self):
        self.vertical_movement_collision()
        self.horizontal_movement_collision()

        # Tiles
        self.tiles.update(self.x_shift, self.y_shift)
        self.player.update()

        map_left   = 0
        map_right  = len(level_data[0])*tile_size
        map_top    = 0
        map_bottom = len(level_data)*tile_size

        camera_x = -self.player.sprite.rect.centerx + self.display_surface.get_rect().centerx

        if self.player.sprite.rect.centerx < map_left + self.display_surface.get_rect().centerx:
            camera_x = -map_left
        if self.player.sprite.rect.centerx > map_right - self.display_surface.get_rect().centerx:
            camera_x = -(map_right - self.display_surface.get_rect().width)

        camera_y = -self.player.sprite.rect.centery + self.display_surface.get_rect().centery

        if self.player.sprite.rect.centery < map_top + self.display_surface.get_rect().centery:
            camera_y = -map_top
        if self.player.sprite.rect.centery > map_bottom - self.display_surface.get_rect().centery:
            camera_y = -(map_bottom - self.display_surface.get_rect().height)

        camera = (camera_x, camera_y)

        for item in self.tiles:
            item.draw(self.display_surface, camera)

        self.player.sprite.draw(self.display_surface, camera)

but in setup_level() it needs y without - ((len(level_data) - fov) * tile_size)
y = (row_index * tile_size) # - ((len(level_data) - fov) * tile_size)

Full code:
import pygame,sys

# Classes
class Game():
    def __init__(self):
        self.level = Level(screen)
        self.status = 'level'

    def run(self):
        if self.status == 'level':
            self.level.run()

class Level:
    def __init__(self,display_surface):
        # Basic setup
        self.setup_level()
        self.display_surface = display_surface

        # Movement
        self.x_shift = 0
        self.y_shift = 0

    def setup_level(self):
        self.tiles = pygame.sprite.Group()
        self.player = pygame.sprite.GroupSingle()
        for row_index,row in enumerate(level_data):
            for col_index,col in enumerate(row):
                x = col_index * tile_size
                y = (row_index * tile_size)# - ((len(level_data) - fov) * tile_size)
                if col == 'X':
                    tile = Tile((x,y))
                    self.tiles.add(tile)
                if col == 'P':
                    player = Player((x,y))
                    self.player.add(player)

    def vertical_movement_collision(self):
        player = self.player.sprite
        player.apply_gravity()

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.y > 0:
                    player.rect.bottom = sprite.rect.top
                    player.on_ground = True
                elif player.direction.y < 0:
                    player.rect.top = sprite.rect.bottom
                player.direction.y = 0

        if player.on_ground and player.direction.y > 1 or player.direction.y < 0:
            player.on_ground = False

    def horizontal_movement_collision(self):
        player = self.player.sprite
        player.rect.x += player.direction.x * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.x > 0:
                    player.rect.right = sprite.rect.left
                elif player.direction.x < 0:
                    player.rect.left = sprite.rect.right

    def run(self):
        self.vertical_movement_collision()
        self.horizontal_movement_collision()

        # Tiles
        self.tiles.update(self.x_shift, self.y_shift)
        self.player.update()

        map_left   = 0
        map_right  = len(level_data[0])*tile_size
        map_top    = 0
        map_bottom = len(level_data)*tile_size

        camera_x = -self.player.sprite.rect.centerx + self.display_surface.get_rect().centerx

        if self.player.sprite.rect.centerx < map_left + self.display_surface.get_rect().centerx:
            camera_x = -map_left
        if self.player.sprite.rect.centerx > map_right - self.display_surface.get_rect().centerx:
            camera_x = -(map_right - self.display_surface.get_rect().width)

        camera_y = -self.player.sprite.rect.centery + self.display_surface.get_rect().centery

        if self.player.sprite.rect.centery < map_top + self.display_surface.get_rect().centery:
            camera_y = -map_top
        if self.player.sprite.rect.centery > map_bottom - self.display_surface.get_rect().centery:
            camera_y = -(map_bottom - self.display_surface.get_rect().height)

        camera = (camera_x, camera_y)

        for item in self.tiles:
            item.draw(self.display_surface, camera)

        self.player.sprite.draw(self.display_surface, camera)

class Tile(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        self.image = pygame.Surface((tile_size,tile_size))
        self.image.fill('grey')
        self.rect = self.image.get_rect(topleft = pos)
        self.x = self.rect.x
        self.y = self.rect.y

    def update(self, x_shift, y_shift):
        self.x += x_shift
        self.y -= y_shift
        self.rect.topleft = round(self.x), round(self.y)

    def draw(self, screen, camera):
        screen.blit(self.image, self.rect.move(camera))

class Player(pygame.sprite.Sprite):
    def __init__(self,pos):
        super().__init__()
        # Image
        self.image = pygame.Surface((32,64))
        self.image.fill('red')
        self.rect = self.image.get_rect(topleft = pos)

        # Movement
        self.direction = pygame.math.Vector2(0,0)
        self.speed = 8
        self.gravity = 0.8
        self.jump_speed = -20

        # Status
        self.on_ground = False

    def get_inputs(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_SPACE]:
            self.jump()
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.direction.x = 1
        elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0

    def apply_gravity(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y

    def jump(self):
        if self.on_ground:
            self.direction.y = self.jump_speed

    def update(self):
        self.get_inputs()

    def draw(self, screen, camera):
        screen.blit(self.image, self.rect.move(camera))

# --- main ---

pygame.init()

# Settings
tile_size = 64
fov = 10
screen_width = 1200
screen_height = tile_size * fov

level_data = [
'                       ',
'                       ',
'                  XX   ',
'XX    XXX              ',
'XX                   XX',
'XXXX        XX         ',
'XXXX  P   XX           ',
'XX    X  XXX    XX  X  ',
'      X  XXX    XX  XX ',
'   XXXX  XXXXX  XX  XXX',
'XXXXXXX  XXXXX  XX  XXX']

# Game setup
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Platformer')
clock = pygame.time.Clock()
game = Game()

# Main
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('black')
    game.run()

    pygame.display.update()
    clock.tick(60)


text:
Q: Error when an agg pipeline assigns a value to the $$Maincode builtin variable    var lookup =
                        new BsonDocument("$lookup",
                        new BsonDocument
                        {
                            {"from","DepoStatus" },
                            {"let",new BsonDocument{ {Maincode,"$Maincode"},{ColorCode , "$Renkcode" } } },
                            {"pipeline",
                                new BsonArray{
                                    new BsonDocument("$match",
                                    new BsonDocument("$expr",
                                    new BsonDocument("$and",
                                      new BsonArray{new BsonDocument("$eq",
                                      new BsonArray { "$Maincode", "$$Maincode" }),new BsonDocument("$eq", new BsonArray { "$Renkcode", "$$Renkcode" })}))),
                                }
                            },
                            {"as","statuses"}
                        });

                    var pipeline1 = new[] { lookup };
                    var depostatus = czProductcollection.Aggregate<Product>(pipeline1).ToList();

MongoDB.Driver.MongoCommandException: 'Command aggregate failed: '20.296' starts with an invalid character for a user variable name.'
I get an error. What can I do ?


text:
Q: Asynchronous request from database in node.js i am making an asynchronous request to a database and then running a loop on the resultant data but i am getting only the last value while sending a response to front-end
routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    var colNameArray1={};
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    const newData= data.map( (item)=>{
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        return colNameArray1
    })

    //in response i am getting just the data from the last index
    res.json(newData)
})

In response i am getting just the data from the last index. Please advise how i can handle this asynchronous request

A: If you want all the rows, then you should push each object you can create in to an array. In the above code, you are overwriting over the same object.
Try updating the code to the following:
routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    var colNameArray1={};
    const dataList = [] // Create a empty array
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    data.forEach( (item)=>{
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        dataList.push(colNameArray1) // Push to the array
    })

    //in response i am getting just the data from the last index
    res.json(dataList)
})

A: You must declare colNameArray1 inside the map function:
routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    const newData= data.map( (item)=>{
        var colNameArray1={};
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        return colNameArray1
    })

    //in response i am getting just the data from the last index
    res.json(newData)
})

A: i found the issue and it has nothing to do with the asynchronous request and as mentioned above its confirmed that i am overwriting the object. Cloning the object using spread {... obj} has solved the issue. Thanks for help.


text:
Q: How to get active state of link (in CSS) to work? Can't see why a:active is not working!
Want link button to remain blue (#1770b8) when active, same as hover state.
[Tried in Firefox, IE and Chrome]
Have I done something silly?!
a:hover
 - Hover works fine.
a:link
 - Button is black, so this works.
a:visited
 - Button stays black (does not default to grey) so this works.
.woocommerce-MyAccount-navigation li a:link,
.woocommerce-MyAccount-navigation li a:visited {
    padding:5px;
    display:block;
    width:150px;
    color:#ffffff;
    background-color:#000 !important;
    border:1px solid #000;
}
.woocommerce-MyAccount-navigation li a:hover,
.woocommerce-MyAccount-navigation li a:active {
    padding:5px;
    display:block;
    width:150px;
    color:#ffffff;
    background-color:#1770b8 !important;
    border:1px solid #000;
}

A: You're telling the the active link to have a foreground color of white and a background-color which is the same as the hover state (the bluish color, #1770b8). This makes it impossible to see the difference in states.
If you separate the :active state into a new style instruction, you can see it's working. For example, I'll set the active foreground color of the link to red:

.woocommerce-MyAccount-navigation li a:link,
.woocommerce-MyAccount-navigation li a:visited {
  padding: 5px;
  display: block;
  width: 150px;
  color: #ffffff;
  background-color: #000 !important;
  border: 1px solid #000;
}

.woocommerce-MyAccount-navigation li a:hover {
  padding: 5px;
  display: block;
  width: 150px;
  color: #ffffff;
  background-color: #1770b8 !important;
  border: 1px solid #000;
}

.woocommerce-MyAccount-navigation li a:active {
  color: red;
}

test link

https://jsfiddle.net/upomysez/


text:
Q: Cannot retrieve the latest update value from database after running the ORM Lite UpdateBuilder.update() in android I have trouble when updating the data in android by using ORM Lite because my updated data is not affected in database immediately.
After the update process, I query the data from the database but I got the old data that was the same as before I update.
So, I solved this problem by refreshing each updated object by using refresh(Object) after the update process, the problem was OK(I can access the latest updated data from data in next query).
But I am not sure is it the best way or not? If there have another ways to
solve this problem, could you please tell me?
Thanks.
Run the batch update by using UpdateBuilder.
try {
    Set<String> ids = accountIdSet;
    UpdateBuilder<Account, Long> updateBuilder = account.updateBuilder();
    updateBuilder.where().in(Account.ID,ids);
    updateBuilder.updateColumnValue(Account.REGISTERED, true);
    return updateBuilder.update();
} catch (SQLException e) { }
return 0;

After update process I do the query data from database by below lines.
try {
    Set<String> ids = accountIdSet;
    List<Account> result =  Account.queryBuilder().where().in(Account.ID, ids).query();
    if (result!=null) {
        for (Account acc : result) {
            Log.i(acc.getId() + ", registered = " + acc.getRegistered());
        }
        return result;
    }
} catch (SQLException e) { }
return null;

At that time I got the old value of data. For example -
1, registered = false
2, registered = false
3, registered = false

Result should be
1, registered = true
2, registered = true
3, registered = true


text:
Q: eplain packages with plain tex no longer have all needed definitions If one uses tex rather than pdftex, one gets errors when inputting certain packages with eplain. For example, let test.tex be this file:
\input /usr/share/texlive/texmf-dist/tex/eplain/eplain
\beginpackages
   \usepackage{graphicx}
\endpackages

\bye

Running tex test.tex gives
This is TeX, Version 3.14159265 (TeX Live 2019/Debian) (preloaded format=tex)
(./test.tex (/usr/share/texlive/texmf-dist/tex/eplain/eplain.tex)
(/usr/share/texlive/texmf-dist/tex/plain/graphics-pln/miniltx.tex)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics-cfg/graphics.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/graphics-def/dvips.def)
! Undefined control sequence.
l.118 \protected
                \def\includegraphics{%
?
! Undefined control sequence.
l.171 \edef\Gin@gzext{\detokenize
                                 {gz}}
?
! Undefined control sequence.
l.413 \protected
                \long\def\rotatebox#1#2{%
?
! Undefined control sequence.
l.482 \protected
                \def\scalebox#1{%
?
! Undefined control sequence.
l.501 \protected
                \def\reflectbox{\Gscale@box-1[1]}
?
! Undefined control sequence.
l.502 \protected
                \def\resizebox{%
?
)
! Undefined control sequence.
l.239 \protected
                \def\rotatebox{%
?
) [1] )
Output written on test.dvi (1 page, 236 bytes).
Transcript written on test.log.

whereas running pdftex test.tex gives no errors:
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019/Debian) (preloaded format=pdftex)
 restricted \write18 enabled.
entering extended mode
(./test.tex (/usr/share/texlive/texmf-dist/tex/eplain/eplain.tex)
(/usr/share/texlive/texmf-dist/tex/plain/graphics-pln/miniltx.tex)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics-cfg/graphics.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/graphics-def/pdftex.def)))
(/usr/share/texlive/texmf-dist/tex/context/base/mkii/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
) )
No pages of output.
Transcript written on test.log.

There were no problems with TeX Live 2015/Debian:
This is TeX, Version 3.14159265 (TeX Live 2015/Debian) (preloaded format=tex)
(./test.tex (/usr/share/texlive/texmf-dist/tex/eplain/eplain.tex)
(/usr/share/texlive/texmf-dist/tex/plain/graphics-pln/miniltx.tex)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/dvips.def))) )
No pages of output.
Transcript written on test.log.

What is the proper fix for this?

A: LaTeX packages assume the presence of etex extensions such as \protected sometimes you get lucky and none are actually used but graphics (now) uses \protected.
The etex extensions are available in all engines (pdftex, luatex, xetex, etex) but the tex format uses the classical tex unextended format as required to use the tex name.
So you can simply use etex (or equivalently pdftex with \pdfoutput=0) to use plain tex with dvi output.


text:
Q: SP 2013 Blog Page Shows List when clicking on Blog Post I have been asked to fix a SP2013 Blog site created by my boss. The issue is that when you click on the title of a specific blog post from list view, it simply shows the list again on load. The expected action is to view the details of the item selected.
I have not tried to delete the blog because it's actively used with about 125 items. Is there a way to edit the part specifically so that when clicking the item you see just that item?
Any help is appreciated.

A: Go to Posts list view page(/Lists/Posts/AllPosts.aspx) in blog site, and Modify the View to check if you use the Title (linked to item with edit menu) field in list view.

And back to the list view page, click this link Title column again to check it it works.
And you can check if some custom code in this list view page.


text:
Q: Largest Among ten numbers using Arrays What's wrong with my code? It always returns the last number but not the largest? I have spent the last half and hour scratching my head & I still can't find what's wrong here..
Please help
// Largest among ten numbers

#include <stdio.h>
#include <conio.h>

int num[10],large,b; // Global Variables
int largest(int a); // Function protype

int main()
{
    for(int i=0;i<5;i++)
    {
        printf("Enter number %d = ",i+1);
        scanf("%d",&num[i]);
        large = largest(num[i]); // Calling Function
        /*
            printf("Num(%d)= %d",i,num[i]); // Testing
            printf("\nLargest for now = %d\n\n",large); //  Testing
        */
    }
    printf("\n\n\n%d is the largest",large);
    getch();
}

int largest(int a) // Function definition
{
    if (a>=b)
        {
            return a;
            b=a;
        }
    else
        {
            return b;
        }
}

A: The problem is here:
if (a>=b)
    {
        return a;
        b=a;
    }

You return before assigning so b is always 0. Just do the assignment before returning i.e.
if (a>=b)
    {
        b=a;
        return a;
    }

Demo


text:
Q: self-referencing relationship in entity model I am building a spring mvc app with hibernate to interact with a third party database that uses a transitive closure table to manage nested subtype and supertype relationships between millions of different types of vehicles stored in a vehicles table. There is also a vehicles_transitiveclosure table that stores lists of subtypes and supertypes so that a user can pull all ancestors or all descendents of a specific vehicleid.  (Car, van, truck, etc.  Car has subtypes sedan, wagon, etc. With many levels of nesting.)
I created a vehicle entity in my spring mvc app, but I am not sure how to represent the transitive closure table in spring mvc.
vehicles table
    vehicleid(pk)
    other fields

vehicles_transitiveclosure table
    subtypeid(fk to vehicleid)
    supertypeid(fk to vehicleid)
    other fields

I hesitate to treat vehicles_transitiveclosure as a junction table because there are a few other fields in each row of vehicles_transitiveclosure.  Also, it is a self-referencing relationship for the vehicles entity.  How should I set up my entity model to represent this relationship?
The reason for the transitive closure table is that it enables fast access to all ancestors or all descendents of a given vehicle.  The alternative would be a very resource intensive iterative algorithm to retrieve all the nested levels of subtype and supertype relationships stored in other tables.


text:
Q: how to add ListView with orientation as horizontal from code behind in uwp? I have to achieve this syntax from code behind how can I do that
    <ListView>
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <ItemsStackPanel Orientation="Horizontal"
                     />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>

in general how can I achieve property element syntax from code behind in uwp?

A: You can achieve it this way.
<ListView x:Name="AwesomeListView" ItemsSource="{x:Bind Items}">
    <!--
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsStackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    -->
</ListView>

public sealed partial class MainPage : Page
{
    public List<int> Items { get; set; } = new List<int>() { 1, 2, 3, 4, 5 };

    public MainPage()
    {
        this.InitializeComponent();

        this.AwesomeListView.ItemsPanel = CreateItemsPanelTemplate(Orientation.Horizontal);
    }

    ItemsPanelTemplate CreateItemsPanelTemplate(Orientation orientation)
    {
        string xamlString =
            $@"<ItemsPanelTemplate
                    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                    <ItemsStackPanel Orientation='{orientation}' />
                </ItemsPanelTemplate>";

        return (ItemsPanelTemplate)XamlReader.Load(xamlString);
    }
}

A:
how to add ListView with orientation as horizontal from code behind in uwp?

For making ItemsPanelTemplate in the code behind, you could parse ItemsPanelTemplate string and then pass it to ListView's ItemsPanel.
private void ApplyItemsStackPanelAsItemsPanel(ItemsControl itemsControl)
{

    var itemsPanelTemplateXaml =
        $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                          xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
           <ItemsStackPanel Orientation='Horizontal'/>
       </ItemsPanelTemplate>";

    itemsControl.ItemsPanel = (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml);

}

Usage
private void BuildListView()
{
    var listview = new ListView();
    ApplyItemsStackPanelAsItemsPanel(listview);
    listview.ItemsSource = new string[] { "1", "2", "3", "4" };
    this.Content = listview;
}


text:
Q: Read data in chunks using sockets I want to send a request using persistant socket connection - to get huge text file from another server, through the API, in chunks.
I can see two layers of dividing the transfer here:
- Sending start and end pointers as parameters of the request, returning only this one part of text in the API, and using one fread to read the whole partial
- Returning the whole request from the API, and using many fread's to read it
What's the proper approach to do this?


text:
Q: Programmatically Edit a Protected microsoft Excel Sheet I want to programmatically change the values of Drop Down Entries in a protected XLS . There are some 1000+ entries with value set to TBD and these entries are not in a sequence . Doing a CTRL-H (replace) throws error that it is password protected sheet . Changing drop-down entry value manually works though .

A: If you know the password,you can unprotect the sheet, chnage the cell and protect it again. You can evem record a macro like this. If you need the same file extension you can run it from a different workbook,alternatively. Again, this can be recorded.


text:
Q: Prevent Exceeding Maximum Recursion Depth I'm trying to make a small script and an efficient way of doing it involves calling a function within itself. However, this gives the message "RuntimeError: maximum recursion depth exceeded while getting the str of an object".
I tried to cause to program to exit before it reached this, but it does not seem to do the job. I'm wondering if there is any way to stop a program after a certain number of runs so this error does not happen. Here is what I tried to do to fix this:
import sys
n = 0
def cycle(b,n):
    total = 0
    for i in str(n):
        for y in i:
         total+=int(y)**b
    n+=1
    print(total)
    if n == 10:
     sys.exit()
    else:
     cycle(b,total)
cycle(2,562)

Thanks.

A: Try passing in a counter and avoid giving confusing variable names:
import sys
def cycle(b,n, counter):
    total = 0
    for i in str(n):
        for y in i:
         total+=int(y)**b
    counter+=1
    print(total)
    if counter == 10:
     sys.exit()
    else:
     cycle(b,total,counter)
cycle(2,562,0)

Run it here.

A: Calling a function recursively might be convenient, but certainly not efficient (at least with the implementation of python you're using, since you get this error).
Yet, what you're trying to do, i.e. limit the recursion depth, is already what happens since you get a runtime error related to the recursion depth.
Why don't you just catch that runtime error at a higher level ?

A: Happy numbers (which is what you're doing there) either end in 1 or end up in the cycle 4, 16, 37, 58, 89, 145, 42, 20, 4, .... So just stop when you reach 1 or 4. Though in general, if your recursion is too deep, you ought to consider an iterative solution.

A: You need to return and use a proper base case:
def cycle(b, n, seen):
    total = 0
    if n == 1 or n in seen:
        return n == 1
    for i in str(n):
        for y in i:
            total += int(y) ** b
    seen.add(n)
    n += 1
    return cycle(b, total, seen)

print(cycle(2, 19,set()))

Output:
In [34]: cycle(2,562,set())
Out[34]: False

In [35]: cycle(2,19,set())
Out[35]: True

In [36]: cycle(2,1,set())
Out[36]: True

In [37]: cycle(2,2,set())
Out[37]: False

In [38]: cycle(2,7,set())
Out[38]: True


text:
Q: what's the difference between a role and a task list and when to use? In ansible, there are include_role and include_tasks modules
what's the difference between them? when to use which of them?
I have a role running on a windows host that requires the variables generated from a linux host. which one should I use in order to run a role in a different host?

A: Include_role: Includes the full role, not only a task file, for example include roles will include: vars, meta, handlers...
Include_tasks: you can call a simple playbook.yml with tasks inside, just a file dont need to be a full role.


text:
Q: Bulk operations NgRX to import a huge list of data actually i try to build an import feature into my angular 6 application based one NgRx.
The source is a CSV-List with about 7.000-10.000 rows which should be imported into my mongo db. The huge amount of data is too large to dispatch this in a single action so I've tried to send a action for each row.
Here is the Effect for this action.
  /**
   * Adds a single transactions, if it ot already exist.
   *
   * @dispatches: ActionOutbankImportSuccess() if the transactions exists or was created
   *              ActionOutbankImportError() if an error  occoured
   */
  @Effect({ dispatch: false })
  addOutbankCSVRow = this.actions$.pipe(
    ofType<ActionOutbankImportAdd>(OutbankImportActionTypes.ADD),
    tap((action) =>
      //  fetch transactions with the given values to  avoid duplicates
      this.transactionsService
        .transactions({
          name: action.payload.transaction.name.replace(/[^\x00-\x7F]/g, ''),
          reason: action.payload.transaction.reason.replace(/[^\x00-\x7F]/g, ''),
          amount: action.payload.transaction.amount,
          date: action.payload.transaction.date,
        })
        .pipe(
          tap(next => console.log(next)),
          tap((existing) => {
            //  if there are no equal transactions ...
            if (existing.length > 0) {
              this.store.dispatch(new ActionOutbankImportSuccess())
            } else {
              //  ... create one
              this.transactionsService
                .createTransaction(action.payload.transaction)
                .pipe(
                  map(() => this.store.dispatch(new ActionOutbankImportSuccess())),
                  catchError(error => {
                    this.store.dispatch(new ActionOutbankImportError({ error: error }));
                    return of();
                  })
                )
            }
          })
        )
    )
  );

Here is the actual method which starts the import:
this.outbankCSVParserService
    .parseCSVFile(files[0])
    .subscribe(rows => {
      this.store.dispatch(
        new ActionOutbankImportStart({ totalCount: rows.length })
      );

      rows.forEach(data =>
        this.store.dispatch(
          new ActionOutbankImportAdd({ transaction: data })
        )
      );
    });

the ActionOutbankImportAdd Actions are triggered but the newly dispatched ActionOutbankImportSuccess | ActionOutbankImportError which i use for progress calculation is only called once at the end.
Whats the best practice for handling such a big import process together with progress indication ?
Thanks for your help


text:
Q: Add time to textarea after click button When i click id=dodaj_godzine_button i want to add current time to id=formularz_wpis_tresc (as string)
I made this but it's doesn't work.
$("#dodaj_godzine_button").click(function(){
        var data = new Date();
        var godzina = data.getHours();
        var minuty = data.getMinutes();
        var czas = godziny;
        czas += ((minuty < 10) ? ":0" : ":");
        $("#formularz_wpis_tresc").html("Godzina: " + czas + "\n");
    });

Where i've made mistake?

A: How about this:
$("#dodaj_godzine_button").click(function(){
    var data = new Date();
    var godzina = data.getHours();
    var minuty = data.getMinutes();
    minuty = ((minuty < 10) ? ":0" + minuty : ":" + minuty);
    $("#formularz_wpis_tresc").html("Godzina: " + godzina + minuty + "\n");
});

A: what's the console log message you got if you take a look at the javascript console? try using
$("#formularz_wpis_tresc").val("Godzina: " + czas + "\n");

see if that works

A: There where two bugs:
1- czas should be equals to "godzina" instead of "godziny".
2- The right way to show the output is:
$("#formularz_wpis_tresc").html("Godzina: " + czas + minuty + "\n");

Sample fiddle: http://jsfiddle.net/s9wxfzcw/

A: Two corrections should make it work:
First, change:
var czas = godziny;

To:
var czas = godzina;

as pointed out by @dfsq in the comments.
Then, change:
$("#formularz_wpis_tresc").html("Godzina: " + czas + "\n");

To:
$("#formularz_wpis_tresc").val("Godzina: " + czas + "\n");

as pointed out by @user2325727, assuming this is the textarea and the clicked element is the the button.


text:
Q: adding extra files to vb.net project I am trying to add some 'supporting' files to my project in VB.NET Express 2012. These files are additional files that are not really part of VB.NET such as RTF files which are templates for reports etc. There is also some text based template files, that will get modified as part of the execution of my program.
What I have done:

*

*I have added these to the project (i.e. they appear in the Solution
Explorer under the project)

*I have set the 'Copy to Output Directory' of each of the files to
"Copy Always" in the properties window.
When I publish the project and re-install it, none of these files are included.
Any help would be appreciated. Thanks in advance.

A: From build action you should select "content"


text:
Q: Calling a phtml file using controller Hi am trying to call a phtml file using controller but the form does not comes within the layout it goes above the page but i want to be within the layout below is my code kindly please take a look
$block = $resultPage->getLayout()
                ->createBlock('Vendor\Module\Block\Rfq')
               ->setTemplate('Vendor_Module::rfq_form.phtml')
               ->toHtml();
             $this->getResponse()->setBody($block);
            $this->_view->renderLayout();
            $this->_view->loadLayout();

update
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Rfq" name="rfq_form" template="Vendor_Module::rfq_form.phtml"  />
        </referenceContainer>
    </body>
</page>

it gives blank when i hit controller

A: Check below code may be it will help.
/**
     * @var Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;

    /**
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory

    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);

    }

    public function execute()
    {

        $resultPage = $this->_resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__(' heading '));

        $block = $resultPage->getLayout()
                ->createBlock('VENDOR\EXTENSION\Block\blockname')
                ->setTemplate('VENDOR_EXTENSION::callingfile.phtml')
                ->toHtml();
        $this->getResponse()->setBody($block);
    }
}

Thanks


text:
Q: SimpleDateFormat bug or misunderstanding pattern and lenient? Having code:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d HH:mm yyyy");

This will work as expected with:
simpleDateFormat.parse("Mar 27 02:02 2016");
simpleDateFormat.parse("Mar 27 03:02 2016");

However             simpleDateFormat.setLenient(false);
will make the parse("Mar 27 02:02 2016") fail.
This makes me totally confused - What I can see, The SDF-format pattern is correct right? So it shouldn't matter if lenient was set. Also, I tried a lot of other random (thousands) datestrings in the same format and it's only  "Mar 27 02:02 2016" datestring that fails -. What is going on here?
Note, locale is sv_SE if that matters and timezone is "Europe/Stockholm" (and useDaylight for created calendar is true).

A: I have tested as below and it worked fine for me
Locale locale = new Locale("sv", "SE");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d HH:mm yyyy", locale);
simpleDateFormat.setLenient(false);
Date pDate = simpleDateFormat.parse("Mar 27 02:02 2016");
//simpleDateFormat.parse("Mar 27 03:02 2016");
System.out.println(pDate);


text:
Q: Cross origin requests are only supported for HTTP but it's not cross-domain I'm using this code to make an AJAX request:
$("#userBarSignup").click(function(){
    $.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
        {/*params*/},
        function(response){
            $("#signup").html("TEST");
            $("#signup").html(response);
        },
        "html");

But from the Google Chrome JavaScript console I keep receiving this error:

XMLHttpRequest cannot load
  file:///C:/xampp/htdocs/webname/resources/templates/signup.php. Cross
  origin requests are only supported for HTTP.

The problem is that the signup.php file is hosted on my local web server that's where all the website is run from so it's not cross-domain.
How can I solve this problem?

A: If you're working on a little front-end project and want to test it locally, you'd typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they're placed in your local directory, you might see warnings like this:
XMLHttpRequest cannot load  file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.
Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through  file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you'd need to mount a webserver to run your project there.
This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you're running several other projects), node.js with  express, a Ruby server, etc. or simply modifying your browser settings.
However there's a simpler and lightweight solution for the lazy ones. You can use Python's SimpleHTTPServer. It comes already bundled with python so you don't need to install or configure anything at all!
So cd to your project directory, for instance
1
cd /home/erick/mysuperproject
and then simply use
1
python -m SimpleHTTPServer
And that's it, you'll see this message in your terminal
1
Serving HTTP on 0.0.0.0 port 8000 ...
So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I'm in a rush to test a new library or work out a new idea.
EDIT:
In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:
python -m http.server 8000

A: You need to actually run a webserver, and make the get request to a URI on that server, rather than making the get request to a file; e.g. change the line:
    $.get("C:/xampp/htdocs/webname/resources/templates/signup.php",

to read something like:
    $.get("http://localhost/resources/templates/signup.php",

and the initial request page needs to be made over http as well.

A: If you have nodejs installed, you can download and install the server using command line:
npm install -g http-server

Change directories to the directory where you want to serve files from:
$ cd ~/projects/angular/current_project

Run the server:
$ http-server

which will produce the message Starting up http-server, serving on:
Available on:
  http://your_ip:8080 and
  http://127.0.0.1:8080
That allows you to use urls in your browser like

http://your_ip:8080/index.html

A: I've had luck starting chrome with the following switch:
--allow-file-access-from-files

On os x try (re-type the dashes if you copy paste):
open -a 'Google Chrome' --args -allow-file-access-from-files

On other *nix run (not tested)
 google-chrome  --allow-file-access-from-files

or on windows edit the properties of the chrome shortcut and add the switch, e.g.
 C:\ ... \Application\chrome.exe --allow-file-access-from-files

to the end of the "target" path

A: I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.

*

*Install express
npm install express

*Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

*Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');

// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));

app.listen(8000);
console.log('Listening on port 8000');

*After you've saved server.js, you can run the server using:
node server.js

*Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load

A: It works best this way. Make sure that both files are on the server. When calling the html page, make use of the web address like: http:://localhost/myhtmlfile.html, and not, C::///users/myhtmlfile.html. Make usre as well that the url passed to the json is a web address as denoted below:
$(function(){
                $('#typeahead').typeahead({
                    source: function(query, process){
                        $.ajax({
                            url: 'http://localhost:2222/bootstrap/source.php',
                            type: 'POST',
                            data: 'query=' +query,
                            dataType: 'JSON',
                            async: true,
                            success: function(data){
                                process(data);
                            }
                        });
                    }
                });
            });

A: REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files

*

*change chromeLocation path with yours.

*save above as .bat file.

*drag drop you file on the batch file you created. (chrome does give restore pages
option though so if you have pages open just hit restore and it will work).

A: You can also start a server without python using php interpreter.
E.g:
cd /your/path/to/website/root
php -S localhost:8000

This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).

A: For all python users:
Simply go to your destination folder in the terminal.
cd projectFoder

then start HTTP server
For Python3+:
python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...
go to your link: http://0.0.0.0:8000/
Enjoy :)


text:
Q: Equation incidence diagram in Dymola There is a new feature of showing the equation incidence diagram in Dymola 2021X, but there are more nonlinear equation systems in the incidence diagram than in the translation log, so I am not sure how to compare these two statistics data.
How should interpret this information?

--------------------------------------------------------------------------------------------------------------------------------
update at 12.23.2020:
here is the result using Dymola 2021x - Hot fix-1

A: Dymola labels block as "Non-linear" when it cannot handle them, you will notice that these additional block are a bit odd as it says "Equation block: Calculations"; and not a non-linear tag.

A: There is now a "hotfix" version of Dymola 2021x that fixes this visualization issue.