text:
Q: Composite primary key as shadow property in many-to-many relation I'm using .NET Core end Entity Framework core to build many-to-many relation between two entities. I've built join entity to fullfil the relation and based primary key on shadow properties like this :
Entity User :
public class User
{
    [Key]
    public int IDUser { get; set; }
    [Required]
    public string Forename { get; set; }

    public List<UserGroup> UsersGroups { get; set; }
}

Entity Group :
public class Group
{
    [Key]
    public int IDGroup { get; set; }
    [Required]
    public string GroupName { get; set; }

    public List<UserGroup> UsersGroups { get; set; }
}

Entity UserGroup :
public class UserGroup
{
    public Group Group { get; set; }
    public User User { get; set; }
}

DBcontext class :
public class DBContext : DbContext
{
    public DBContext(DbContextOptions<DBContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // shadow property - primary/foreign key
        modelBuilder.Entity<UserGroup>()
            .Property<int>("IDUser");

        // shadow property - primary/foreign key
        modelBuilder.Entity<UserGroup>()
            .Property<int>("IDGroup");

        // composite primary key based on shadow properties
        modelBuilder.Entity<UserGroup>()
            .HasKey( new string[]{ "IDUser", "IDGroup" });

        modelBuilder.Entity<UserGroup>()
            .HasOne(ug => ug.Group)
            .WithMany(g => g.UsersGroups)
            .HasForeignKey(???); //what to do here ?

        modelBuilder.Entity<UserGroup>()
            .HasOne(ug => ug.User)
            .WithMany(u => u.UsersGroups)
            .HasForeignKey(???); // what to do here ?

        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Group> Groups { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<UserGroup> UserGroups { get; set; }
}

Now. How can I properly establish Foreign Key on UserGroup entity based on my shadow composite primary key ? I would like this shadow primary key to be foreign key simultaneously. I don't know how to refer to this shadow primary key now in order to make foreign key. I marked where I don't know what to do with question markes.

A: .HasForeignKey() declares Foreign Key Properties on your entity.
If you don't want Foreign Key Properties on your linking Entity (and you should have them), just omit the .HasForeignKey declaration and EF will use map the FK columns by convention.
eg
   protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // shadow property - primary/foreign key
        modelBuilder.Entity<UserGroup>()
            .Property<int>("IDUser");

        // shadow property - primary/foreign key
        modelBuilder.Entity<UserGroup>()
            .Property<int>("IDGroup");

        // composite primary key based on shadow properties
        modelBuilder.Entity<UserGroup>()
            .HasKey(new string[] { "IDUser", "IDGroup" });

        modelBuilder.Entity<UserGroup>()
            .HasOne(ug => ug.Group)
            .WithMany(g => g.UsersGroups);
        //.HasForeignKey(???); //what to do here ?

        modelBuilder.Entity<UserGroup>()
            .HasOne(ug => ug.User)
            .WithMany(u => u.UsersGroups);
            //.HasForeignKey(???); // what to do here ?

        base.OnModelCreating(modelBuilder);
    }

Generates
CREATE TABLE [UserGroups] (
    [IDUser] int NOT NULL,
    [IDGroup] int NOT NULL,
    CONSTRAINT [PK_UserGroups] PRIMARY KEY ([IDUser], [IDGroup]),
    CONSTRAINT [FK_UserGroups_Groups_IDGroup] FOREIGN KEY ([IDGroup]) REFERENCES [Groups] ([IDGroup]) ON DELETE CASCADE,
    CONSTRAINT [FK_UserGroups_Users_IDUser] FOREIGN KEY ([IDUser]) REFERENCES [Users] ([IDUser]) ON DELETE CASCADE
);

A: You are trying to create a many-to-many join table without defining any scalar properties and you are utilizing shadow property to configure the join table. For EF fluent API, where you have to refer to a shadow property you need to use string based methods. Due to lack of backing CLR property lambda expression doesn't work.
In your case, "what to do here" part is just use the string name of the property.
e.g.
modelBuilder.Entity<UserGroup>()
    .HasOne(ug => ug.Group)
    .WithMany(g => g.UsersGroups)
    .HasForeignKey("IDGroup"); //what to do here ?

Same for the other relationship. This is general mechanism when you want to configure a shadow property as your foreign key property. Furthermore, configuring the shadow property in HasForeignKey does not require you to define the shadow property in advance, since EF can infer the type based on the properties on principal side of relationship. Though for HasKey you still need to declare the shadow properties since EF has no knowledge of types. (As you have done in your example)
EF Core also has convention to figure out FK property. One of the convention is to use property as FK if it has same name as the principal property. In your special case as above, since your principal side primary key property is named as IDGroup which is same as foreign key you are trying to configure, EF will use that by convention automatically. That means you can ignore configuring your relationship (as @David suggested). Also since EF discovers relationships based on navigations you can remove following piece of code fully from your application and it will create the same model.
modelBuilder.Entity<UserGroup>()
    .HasOne(ug => ug.Group)
    .WithMany(g => g.UsersGroups);
//.HasForeignKey(???); //what to do here ?

modelBuilder.Entity<UserGroup>()
    .HasOne(ug => ug.User)
    .WithMany(u => u.UsersGroups);
    //.HasForeignKey(???); // what to do here ?


text:
Q: How to set up a web e-payment system(Donation System )? The current website is running only with HTML pages.
My idea to set up a web epayment system (Donation System) is that I would like to build a web server with Xmapp. I am going to build a db stored the payment info . The HTML form passes the info to the db and the field of payment amount passes to the payment website . After the user clicks the submit button , it redirects to the epayment websites .The users end the process with the epayment websites. And it auto-generate an email to the user.
Is this idea possible ?
Update
1.Any more convenient ways to set up the db with purely HTML?
2.Should I register the shop ac in the epayment websites ?

A: Smith is still right but it looks like you are going to have to implement a basic CRUD application with php, you 'cannot' implement this without a programming language ( i.e. with only html).
HERE IS A SIMPLE TUTORIAL:
https://www.startutorial.com/articles/view/php-crud-tutorial-part-1
There are apis for payment integration with php.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can use vuejs in laravel for web-page that need SEO support? I am bit confused to use PHP laravel vuejs template for my dynamic website. Even JavaScript framework is not SEO friendly and how can use this in laravel for an dynamic website that need SEO.
I got reference from google and stack overflow questions that need to use an API based architecture.  I don`t want to create it as an API based laravel and NUXTJS front end.
How can use vuejs search engine optimization friendly in laravel ?


text:
Q: Why does this stored procedure work with one query but not another? I modified a stored procedure i found to send have a list of of values as a parameter is SSRS. The user simply enters values one after another seperated by commas "2444,2445,2446,...". The stored procedure works perfectly as expected with one of my queries, but when i changed the query that it uses but not the logic of the stored procedure it no longer works... Seems strange as the logic of the stored procedure has nothing to do with the query itself.
Here is the working Stored procedure
GO
/****** Object:  StoredProcedure [dbo].[MULTI_VALUED_USER_INPUT_PARAMETER]    Script Date: 4/28/2017 10:22:55 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*CREATING A STORED PROCEDURE, WHICH HAS ONE INPUT PARAMETER*/
ALTER PROCEDURE [dbo].[MULTI_VALUED_USER_INPUT_PARAMETER](@DIESECTION VARCHAR(MAX))
AS
BEGIN
  /*CHECKING IF TABLE EXISTS IN THE DATABASE*/
  IF OBJECT_ID('TEMP', 'U') IS NOT NULL
    /*IF TABLE EXISTS THEN DROPPING AND RECREATING TABLE*/
    DROP TABLE TEMP

  CREATE TABLE TEMP (DIESECTION VARCHAR(MAX))

  /*INSERTING EACH COMMA SEPERATED VALUE INTO TEMP TABLE*/
  WHILE CHARINDEX(',',@DIESECTION)<>0
  BEGIN
    INSERT INTO TEMP VALUES((SELECT LEFT(@DIESECTION, CHARINDEX(',',@DIESECTION)-1)))
    SET @DIESECTION=(SELECT RIGHT(@DIESECTION,LEN(@DIESECTION)-CHARINDEX(',',@DIESECTION)))
  END

  /*MODIFY QUERY TO FIT YOUR NEEDS!*/
  SELECT DISTINCT TOP 100000 p.id AS DIE_SECTION,SUM(r.CALC_QTY) AS GROSS_KG, COUNT(WO.BASE_ID) AS NUMBER_OF_TIMES_ORDERED, MAX(WO.CREATE_DATE) AS RECENT_ORDER_DATE,
    CASE
        WHEN ISNUMERIC(P.USER_3) = 1
        THEN Convert(varchar(50), CONVERT(decimal(14,3), P.USER_3))
    END AS KG_M

  FROM [DAJCOR].[dbo].[WORK_ORDER] wo JOIN REQUIREMENT R ON R.WORKORDER_BASE_ID = wo.BASE_ID JOIN PART P ON P.ID = WO.DRAWING_ID
  WHERE P.USER_3 IS NOT NULL
  AND r.PART_ID = WO.DRAWING_ID
  AND WO.BASE_ID <> WO.PART_ID
  AND P.ID IN(SELECT DIESECTION FROM TEMP)
  AND (WO.CREATE_DATE BETWEEN convert(datetime, '2009-01-01') AND GETDATE())
  GROUP BY P.ID, P.USER_3 ORDER BY COUNT(WO.BASE_ID)

  /*DROPPING THE TEMP TABLE*/
  DROP TABLE TEMP
END

And this second one uses the exact same stored procedure with a slightly more complex query. But the store procedure should only be affecting the first argument of the WHERE clause.
GO

/****** Object:  StoredProcedure [dbo].[MULTI_VALUED_USER_INPUT_PARAMETER]    Script Date: 4/28/2017 9:49:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

GO
/*CREATING A STORED PROCEDURE, WHICH HAS ONE INPUT PARAMETER*/
ALTER PROCEDURE [dbo].[MULTI_VALUED_USER_INPUT_PARAMETER_NET_KG](@DIESECTION VARCHAR(MAX))
AS
BEGIN

  /*CHECKING IF TABLE EXISTS IN THE DATABASE*/
  IF OBJECT_ID('TEMP', 'U') IS NOT NULL
    /*IF TABLE EXISTS THEN DROPPING AND RECREATING TABLE*/
    DROP TABLE TEMP

  CREATE TABLE TEMP (DIESECTION VARCHAR(MAX))

  /*INSERTING EACH COMMA SEPERATED VALUE INTO TEMP TABLE*/
  WHILE CHARINDEX(',',@DIESECTION)<>0
  BEGIN
    INSERT INTO TEMP VALUES((SELECT LEFT(@DIESECTION, CHARINDEX(',',@DIESECTION)-1)))
    SET @DIESECTION=(SELECT RIGHT(@DIESECTION,LEN(@DIESECTION)-CHARINDEX(',',@DIESECTION)))
  END

  /*MODIFY QUERY TO FIT YOUR NEEDS!*/
 SELECT DISTINCT LT.WORKORDER_BASE_ID,WO.DRAWING_ID,P.WEIGHT AS SHIPPING_WEIGHT,
    CASE
    WHEN R.SUBORD_WO_SUB_ID >= 0
    THEN P.WEIGHT/R.QTY_PER
    ELSE P.WEIGHT
    END AS NET_WEIGHT
,R.PART_ID,LT.GOOD_QTY,
LT.GOOD_QTY * CASE
    WHEN R.SUBORD_WO_SUB_ID >= 0
    THEN P.WEIGHT/R.QTY_PER
    ELSE P.WEIGHT
    END AS NET_KG,SUM(IT.QTY) AS GROSS_KG,LT.TRANSACTION_ID AS LT_TRANS,IT.TRANSACTION_DATE AS IT_DATE,LT.TRANSACTION_DATE AS LT_DATE
,LT.EMPLOYEE_ID,LT.RESOURCE_ID,LT.HOURS_WORKED,(LT.GOOD_QTY * CASE
    WHEN R.SUBORD_WO_SUB_ID >= 0
    THEN P.WEIGHT/R.QTY_PER
    ELSE P.WEIGHT
    END/LT.HOURS_WORKED) AS NET_KG_HR
FROM LABOR_TICKET LT JOIN INVENTORY_TRANS IT ON IT.WORKORDER_BASE_ID = LT.WORKORDER_BASE_ID LEFT JOIN WORK_ORDER WO ON WO.BASE_ID = LT.WORKORDER_BASE_ID LEFT JOIN PART P ON P.ID = WO.PART_ID
    LEFT JOIN REQUIREMENT R ON R.WORKORDER_BASE_ID = LT.WORKORDER_BASE_ID  AND R.WORKORDER_SUB_ID = WO.SUB_ID
WHERE WO.DRAWING_ID IN (SELECT DIESECTION FROM TEMP) AND LT.GOOD_QTY > 0 AND (LT.TRANSACTION_DATE BETWEEN '04-01-2017' AND '04-10-2017') AND IT.WAREHOUSE_ID <> 'COSTCODE' AND IT.PART_ID = WO.DRAWING_ID
    AND P.WEIGHT IS NOT NULL AND LT.RESOURCE_ID LIKE 'EP%' AND (R.PART_ID IN ('25023', '25024', '25025', '25026', '25027', '25028') OR R.PART_ID IS NULL) AND R.QTY_PER <> 0
GROUP BY LT.WORKORDER_BASE_ID,WO.DRAWING_ID,P.WEIGHT,
    CASE
    WHEN R.SUBORD_WO_SUB_ID >= 0
    THEN P.WEIGHT/R.QTY_PER
    ELSE P.WEIGHT
    END,R.PART_ID,LT.GOOD_QTY, LT.GOOD_QTY * CASE
    WHEN R.SUBORD_WO_SUB_ID >= 0
    THEN P.WEIGHT/R.QTY_PER
    ELSE P.WEIGHT
    END,LT.TRANSACTION_DATE,IT.TRANSACTION_DATE,LT.TRANSACTION_ID,LT.EMPLOYEE_ID,LT.RESOURCE_ID,LT.HOURS_WORKED
ORDER BY WO.DRAWING_ID,LT.WORKORDER_BASE_ID

  /*DROPPING THE TEMP TABLE*/
  DROP TABLE TEMP
END

The problem is that when i try and enter values for example "23703" then nothing appears, but if i add a comma at the end "23703," then it works. Where the first example works normally for the first query but only the second example works for the 2nd query. Another example would be if i had multiple values "1,2,3" only 1 and 2 would appear because they are followed by a comma, but the 3 value would not because it does not have a comma following it.

A: The problem in your code most likely has to do with this loop: WHILE CHARINDEX(',',@DIESECTION)<>0. Since without a comma, it will not do anything.
However the real problem of splitting delimited strings can be solved with some other much faster solutions.
One example is a table valued function by Jeff Moden:
create function [dbo].[delimitedsplit8K] (
      @pstring varchar(8000)
    , @pdelimiter char(1)
  )
returns table with schemabinding as
 return
  with e1(N) as (
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all select 1
  )
  , e2(N) as (select 1 from e1 a, e1 b)
  , e4(N) as (select 1 from e2 a, e2 b)
  , ctetally(N) as (
    select top (isnull(datalength(@pstring),0))
      row_number() over (order by (select null)) from e4
  )
  , ctestart(N1) as (
    select 1 union all
    select t.N+1 from ctetally t where substring(@pstring,t.N,1) = @pdelimiter
  )
  , ctelen(N1,L1) as (
    select s.N1,
      isnull(nullif(charindex(@pdelimiter,@pstring,s.N1),0)-s.N1,8000)
    from ctestart s
  )
 select itemnumber = row_number() over(order by l.N1)
      , item       = substring(@pstring, l.N1, l.L1)
   from ctelen l
;
go

Which can be used like so:
declare @diesection varchar(8000) = '1,2,3';
select s.ItemNumber, s.Item
from [dbo].[delimitedsplit8K](@diesection,',') s

rextester demo: http://rextester.com/XJSQUS89642
returns:
+------------+------+
| ItemNumber | Item |
+------------+------+
|          1 |    1 |
|          2 |    2 |
|          3 |    3 |
+------------+------+

splitting strings reference:

*

*Tally OH! An Improved SQL 8K "CSV Splitter" Function - Jeff Moden

*Split strings the right way – or the next best way - Aaron Bertrand

*Splitting Strings : A Follow-Up - Aaron Bertrand

*Splitting Strings : Now with less T-SQL - Aaron Bertrand

*string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand

Since this is for reporting, and you are doing things where parameters may or may not be populated, you may find these articles helpful as well:
Catch-all queries reference:

*

*Parameter Sniffing, Embedding, and the RECOMPILE Options - Paul White

*Dynamic Search Conditions - Erland Sommarskog

*Catch-all queries - Gail Shaw

*An Updated "Kitchen Sink" Example - Aaron Bertand


text:
Q: Query syntax for JSON lookup data with var ( not condition ) I'm trying to filter some JSON data, but I would like the lookup to be based on selection of a drop down.  However, I just can't get the syntax correct when trying to do this.  Currently the following works in my code, great:
var as = $(json).filter(function (i, n) {
    return (n.FIELD1 === "Yes"
});

However, what I would like to do is replace the FIELD1 value with a var from the drop down.  Something like this following, which is not working:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
    return (n.dropdownResult === "Yes"
});

I'm trying to get the var to become the field name after the n. but it's not working.
Thanks for your time.  Sorry if this has been answered many times before and is obvious to you.

A: To use a variable value as the key of an object you should use bracket notation, like this:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
    return n[dropdownResult] === "Yes";
});

I removed the extraneous ( you left in your code - I presume this was just a typo as it would have created a syntax error and stopped your code from working at all.
Also note that it's much better practice to use a boolean value over a string 'Yes'/'No'


text:
Q: Best location for a reusable helper method in Rails 2.2 I plan to create a method that would format a Time in a specific way (specialized formatting in Russian).
I would like to reuse this helper method in multiple models, controllers and possibly views. Also I would like to call this helper method on instance of Time class like follows:
t=Time.now
t.my_super_shiny_helper

Question: where should I implement this helper? (module or class, where in application directory structure?). After creating it, how should I call it?
I'm new to ruby/rails and struggle to get this working in a proper way.
Thank you.

A: I would add a file to lib/time_extensions.rb
class Time
  def my_shiny_helper
    ...
  end
end

And in an initializer file in config/intitializers
require 'time_extensions'

If the extensions grow a bit and are something you want to reuse think of putting it into a plugin for easy inclusion.  Or even a gem.

A: If you just want to format a time, a clean approach in Rails (as given in Agile Web Development) is to extend the formats used in the to_s method:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :russian => "%A %d %B %Y"
)

Time.now.to_s(:russian) #=> "Tuesday 17 February 2009"

Include the first bit in either config/environment.rb or in a file in config/initializers.


text:
Q: Do zsh aliases lower terminal performance? I really make use of aliases and I've started to create some function aliases which are made of only one if..else case. For instance, I have the following alias to start my json-server:
jsp() {
        if [[ -z $2 ]]; then
                json-server --watch data/db.json --port $1
        else
                json-server --watch $1 --port $2
        fi
}

Does having a lot of aliases effect the terminal performance? Can this if..else type of aliases be improved in some kind of way (e.g., making them single line)?

A: Having many aliases and small functions will not have any measurable runtime performance impact.
Having many large functions will impact the time it take to start an interactive shell. The shell has to parse all the code. You aren't likely to notice it unless your init files are on a slow network filesystem. If this is a problem (and once again, don't even worry about it unless it's actually a problem), make sure your large functions are autoloaded and byte-compiled (for zsh), or split them out into separate scripts (for any shell, and that's usually a good idea for any large function anyway, so that it can be used on its own without first loading an interactive shell).
As a point of comparison, if you're using bash's smart completion, it loads about 60k lines of code when bash starts. So to make a visible difference in the startup time, you'd have to have about that much code of your own.


text:
Q: Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call on ASP.NET core 2.2 I'm using aspnetboilerplate solution developed with ASP.NET core 2.2 . The backend is deployed on azure and it uses the SQL server provided.
Sometimes, when the backend has a lot of requests to handle, it logs this exception:

Mvc.ExceptionHandling.AbpExceptionFilter - An exception has been
raised that is likely due to a transient failure. Consider enabling
transient error resiliency by adding 'EnableRetryOnFailure()' to the
'UseSqlServer' call. System.InvalidOperationException: An exception
has been raised that is likely due to a transient failure. Consider
enabling transient error resiliency by adding 'EnableRetryOnFailure()'
to the 'UseSqlServer' call. ---> System.Data.SqlClient.SqlException: A
transport-level error has occurred when receiving results from the
serv

I tried to solve this problem adding this code to my Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(
                options => options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName))
            ).AddJsonOptions(
            // To fix OldContract in Contract entity (self-referencing loop)

        services.AddDbContext<ManagerDbContext>(options =>
        {
            options.UseSqlServer(_appConfiguration["ConnectionStrings:Default"],
                sqlServerOptionsAction: builder =>
                {
                    builder.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(30),
                        errorNumbersToAdd: null);
                });
        });

    }

But the problem is not solved.

A: you will have to add your error code in the list errorNumbersToAdd:
options.EnableRetryOnFailure(
        maxRetryCount: 3,
        maxRetryDelay: TimeSpan.FromSeconds(10),
        errorNumbersToAdd: new List<int> { Add your code here});


text:
Q: What is the name of matrices of this form? Consider the upper traingular $N \times N$ matrix
$$\left(\begin{array}{cccccccc}
0 & b_{1} & \dots & b_{q} & 0 & 0 & \dots & 0\\
\vdots & 0 & b_{1} & \dots & b_{q} & 0 & \dots & 0\\
\vdots &  & \ddots &  &  &  &  & \vdots\\
\vdots &  &  & 0 & b_{1} & \dots & b_{q} & 0\\
\vdots &  &  &  & 0 & b_{1} & \dots & b_{q}\\
\vdots &  &  &  &  & 0 & \dots & 0\\
\vdots &  &  &  &  &  & \ddots & \vdots\\
0 & \dots & \dots & \dots & \dots & \dots & \dots & 0
\end{array}\right)$$
Is there a name for matrices of this form?

A: The upper block has several properties that you can combine in a name:

strictly upper triangular, Toeplitz, band matrix with a right/upper bandwidth $q$.

However, if you want to describe the whole matrix, you lose the "Toeplitz" part. You might say

These matrices are of form
$$\begin{bmatrix} X \\ 0 \end{bmatrix}$$
where $0$ is a zero matrix of order $q \times n$, and $X$ is strictly upper triangular, Toeplitz, band matrix of order $(n-q) \times q$ with a right/upper bandwidth $q$.

However, I believe a formal, nameless description is far better.

A: There is, so far as I know, no standard name for this type of matrix. However, it is composed of the first $q$ superdiagonals of the matrix, so "q-superdiagonal matrix" might be a sensible thing to call them.

A: Strictly (zeros on the diagonal) upper triangular (obvious) banded (has a limited band) Toeplitz (is a diagonal-constant) matrix.
You can call it a StrUTriBaToM :-)


text:
Q: Storyboard UITable(View?) with Sprite Kit I just created a tiny little game with sprite kit. Works flawless!
Now I wanted to add a simple menu button (SKLabelNode*) which presents a UITable(View?).
To design the tableViewCells I created a UIViewController in the storyboard and added a UITable.

Now I need to display this table from my SKSzene. How do I achieve this?
And if that's possible, how do I call methods of my SKScene by touching a tableViewCell?
This displays the tableView but without content...
-(void)showTableShop{
TableViewController *table = [[TableViewController alloc]init];
[self.view addSubview:table.view];
}

I appreciate any help!


text:
Q: sticky menu div doensn't stay centered when stuck I have a menu bar in a
 that should stick to the top of the browser when scrolled down.
This works, using JQuery
var stickyHeaderTop = $('#stickyheader').offset().top;

$(window).scroll(function()
{
  if( $(window).scrollTop() > stickyHeaderTop ) {
     $('#stickyheader').css({position: 'fixed', top: '0px'});
     $('#stickyalias').css('display', 'block')
  }
  else {
     $('#stickyheader').css({position: 'static', top: '0px'});
     $('#stickyalias').css('display', 'none');
  }
});

However, the
 is centered using CSS: margin-right: auto; margin-left: auto; and somehow this breaks when the menu is stuck?
See JSFiddle

A: I strongly recommend you use classes since will make code clear and you can customize it faster.
DEMO
HTML

BAR

JS
            if( $(window).scrollTop() > stickyHeaderTop )
            {
                $('#stickyheader').addClass('fixed');
                $('#stickyalias').removeClass('hidden');
            }
            else
            {
                $('#stickyheader').removeClass('fixed');
                $('#stickyalias').addClass('hidden');
            }

CSS
#stickyheader {
  width: 100%;
}
#stickyheader.fixed {
  position: fixed;
  top: 0;
  left: 8px;/*body margin*/
  width: calc(100% - 16px);
}
#stickyalias {
  display: block;
  height: 60px;
}
#stickyalias.hidden {
  display: none;
}

A: This is happening because you are setting to position fixed and top: 0 (by default left: 0 is added also). Add left: 50%; margin-left: -100px and it will work.
Updated fiddle

A: you can use the method with positive coordonates and negative margin.
http://jsfiddle.net/p77dK/2/
update : to restore margin once scrolling back down http://jsfiddle.net/p77dK/7/
these are communly used to center absolute elements.
var stickyHeaderTop = $('#stickyheader').offset().top;

$(window).scroll(function()
        {
                if( $(window).scrollTop() > stickyHeaderTop )
                {
                    $('#stickyheader').css({position: 'fixed', top: '0px', margin: '0 -100px',left:'50%'});
                        $('#stickyalias').css('display', 'block');
                        // also set content top padding under menu
                }
                else
                {
                        $('#stickyheader').css({position: 'static', top: '0px',  margin: '0 auto'});
                        $('#stickyalias').css('display', 'none');
                }
        });

other way to do it.
fixed container can as well be used as a wrapper and show a scrollbar if needed . bar is then in as in a regular container and can be centered with margin:auto;
http://jsfiddle.net/p77dK/6/


text:
Q: hibernate criteria group-wise maximum I am trying to achieve the group wise maximum for a date, but even with the log showing the correct query, i get the exception:
java.lang.ClassCastException : java.lang.String cannot be cast to java.util.Date

This the smallest portion of code generating the cast exception:
DetachedCriteria maxLogin= DetachedCriteria.forClass(UsersSessions.class,"du");
maxLogin.setProjection(Projections.projectionList()
    .add(Projections.max("du.login").as("login")));

Criteria crit = session.createCriteria(UsersSessions.class,"u");
crit.add(Subqueries.eq("u.login", maxLogin));

This is the sql equivalent of what i am trying to do with my full code:
SELECT *
FROM   UsersSessions u
WHERE  u.login=(SELECT MAX(du.login)
              FROM UsersSessions ud
              WHERE ud.fkUser = u.fkUser);

This would be even better:
SELECT *
FROM (SELECT *
FROM UsersSessions
[WHERE conditions]
ORDER BY login  DESC) u
GROUP BY u.fkUser

But idk how to do a subquery in the from part like that...
Edit: OK, just tried casting maxLogin to Date but i am getting same exception.
Edit: i just tried this
Criteria crit = session.createCriteria(UsersSessions.class,"u");
crit.setProjection(Projections.projectionList()
        .add(Projections.max("u.login").as("login")));
Timestamp max=(Timestamp)crit.uniqueResult();

And it worked.
Leaving me with even less places to look at... cero at the moment.
Any ideas of whats causing the cast excepton?

A: Are you sure crit.add(Subqueries.eq("u.login", maxLogin)); maxLogin is type of Date? if not, try convert it to java.lang.Date type.

A: Got it working...
So apparently, the eq function takes the string as a value of comparition.
Subqueries.eq("u.login", maxLogin);

This is the one that compares a propertie against the subquery:
Subqueries.propertiesEq(new String[]{"u.login"},maxValidacion);


text:
Q: jQuery - how to make a fixed div scroll horizontally after scrolling vertically This is kind of a variation of the following, but a little different: How do I get a fixed position div to scroll horizontally with the content? Using jQuery
Here is my variation: http://jsfiddle.net/Bdwc4/
Basically, I would like to be able to see that "x" on the far right of the div, and in order to do so, the div must be absolute.  But at the same time, I need the div to be fixed when scrolling vertically.  In other words, you should always be able to see the "x" in that fixed position, while scrolling vertically or horizontally.  It kind of does what I want it to do, but only when you're at the top of the window.  I'd like to be able to scroll horizontally, regardless of where you scroll vertically.
If you choose not to use jsfiddle above, here is the code I'm using:

x

    Enter a very long string of text

After you enter in the code, shrink the browser window horizontally and vertically until the "x" in the red box is out of view, which will force you to scroll horizontally to see it, and while you scroll vertically, the red box should be in a fixed position.

A: Looks like this is what you're after: http://css-tricks.com/scrollfollow-sidebar/

A: Look this url
http://ryanfait.com/position-fixed-ie6/


text:
Q: Using BigQuery in Google Apps Scripts to connect to Google Spreadsheet I've enabled BigQuery in API console and in my GAS app and I tried using the example from this thread: Accessing BigQuery with Google Spreadsheet
I got the Project ID but I don't know how to connect to my Google Spreadsheet.
How do you use BigQuery in GAS to connect to Google Spreadsheet anyway?  Do you input the Spreadsheet as a dataset in the API console? How is that done?
The V2 documentation has several tutorials and samples but none about connecting to a Google Spreadsheet using GAS.
Thanks.

A: You can call Google BigQuery from Spreadsheet using GAS. But you can't read values in Google Spreadsheet from Google BigQuery Queries.
Google BigQuery is separate product where you have to upload the data into Google BigQuery to query. Google BigQuery wont read the Spreadsheet automatically. You got to export the Spreasheet as CSV first and upload into BigQuery before you can query the data.
What you can do is you can use the Spreadsheet as a Front end to BigQuery , for example users can populate some fields in the spreadsheet and GAS can use that values and query the BigQuery to get results and populate the spreadsheet and use visualization gadgets like charts in spreadsheet to view the data.


text:
Q: github jenkins webhook expecting a jenkins job that has been deleted I have set up Github with a Jenkins (GitHub plugin) integration/service and webhooks (one for push only, one for specified events including comments). I am replacing an old Jenkins "project" (aka job) with a new one that is programmatically generated. For a period of time we had both Jenkins jobs configured to listen for Github events in this repo, but I deleted the old Jenkins job and now there is only one. However, Github is still looking for a report from the old job and is also marking it "REQUIRED". (Nobody can figure out what causes it to consider the one job required and not the other one, either.)
How do I make Github stop looking for the deleted Jenkins job?
Here's a screencap of part of the github page:

A: Repository settings -> Branches -> Protected branches -> select a branch. Then check new Jenkins job, uncheck old one:


text:
Q: how to show hand cursor on a button which is inside a div? I have a button which is inside div

.calculateActivityBtn {
    float: left;
    margin-right: 1px;
    cursor: pointer;
}

.pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
    cursor: pointer
}

        <div class="btn btn-primary" id="getFilesButton" title="<%= language['UI.reports.tooltip.getFilesButton'] %>">button text

when i hover on the div it gives me a hand cursor in chrome, but in firefox it does not show me a hand cursor till the pointer reaches the button icon .
I have tried changing z-index of the two div's and changing cursor:pointer in css.
I want a hand cursor when hovered on the div also in firefox.

A: Just use Padding instead of margin in pagination div..
check updated snippet...

.calculateActivityBtn {
    float: left;
    margin-right: 1px;
    cursor: pointer;
}

.pagination {
    display: inline-block;
    padding-left: 0;
    padding: 20px 0;
    border-radius: 4px;
    cursor: pointer;
    background: red;
}

        <div class="btn btn-primary" id="getFilesButton" title="<%= language['UI.reports.tooltip.getFilesButton'] %>">
          button text

A: use this css
.pagination:hover #getFilesButton{
cursor: pointer;
}

and be sure to support any specific browser for
browser support about cursor you can check it here
Caniuse cursor supported
Hope, it will work. let me know if you need more help


text:
Q: control array, links by role in header, laravel-admin I use https://laravel-admin.org/docs/en/README on my site.
I have a general header in the admin panel, which displays all the sections that can be edited, here is the code:
<?php foreach(Admin::menuLinks() as $link) { ?>
<?php if (in_array($link['uri'], ['users', 'posts', 'comments'])) {?>
    <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
        <?= admin_trans ($link['title']) ?>

<?php } ?>
<?php } ?>

So, I have 3 partitions. Each section will have its own admin, who will have a corresponding role. Now all admins with roles see all links in the header, but I need to hide them and make sure that the admin sees only the link to which he has a role with rights. How can I do such a check in the header? To display these links depending on the user's role.
I did it this way:
<?php foreach(Admin::menuLinks() as $link) { ?>
<?php if (Admin::user()->isRole('administrator')) {?>
<?php if (in_array($link['uri'], ['users', 'posts', 'comments'])) {?>
    <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
        <?= admin_trans ($link['title']) ?>

<?php } ?>
<?php } ?>

<?php if (Admin::user()->isRole('post-admin')) {?>
<?php if (in_array($link['uri'], ['posts'])) {?>
    <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
        <?= admin_trans ($link['title']) ?>

<?php } ?>
<?php } ?>

<?php if (Admin::user()->isRole('comment-admin')) {?>
<?php if (in_array($link['uri'], ['comments'])) {?>
    <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
        <?= admin_trans ($link['title']) ?>

<?php } ?>
<?php } ?>
<?php } ?>

It works, but I ended up with too much repetitive code. Is it possible to do it somehow simpler, to control all the roles in the array?
Something like this:
<?php foreach(Admin::menuLinks() as $link) { ?>
<?php if (in_array($link['uri'],
     if (Admin::user()->isRole('administrator')) {
          ['users', 'posts', 'comments']
     }

    else if (Admin::user()->isRole('post-admin')) {
          ['posts']
     }
)) {?>
    <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
        <?= admin_trans ($link['title']) ?>

<?php } ?>

Or:
<?php if (in_array($link['uri'],
Admin::user()->isRole('administrator') ? ['users', 'posts', 'comments'] :
Admin::user()->isRole('post-admin') ? ['posts'] : '')) {?>

But both options don't work for me..

A: You have multiple possible solution. One would be to make a helper adminHasAccess($link['uri']) and use it elegantly in your blade.
function adminHasAccess($uri)
{
    switch($uri) {
        case 'users':
            return Admin::user()->isRole('administrator');
        case 'posts':
            return Admin::user()->isOne(['post-admin', 'administrator']);
        case 'comments':
            return Admin::user()->isOne(['comment-admin', 'administrator']);
        default:
            return false;
    }
}

And in your blade:
<?php foreach(Admin::menuLinks() as $link) { ?>
    <?php if (adminHasAccess($link['uri'])) {?>
        <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
            <?= admin_trans ($link['title']) ?>

    <?php } ?>
<?php } ?>

For the jammed solution, you can try
<?php foreach(Admin::menuLinks() as $link) { ?>
    <?php if (
        (Admin::user()->isRole('administrator') &&  in_array($link['uri'], ['users', 'posts', 'comments'])) ||
        (Admin::user()->isRole('post-admin') && in_array($link['uri'], ['posts'])) ||
        (Admin::user()->isRole('comment-admin') && in_array($link['uri'], ['comments']))
        ) {?>

        <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
            <?= admin_trans ($link['title']) ?>

    <?php } ?>
<?php } ?>

Or more compact but less maintainable
<?php foreach(Admin::menuLinks() as $link) { ?>
    <?php if (in_array($link['uri'], Admin::user()->isRole('administrator') ? ['users', 'posts', 'comments'] : (Admin::user()->isRole('post-admin') ? ['posts'] : (Admin::user()->isRole('comment-admin') ? ['comments'] : [])))) {?>

        <a class="sidebar-toggle sidebar-toggle-link" role="button" href="<?= admin_url($link['uri']) ?>"><i class="fa <?= $link['icon'] ?>">
            <?= admin_trans ($link['title']) ?>

    <?php } ?>
<?php } ?>

A: This is a tipical situation where Policies should help to resolve your problem
I would create a Policies for User, Post, Comment Models and later in my view I would use can() and cannot() helpers to check view on models with the auth user, as in your policies you are checking the auth user Rol.
https://laravel.com/docs/9.x/authorization#writing-policies


text:
Q: React 15 not compatible with React-redux I am trying to upgrade to the freshly released react@15.0.0-rc.1 on my project that is also using react-redux@^4.4.0 package.
However when I try to run the upgrade suggested in the documentation (https://facebook.github.io/react/blog/2016/03/07/react-v15-rc1.html)
npm install --save react@15.0.0-rc.1 react-dom@15.0.0-rc.1

It comes up with an error because the versions are not compatible:
npm ERR! peerinvalid Peer react-addons-test-utils@0.14.7 wants react@^0.14.7
npm ERR! peerinvalid Peer react-redux@4.4.0 wants react@^0.14.0

Any suggestion please?

A: I just published react-redux@4.4.1 which allows React 15 as a peer dependency.
Note that you can use npm@3.x which doesn't enforce peer dependencies. This way, you don't have to wait for project authors to update their packages.


text:
Q: Webview load html from assets directory and send data to I'm trying to load a html page from the assets directory
public class ViewWeb extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        WebView wv;
        wv = (WebView) findViewById(R.id.webView1);
        wv.loadUrl("file:///android_asset/aboutcertified.html");
    }
  }

its work but i wont to send some text also for textbox. How to Do that? Pls help me!!!!

A: One way of  doing this is to have JavaScript bridge apis. Let say you have JS method in HTML like this :
function setText(message){
     // Set message to Text Box
}

You can Invoke this JS method from native code(Java) like this:
myWebView.loadUrl("javascript:setText(" + text + ")");

A: There are two ways.
First way
In javascript
function getParameters(query) {
    var parts = query.split('&');
    var params = {};
    for (var i = 0, ii = parts.length; i < ii; ++i) {
        var param = parts[i].split('=');
        var key = param[0];
        var value = param.length > 1 ? param[1] : null;
        params[decodeURIComponent(key)] = decodeURIComponent(value);
    }
    return params;
}
document.addEventListener("load", function() {
    var params = getParameters(document.location.search.substring(1));
    if(params.hasOwnProperty('text_box_value')) {
        var textBox = document.getElementById(<ID of your textbox>);
        textBox.value = params['text_box_value'];
    }
}
);

In Java code
wv.loadUrl("file:///android_asset/aboutcertified.html?text_box_value=sometext");

Second way
In Java code
public class ViewWeb extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        WebView wv;
        wv = (WebView) findViewById(R.id.webView1);
        wv.setWebViewClient(new CustomWebViewClient());
        wv.loadUrl("file:///android_asset/aboutcertified.html");
    }
}

private class CustomWebViewClient extends WebViewClient {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        view.loadUrl("javascript:(function setText() {var textBox = document.getElementById('your textbox id'); textBox.value = '" + yourTextString + "';})()");
    }
}


text:
Q: Ambiguous compiling of string array with non-constant size? My gcc compiler from mingw64 8.1.0 doesn't allow the following to be compiled because var has to be a constant value:
    int var=3;
    string str[var];

int main(){

However, doing the same within main() doesn't show any errors:
int main(){
    int var;
    cin >> var;
    string str[var];

Why is there an ambiguity?
My compile command is simple: g++ main.cpp
These are the headers I had included in the beginning for both the cases:
#include <iostream>
#include <string>
#include <sstream>

A: Depending on your compile flags, they're both "wrong":
Code:
#include <string>

int i = 3;
std::string s1[i];

int main ()
{
  int j = 3;
  std::string s2[j];
  return 0;
}

g++ -o tmp3 -g -pedantic -Wall tmp3.cpp
tmp3.cpp:4:17: error: array bound is not an integer constant before ']' token
 std::string s1[i];
                 ^
tmp3.cpp: In function 'int main()':
tmp3.cpp:9:19: warning: ISO C++ forbids variable length array 's2' [-Wvla]
   std::string s2[j];

Remembering that VLAs are a 'C' feature ("discouraged" in C++, only supported as an "extension"), here are the rules:

https://en.cppreference.com/w/c/language/array
Declarator for VLA of unspecified size (can appear in function
prototype scope only) where expression

*

*any expression other than
comma operator, designates the number of elements in the array
qualifiers

*any combination of const, restrict, or volatile
qualifiers, only allowed in function parameter lists; this qualifies
the pointer type to which this array parameter is transformed

Importantly:

Objects of any variably-modified type may only be declared at block
scope or function prototype scope.

This is precisely why the first example is an "error"; the second a "warning".  VLAs must be stack-allocated variables.

A:
However, doing the same within main() doesn't show any errors

It would tell that this code is not correct C++ if you call it properly:
g++ -Wpedantic t.cpp

produces this warning:
t.cpp: In function 'int main()':
t.cpp:3:16: warning: ISO C++ forbids variable length array 'arr' [-Wvla]
     int arr[var];

for this t.cpp file:
int main(){
    int var = 3;
    int arr[var];
}

A: GCC accepts Variable Length Arrays (VLAs) as a language extension, but only in certain situations (emphasis mine):

These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits

As an extension, GCC accepts variable-length arrays as a member of a structure or a union.

You can also use variable-length arrays as arguments to functions:

Creating an array outside of block scope (i.e. in global memory area) is not one of the accepted use-cases for VLA. See the documentation.
Note that, as everyone else mentioned, VLAs are GCC extension and are not a part of C++ standard. MSVC for example will not compile them at all.


text:
Q: Dynamically style certain tag in javascript To style body you can simply do document.body.style.color = "white" for example, but if I want to do the same with pre-tag how do I do that?

A: The best solution would be to alter the styles with a class. This is typically how themes work. You set a class on the body that alters the things you want changed.

window.setTimeout( function () {
  document.body.classList.add("luckyGreen")
}, 4000)

window.setTimeout( function () {
  document.body.classList.remove("luckyGreen")
}, 8000)
pre {
  background-color: #CCC;
}

body.luckyGreen {
  color:green;
}
body.luckyGreen pre {
  background-color: #CFC;
}

 Hello there

X

 Hello there

Y

 Hello there

But for some reason you want to alter a class, you can write a new css rule.

function addRule() {
  var styleEl = document.createElement('style');
  document.head.appendChild(styleEl);
  var styleSheet = styleEl.sheet;
  var ruleStr = "pre { background-color: red; }"
  styleSheet.insertRule(ruleStr, styleSheet.cssRules.length);
}

window.setTimeout(addRule, 4000)

 Hello there

X

 Hello there

Y

 Hello there

A: In this case you need to use getElementsByTagName as follows:
var tags = document.getElementsByTagName("pre");
for(var i = 0; i < tags.length; i++)
     tags[i].style.color = "white";

A: You can create classes in your CSS then toggle them or add/remove them or manually do stuff like this.

let v3 = document.getElementsByTagName("pre")[2];
v3.classList.add('three');

let pre = document.getElementsByTagName("pre")[0];
pre.classList.add('one');

let preAll = document.getElementsByTagName("pre");
preAll[3].classList.add('four');

let i;
for (i = 0; i < preAll.length -1; i++) {
  preAll[i].style.backgroundColor = "#ddddff";
}
pre.one {
  color: red;
  font-weight: bold;
}

pre.two {
  color: blue;
  font-weight: 2;
}

pre.three {
  background-color: #ddffdd;
}

pre.four {
  color: green;
  background-color:#ffddff;
  font-weight: bold;
}

pretty pre

pretty pre

pretty pre

pretty pre


text:
Q: Invalid column definition error when using four part name to access Oracle DB as SQL Server linked server I have setup a linked server in SQL Server 2008 R2 in order to access an Oracle 11g database. The MSDASQL provider is used to connect to the linked server through the Oracle Instant Client ODBC driver. The connection works well when using the OPENQUERY with the below syntax:
SELECT *
FROM OPENQUERY(LINKED_SERVER, 'SELECT * FROM SCHEMA.TABLE')

However, went I try to use a four part name using the below syntax:
SELECT *
FROM LINKED_SERVER..SCHEMA.TABLE

I receive the following error:

Msg 7318, Level 16, State 1, Line 1
  The OLE DB provider "MSDASQL" for linked server "LINKED_SERVER" returned an invalid column definition for table ""SCHEMA"."TABLE"".

Does anyone have any insight on what my be causing the four part name query to fail while the OPENQUERY one works without any problems?

A: The correct path to follow is to use OPENQUERY function because your linked server is Oracle: the four name syntax will work fine for MSSQL servers, essentially because they understand T-SQL.
With very simple queries, a 4 part name can accidentally work but not often if you are in a real scenario. In your case, the SELECT * is returning all the columns, and in your case one of the column definition is not compatible with SQL Server. Try another table or try to select a single simple column (e.g. a CHAR or a NUMBER), maybe it will work without problem.
In any case, using distributed queries can be tricky sometime. Database itself does some optimizations before executing commands, so it is important for the database to know what it can do and what it can't. If the DB thinks the linked server is MSSQL, it will take some action that may not work with Oracle.
When using four part name syntax with a linked DB different from MSSQL, you will have other problems as well, for example using database builtin functions (i.e. to_date() Oracle function will not work because MSSQL would want to use its own convert() function, and so on).
So again, if the linked server is not a MSSQL, the right choice is to use OPENQUERY and passing it a query that use a syntax valid against the linked server SQL dialect.

A: If you use the OLEDB provider for Oracle you can query without using openquery


text:
Q: I happend to chmod 755 my whole /usr/ dir I happend to change my whole /usr/ dir files to -rwxr-xr-x with command "sudo chmod 775 -R /usr/"
now I firguire out that some special binary files like "su" "chkpaswd"and "sudo" should have the privilege
of setuid ,and I have use chmod to return them back to fix same authority problem.
But still have some mistory trouble like I cant use dolphin to mount the dev automaticly or use kwrite to rewrite some files by input passwd.It just says u dont have right to operate:Not authorized to perform operation
and now ,I cant just open the appimage because of
Cannot mount AppImage, please check your FUSE setup.
You might still be able to extract the contents of this AppImage
if you run it with the --appimage-extract option.
See https://github.com/AppImage/AppImageKit/wiki/FUSE
for more information
open dir error: No such file or directory
I use debian 10 base os ubuntu 20.04 ,and this pic is what i have in /usr/.
I did this dangerous operation because I want to use CAE on oridinary user.enter image description here
So ,can some handsome guys to told me are there any special files like "sudo" in dir /usr/ that I dont know?
Thanks!!QwQ

A: This is what we refer to as a "fatal error". It would be very tedious and lengthy to get to know the required file permission of every system file, then correct the permissions.  In practice, the only solution here is a reinstall.
Note that you can reinstall without reformatting the system file system. Doing so will rather work as a "repair", updating all of your system files but leaving installed programs and system configuration intact. Also user configuration is preserved because user home folders are not deleted.

A: I spend my space time to start a virt system of Ubuntu,and try to figure out the difference between the origin one and my broken one.
After I modify the special right of many key files ,it really help of solving almost every problems.I say like that because maybe there`re still some thing I didnt find yet.
follow are some files which have setuid right may help people like me to fix serious authrioty problems :

enter image description here


text:
Q: Understanding the change of seek bar in Android 10 notification  mediaSession.setPlaybackState(
        PlaybackStateCompat.Builder()
            .setState(
                PlaybackStateCompat.STATE_PLAYING,
                myPlayer!!.getCurrentPosition(),
                myPlayer!!.getSpeed()
            )
            .setActions(PlaybackStateCompat.ACTION_SEEK_TO)
            .build()
    )

How when the notification seekBar is changed? Should I change the position of the player?


text:
Q: How to remove all array items except at indexes at multiples of x - Swift I have an array of coordinates (965 in total). I want to use these coordinates in Google Roads API however the limit is 100.
I have a function that determines how many items in the array and then gets the value to use.
round(Double(userCoordinatesHardCoded.count / 100))

produces 9.
I would like to remove ALL items that are not at indexes that are multiples of, in this case, 9. So in theory I will only ever have no more than 100 items in the array.
If possible, I would like to keep the first and last array item.

A: I know this has already been answered, but this is a great use case for using the filter function built into Swift:
let newCoordinates = oldCoordinates.filter { coord in
  return (coord % 9 != 0)
}

A: If space is not a problem, you can create another array with the desired multiples.
var oldCoordinates // Imagine it having all those elements
var newCoordinates : GoogleCoordinates = [] // This one will have new ones

newCoordinates.append(oldCoordinates[0])
var x = 1
for (x; x < oldCoordinates.count ; x++ ) {
   if (x % 5 == 0) {
      newCoordinates.append(oldCoordinates[x])
   }
}
if (x != (oldCoordinates.count - 1)) {
   newCoordinates.append(oldCoordinates[oldCoordinates.count - 1])
}


text:
Q: Tried to load Angular more than once + included the Google Maps API multiple times on this page Whenever I press the "Get started" button on my website, the screen goes black and I get the following errors in the console log. I do not see this issue locally, prior to grunt build being run and me deploying to Heroku:
WARNING: Tried to load angular more than once.

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

The code for my index.html is as follows, full code here:
  <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyBHuxIv-E8l4YRp_vWjW7X22gRNwI1xN30"></script>
  <!-- build:js(.) scripts/vendor.js -->
  <!-- bower:js -->
  <script src="bower_components/jquery/dist/jquery.js"></script>
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js"></script>
  <script src="bower_components/angular-animate/angular-animate.js"></script>
  <script src="bower_components/angular-cookies/angular-cookies.js"></script>
  <script src="bower_components/angular-resource/angular-resource.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
  <script src="bower_components/angular-touch/angular-touch.js"></script>
  <script src="bower_components/ngstorage/ngStorage.js"></script>
  <script src="bower_components/moment/moment.js"></script>
  <script src="bower_components/angular-moment/angular-moment.js"></script>
  <script src="bower_components/angular-strap/dist/angular-strap.js"></script>
  <script src="bower_components/angular-strap/dist/angular-strap.tpl.js"></script>
  <script src="bower_components/angular-modal-service/dst/angular-modal-service.js"></script>
  <script src="bower_components/vsGoogleAutocomplete/dist/vs-google-autocomplete.js"></script>
  <script src="bower_components/vsGoogleAutocomplete/dist/vs-autocomplete-validator.js"></script>
  <!-- endbower -->
  <!-- endbuild -->

What else could be causing the issue?
Update
I've included my Grunt task as well: https://pastebin.com/3JiaQwXU.

A: Upon analysing  your page in the dev console, it seems that you are indeed loading the script twice. I shall explain.
Follow the image below
On clicking Get started you are basically loading the entire page again. Check html of getstarted.html. If you intend to use templates then the template should have only a portion of the view not the entire site from the very top.


text:
Q: How to fit an image in a stacklayout or grid? I have an image that in xamarin form the image adjust to fit in stacklayout. Now that i migrated to .net MAUI the image does not adjust but part of the image is hidden by the stacklayout or the stacklayout swallows part of the image. The purple background is another stacklayout that will contain other images that will also fit to the purple stacklayout.

    <StackLayout x:Name="PlayingWindow">
        <StackLayout HorizontalOptions="Center"  VerticalOptions="End"  Padding="2" x:Name="PlayingWindow1" >
            </Grid>

        <Grid Grid.Row="1" >
            <ScrollView HorizontalOptions="Center"  VerticalOptions="End"  Padding="2" x:Name="PlayingWindow1"  >
                <Grid x:Name="mainGrid"
                  Grid.Row="1"  Padding="2,0" RowSpacing="2" ColumnSpacing="2" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                    <!-- Initialized for Portrait m\ -->
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                    </Grid.ColumnDefinitions>
                    <!-- History display. -->

                    <Label Text="Levels:" Grid.Row="0" Grid.Column="0" BackgroundColor="LightGreen" HeightRequest="15"/>
                    <Label Text="1" Grid.Row="0" Grid.Column="1" x:Name="Level" BackgroundColor="LightGreen" />
                    <Label Text="Timer:" Grid.Row="0" Grid.Column="2"  x:Name="Time" BackgroundColor="DarkGray"  />
                    <Label Text="" Grid.Row="1" Grid.Column="0"  x:Name="Callback" BackgroundColor="DarkGray"  />
                    <Label Text="Commands:" Grid.Row="1" Grid.Column="1" x:Name="Card" BackgroundColor="DarkGray"  />
                    <Label Text="Player6" Grid.Row="1" Grid.Column="2"  x:Name="Player6" BackgroundColor="DarkGray"  />
                    <Label x:Name="TimeContainer1" Text="" BackgroundColor="White"   Grid.Row="1" Grid.Column="2" />
                    <Image Source="" x:Name="ImageCommands" Grid.Row="1" Grid.Column="2" HorizontalOptions="Center"  VerticalOptions="Center" >
                        <Image.GestureRecognizers >
                            <TapGestureRecognizer Tapped ="Imagejokerb" />
                        </Image.GestureRecognizers >
                    </Image>
                    <Button x:Name="initiator" Text="Me" BackgroundColor="LightGreen"   Grid.Row="1" Grid.Column="3" Pressed="play"  CornerRadius="25"  />
                </Grid>

            </ScrollView >
        </Grid>

        </StackLayout >

        <ScrollView HorizontalOptions="Center" HorizontalScrollBarVisibility="Always" Orientation="Horizontal" >
            <StackLayout  Orientation="Horizontal" x:Name="PlayingWindow2">

                <Image Source="pickme.png" x:Name="pickCard" HorizontalOptions="Center"  VerticalOptions="Center"  >
                    <Image.GestureRecognizers >
                        <TapGestureRecognizer Tapped ="TapGestureRecognizer_pickme_5" />
                    </Image.GestureRecognizers >
                </Image>

                <Image  x:Name="droppedCard" HorizontalOptions="Center"  VerticalOptions="Center"  />

            </StackLayout>

        </ScrollView>
        <ScrollView HorizontalOptions="Center" HorizontalScrollBarVisibility="Always" Orientation="Horizontal" >
            <StackLayout Orientation="Horizontal" x:Name="PlayingWindow3" BackgroundColor="MediumPurple">

                <Image Source="pickme.png" x:Name="VariableImagepickmeb" HorizontalOptions="Center"  VerticalOptions="Center" IsVisible="false" >
                    <Image.GestureRecognizers >
                        <TapGestureRecognizer Tapped ="Imagepickmeb" />
                    </Image.GestureRecognizers >
                </Image>
                <Image Source="pickme.png" x:Name="VariableImagepickmer" HorizontalOptions="Center"  VerticalOptions="Center" IsVisible="false" >
                    <Image.GestureRecognizers >
                        <TapGestureRecognizer Tapped ="Imagepickmer" />
                    </Image.GestureRecognizers >
                </Image>

            </StackLayout>
        </ScrollView>
    </StackLayout>

I wish to have the picture adjust, to the stacklayout proportion.
Can some help please?

A: First of all, you have ScrollViews stacked on top of each other in a StackLayout and your image is in a StackLayout inside of one of the ScrollViews, which means the StackLayout that contains the image will have an overflow that is hiding part of the image. You should be able to scroll to it.
You could remove the ScrollView around the StackLayout with the image.
[UPDATED]
At least you should set the Image.Aspect property to AspectFit or Fill: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/image#control-image-scaling:
<ScrollView HorizontalOptions="Center" HorizontalScrollBarVisibility="Always" Orientation="Horizontal">
    <StackLayout Orientation="Horizontal" x:Name="PlayingWindow2">
        <Image Source="pickme.png" x:Name="pickCard" HorizontalOptions="Center" VerticalOptions="Center"
               Aspect="AspectFit">
            <Image.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_pickme_5"/>
            </Image.GestureRecognizers>
        </Image>
        <Image x:Name="droppedCard" HorizontalOptions="Center" VerticalOptions="Center"/>
    </StackLayout>
</ScrollView>

However, auto-sizing images does not work well with ScrollViews when neither Width nor Height are constrained in any way.
Also, if you want to keep adding items to the View, then I recommend using a different type of View. You could, for example, use a HorizontalListView (Sharpnado.CollectionView package) or a CollectionView or anything that allows you to display a set of Views or Data, because they are better suited for dynamic layouts and data compared to a StackLayout wrapped inside a ScrollView, which is more appropriate for View elements that are known at compile time.


text:
Q: How to login with email and password in angular typescript I have an Angular app where user can login with his email and password. so at first i just want the login (login.component) page to appear first, when the user enters his email and password then we go directly to menu page (app.component), in the menu page we have LogOut so when the user click on it then return to login page.
This is what i do :
code :
login.component.html :

S'identifier

        <form class="login-container" #myform="ngForm" (ngSubmit)="onSubmit(myform)">

            <input class='form-control' type="email" name="email" placeholder="email" ngModel>

            <input class='form-control' type="password" name="password" placeholder="Password"
              [type]="hide ? 'password': 'text'" [(ngModel)]="passwordValue">

              {{hide ? 'visibility': 'visibility_off'}}

          <input class='btn btn-outline-info' type="submit" value="Login">
        </form>

You are logged in

        <button class='btn btn-outline-info' (click)='logout()'>Log-out</button>

login.component.ts :
export class LoginComponent implements OnInit {
  isLogin: boolean = false
  errorMessage: any
  hide =true;
  passwordValue='';

  constructor(
    private _api: ApiService,
    private _auth: AuthService,
    private _router:Router,  private toastr : ToastrService) { }

  ngOnInit(){
    this.isUserLogin();
  }

  onSubmit(form: NgForm) {

    console.log('Your form data : ', form.value);
    this._api.postTypeRequest('user/login', form.value).subscribe((res: any) => {

      switch (res.status) {
        case 0:
            this.toastr.error("you have a problem","Erreur");
            break;
        case 1:
            this._auth.setDataInLocalStorage('userData', JSON.stringify(res.data));
            this._auth.setDataInLocalStorage('token', res.token);
            this._router.navigate(['']);
            break;
        case 2:
            this.toastr.warning("your email or password is incorrect","Warning");
            this.passwordValue = '';
            break;
    }
    })
  }

  isUserLogin(){
    if(this._auth.getUserDetails() != null){
        this.isLogin = true;
    }
  }

  logout(){
    this._auth.clearStorage()
    this._router.navigate(['']);
  }
}

app.component.html (menu) :

Adherents

            Factures

            Logs

            Regions

            Roles

            welcome james

LogOut

<router-outlet></router-outlet>

auth-guard.service.ts :
@Injectable({
  providedIn: 'root'
})
export class AuthGuardService {

  constructor( private _authService: AuthService,
    private _router: Router) { }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if (this._authService.getToken()) {
        return true;
      }

      this._router.navigate(['/login']);
      return false;
    }

}

auth.service.ts:
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor() { }

  getUserDetails() {
    if(localStorage.getItem('userData')){
      return localStorage.getItem('userData')
    }else{
      return null
    }

  }
  setDataInLocalStorage(variableName, data) {
      localStorage.setItem(variableName, data);
  }
  getToken() {
      return localStorage.getItem('token');
  }
  clearStorage() {
      localStorage.clear();
  }

}

api.service.ts :
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  baseUrl = 'http://localhost:3000/';

  constructor(private _http: HttpClient) { }

  getTypeRequest(url) {
    const headers = new HttpHeaders().set('Content-Type','application/json');
    return this._http.get(`${this.baseUrl}${url}`, {headers}).pipe(map(res => {
      return res;
    }));
  }
  postTypeRequest(url, payload) {
    const headers = new HttpHeaders().set('Content-Type','application/json');
    return this._http.post(`${this.baseUrl}${url}`, payload, {headers}).pipe(map(res => {
      return res;
    }));
  }

}

A: The question is not clear but I guess you just need to use logout() method in the app component the same way you are using it in the login component

LogOut

A: You have to follow the below steps

*

*Replace app.component.html code like

Existing

LogOut

New

LogOut

*Paste the below code lines in app.component.ts
logout(){this._auth.clearStorage();this._router.navigate(['/login']);}

*Check the constructor of app.component.ts and verify that there are the following lines added (similar to login.component.ts)
private _auth: AuthService, private _router:Router


text:
Q: C: How to append data to a file without using standard I/O libraries I was wondering if there is a way to append data to a file without using functions from standard I/O libraries (i.e. stdio.h). I though of doing something like this first:
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("test.txt", O_WRONLY | O_CREAT, 0700);
    ssize_t wr = write(fd, "hello world", sizeof("hello world");
}

But this only writes data to the file without appending it so instead repeatedly displaying "hello world", it only overwrites the previous data and displays it once. Can someone please help me out? Thanks

A: Try this:
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main() {
    int fd = open("test.txt", O_WRONLY | O_CREAT | O_APPEND, 0700);
    ssize_t wr = write(fd, "hello world", strlen("hello world");
    exit(0);
}


text:
Q: iPhone SDK deployment target on Xcode I'm hesitant about Deployment target in xCode.
my question : can my application run on iOS 3, 4, 5, 6 if I select on Deployment target 4.3 ?
I can't test my application on an iPhone because I don't have it but I think the application can only run on IOS 4.3 or later
sorry for my bad english

A: If you use iOS 4.3 as deployment target, that will be the minimum version supported by your app. So, no, it won't run in iOS 3.0 for instance.
Also, you'll need to detect features not present in the iOS actually running the app and program them conditionally.
I'd suggest supporting iOS 5 or better. And definitely forgetting about iOS 3.

A: That is correct. The Deployment Target is the earliest version of iOS that your application will support.
Note, however, that if you use an API call from your current SDK (4.3) that is not present in the 3.0 SDK, your application will crash on devices running iOS 3.0.
So even though you can set the Deployment Target to 3.0, that will not guarantee that your app will work on an iOS 3 device.
See the Apple Developer documentation for more details.


text:
Q: React + FontAwesome + Bootstrap I am attempting to learn React and Bootstrap at the same time. I am a beginner.
My issue is that I am trying to display a FontAwesome icon within a React application using the FontAwesome component.  I have a Pro license for FontAwesome and have followed their directions on setting up the dependencies.  My package.json contains the following:
"dependencies": {
    "@fortawesome/fontawesome-pro": "^5.15.4",
    "@fortawesome/fontawesome-svg-core": "^1.2.33-beta1",
    "@fortawesome/pro-regular-svg-icons": "^6.0.0-beta1",
    "@fortawesome/react-fontawesome": "^0.1.15",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.1.1",
    "react": "^17.0.2",
    "react-bootstrap": "^1.6.3",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

When I attempt to use an icon in a component like below:
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faUser } from "@fortawesome/pro-regular-svg-icons";

function Header(){
    return (

My Header

            <FontAwesomeIcon icon={faUser} color="red" size="6x" />

    )
}

export default Header

I get an error:
Error: Cannot find module '@fortawesome/free-solid-svg-icons'
When I review the error bodies below the header they all seem to point to bootstrap.
__webpack_require__
C:/work/RTS/rts_react/webpack/bootstrap:851
  848 |
  849 | __webpack_require__.$Refresh$.init();
  850 | try {
> 851 |     modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  852 | } finally {
  853 |     __webpack_require__.$Refresh$.cleanup(moduleId);
  854 | }
View compiled
fn
C:/work/RTS/rts_react/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
▶ 2 stack frames were collapsed.
__webpack_require__
C:/work/RTS/rts_react/webpack/bootstrap:851
  848 |
  849 | __webpack_require__.$Refresh$.init();
  850 | try {
> 851 |     modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  852 | } finally {
  853 |     __webpack_require__.$Refresh$.cleanup(moduleId);
  854 | }
View compiled
fn
C:/work/RTS/rts_react/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
▶ 2 stack frames were collapsed.
__webpack_require__
C:/work/RTS/rts_react/webpack/bootstrap:851
  848 |
  849 | __webpack_require__.$Refresh$.init();
  850 | try {
> 851 |     modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  852 | } finally {
  853 |     __webpack_require__.$Refresh$.cleanup(moduleId);
  854 | }
View compiled
fn
C:/work/RTS/rts_react/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
▶ 2 stack frames were collapsed.
__webpack_require__
C:/work/RTS/rts_react/webpack/bootstrap:851
  848 |
  849 | __webpack_require__.$Refresh$.init();
  850 | try {
> 851 |     modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  852 | } finally {
  853 |     __webpack_require__.$Refresh$.cleanup(moduleId);
  854 | }
View compiled
fn
C:/work/RTS/rts_react/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:1069:18
__webpack_require__
C:/work/RTS/rts_react/webpack/bootstrap:851
  848 |
  849 | __webpack_require__.$Refresh$.init();
  850 | try {
> 851 |     modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  852 | } finally {
  853 |     __webpack_require__.$Refresh$.cleanup(moduleId);
  854 | }
View compiled
checkDeferredModules
C:/work/RTS/rts_react/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
C:/work/RTS/rts_react/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;

I have looked through my project which is still small because I am just beginning and I can't find any reference to the Free icons for FontAwesome.  I am at a loss and not sure what to even ask.  Is there a reference to the free icons within the Bootstrap React component?

A: According to FontAwesome's React documentation, you need to install @fortawesome/free-solid-svg-icons, too, before adding additional styles.
Run npm i --save @fortawesome/free-solid-svg-icons and try again.


text:
Q: Python how to create excel with autofilter from pandas dataframe and openpyxl I tried to create an excel file from Python pandas dataframe with the auto filter to display invalid data as default.
Here's my input dataframe df:
ITEM   RESULT
A1    VALID
A2    VALID
A#  INVALID

I want to add a worksheet 'filter test' on an existing excel file 'filter_output.xlsx' and with auto-filter set to column 'RESULT' to display only 'INVALID' data by default.
Here's my code:
import pandas as pd
from openpyxl import load_workbook

workbook=load_workbook('filter_output.xlsx')
writer = pd.ExcelWriter('filter_output.xlsx', engine='openpyxl')
writer.book=workbook
df.to_excel(writer, 'filter test', index=False)
ws=writer.sheets['filter test']
ws.auto_filter.ref='A:B'
ws.auto_filter.add_filter_column(1, 'INVALID', blank=False)
writer.save()
workbook.close()

I got the following error:
  ws.auto_filter.add_filter_column(1, 'INVALID', blank=False)
  File "C:\Python27\lib\site-packages\openpyxl\worksheet\filters.py", line 357, in add_filter_column
    self.filterColumn.append(FilterColumn(colId=col_id, vals=vals, blank=blank))
  File "C:\Python27\lib\site-packages\openpyxl\worksheet\filters.py", line 315, in __init__
    self.filters.filter = vals
  File "C:\Python27\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in __set__
    raise TypeError("Value must be a sequence")
TypeError: Value must be a sequence

Any idea about how to fix this error ?
Is there a better way to create excel with auto filter on to show default value only from pandas dataframe?

A: I was looking for the same and could not find the bug.
Trial/error led me to the decision you need to use list
ws.auto_filter.add_filter_column(1, ['INVALID'], blank=False)

Reference https://openpyxl.readthedocs.io/en/2.5/filters.html


text:
Q: Use of std::use_facet to get local currency I am trying to use the standard library to decide billing info based on locale. I went through a few examples http://en.cppreference.com/w/cpp/locale/use_facet
As per the example it returns USD but when I run I  am get nothing
#include <iostream>
#include <locale>

int main()
{
    std::locale loc = std::locale(""); // user's preferred locale
    std::cout << "Your currency string is "
              << std::use_facet<std::moneypunct<char, true>>(loc).curr_symbol() << '\n';
}

Output
Your currency string is
Program ended with exit code: 0

Expected output (if user from US)
Your currency string is USD
Program ended with exit code: 0

Expected output (if user from India )
Your currency string is RS
Program ended with exit code: 0

Am I Missing anything? How to make it to use by default use the locale  based on time zone of the user?

A: Got some break through
#include <iostream>
#include <locale>
#include <clocale>

int main()
{
    std::setlocale(LC_MONETARY, "it_IT");
    const struct lconv * const currentlocale = localeconv();
    std::cout<<"In the current locale, the default currency symbol is:"<<currentlocale->currency_symbol<<std::endl;

}

Output
In the current locale, the default currency symbol is:Eu
Program ended with exit code: 0


text:
Q: Android: Error in opening db file I am using this code to check whether a database already exists:
public static boolean checkDataBase(String DB_FULL_PATH) {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
    }
    return checkDB != null ? true : false;
}

My Helper Class is:
public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "my_db";
    private static final String TABLE_NAME = "products";
    private static final String KEY_NAME = "pname";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_NAME + " TEXT" + ")";
        db.execSQL(CREATE_PRODUCTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addProducts(String product_name) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, product_name); // Product Name
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public String getProducts() {

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        String s = "default";
        if (cursor.moveToFirst()) {
            int n = cursor.getCount();
            s = cursor.getString(0);
        }
        cursor.close();
        return s;
    }
}

when i tried this:
checkDataBase(Environment.getDataDirectory() + "/data/com.android.my_app/databases/my_db.db")

I get this Error message in log cat:
sqlite returned: error code = 14, msg = cannot open file at source line 25467
sqlite3_open_v2("/data/data/com.android.my_app/databases/my_db.db", &handle, 1, NULL) failed

A: Use this to check Database
     private boolean checkDataBase() {
    // TODO Auto-generated method stub
       File dbFile = new File(DB_PATH + DB_NAME);
       return dbFile.exists();
  }
    where  path
    private static String DB_PATH = "/data/dat/your_package_name/databases/";
    and  DB_NAME is database name


text:
Q: When should I use type level computation in scala? I have been studying type-level programming in scala lately, and apparently it can do some fancy stuff at compile time, and that's interesting and impressive. I am wondering when should I use these tricks (after I get sufficiently familiar with them)?
Admittedly this is a very broad question, but I guess I am not the only one who is thinking about this, so hopefully experts can shed some light for the newbies.

A: The golden rule is to do so when it leads you to a safer and more elegant solution that is easy to understand and faster to implement than a regular solution. Otherwise code in the way you prefer or the way you are advised to. It's like asking "when should I use functional style vs imperative style?" Imho it's up to you. Some solutions are more natural with functional and others are more natural with imperative. The same is true for type level programming but what is intrisically easier with type level programming could become a nightmare for someone that is still struggling with the basics.
Also you could find a lot of already developed stuff with this style, like shapeless and many other libs that leverage the power of Scala's type system to solve common problems and support powerful abstractions that maybe you wouldn't look for otherwise.
My suggestion, as someone that is still struggling with type level programming, is to start with tools like shapeless and first learn the abstractions inherited from category theory and all that stuff. When you will have many of these concepts in your bag, you could start thinking of new solutions to implement with the type system.
My 2 cents.


text:
Q: Convert array key from string to int of same value I have a a vaery large array which is parsed to my php script in json form. I would like to convert the keys from string to integer. The keys are serial numbers so i can't just use array_values. Currently i do it like this but would much prefer a solution that didn't involve a loop.
Example Array after json decode before int conversion:
array (
    '123' => 'my text',
    '223' => 'my text too',
    '183' => 'my text foo',
    '103' => 'my text doo',
    // more array items
);

Example Code:
$data = json_decode($_POST['json']);

$newArr = Array();
foreach ($data as $key => $val) {
    $ref = (int)$key;
    newArr[$ref] = $key;
}

A: $arr = array (
    '123' => 'my text',
    '223' => 'my text too',
    '183' => 'my text foo',
    '103' => 'my text doo'
);

$newArray = array_combine(array_map('intval', array_keys($arr)), array_values($arr));

A: Try this!
$test = array (
    '123' => 'my text',
    '223' => 'my text too',
    '183' => 'my text foo',
    '103' => 'my text doo',
    // more array items
);

$newArr = array_combine(array_keys($test), array_keys($test));

:)

A: If you have the source function via which the JSON encodes, just add  json_encode($data, JSON_NUMERIC_CHECK)
This will force the key fields in JSON to int (if int key field exist)


text:
Q: Intuition for the density of states of the free electron gas model The density of states as a function of energy for a free electron gas (inside some solid-thing where the electrons are modeled due to the free elecetron gas model) is in:
1D: D(E) ~ $\sqrt[-1/2]{E}$
2D: D(E) ~ $\sqrt[0]{E}$
3D: D(E) ~ $\sqrt[1/2]{E}$
The mathematics is okay but how does this makes sense from the physical point of view?
How does the dimension of the system dictate that in 3D we have more states with high energy where as in a 1D the system we get fewer and fewer states for increasing the energy?

A:
The mathematics is okay but how does this makes sense from the
  physical point of view? How does the dimension of the system dictate
  that in 3D we have more states with high energy where as in a 1D the
  system we get fewer and fewer states for increasing the energy?

The density of states just comes from counting the states with energy less that $E$ and identifying the integrand of that count as the density.
In three dimensions the count is given by
$$
\int d^3r \int d^3p\sim V\int^{\sqrt{2mE}} dp p^2 \sim V\int^E dE' (\sqrt{E'})\;,
$$
where  the $\sim$ means I've ignored some irrelevant constants. The part in the parenthesis on the far RHS is the density of states.
In two dimensions the count is given by
$$
\int d^2r \int d^2p\sim V\int^{\sqrt{2mE}} dp p\sim \int ^E dE\;,
$$
where you may notice that there is only 1 in the integrand.
In d-dimensions the count is given by
$$
\int d^dr \int d^dp\sim V\int^{\sqrt{2mE}} dp p^{d-1}\sim \int^E dE (E^{(d-2)/2})\;.
$$
So, the density of states for the free particle is always proportional to
$$
E^{(d-2)/2}\;,
$$
just due to counting states and the fact that E is a quadratic function of p.


text:
Q: How do I cite a UN Conference Fact sheet correctly? So there is a fact sheet by the United Nations uploaded from one of their conferences.
You can see it here.
How do I cite this correctly? It is not an article or anything similar.
I currently do it like this:
@manual{UNFactSheet,
    author        = "{United Nations}",
    title         = {Factsheet: People and Oceans},
    year          = {2017},
    url           = {https://www.un.org/sustainabledevelopment/wp-content/uploads/2017/05/Ocean-fact-sheet-package.pdf}
}

Is this more or less correct, or should I do something else?

A: You've chosen the @manual entry type, which IMNSHO isn't an entirely obvious choice; I would have chosen the @misc type. However, if you do want to stick with the @manual entry type, you could (should?) make use of the fact that this entry type recognizes the fields organization and address to write
@manual{UNFactSheet,
    author        = "{United Nations}",
    title         = {{Factsheet: People and Oceans}},
    organization  = {The Ocean Conference, United Nations},
    address       = {New York},
    year          = {2017},
    url           = {https://www.un.org/sustainabledevelopment/wp-content/uploads/2017/05/Ocean-fact-sheet-package.pdf}
}

And, be sure to load the xurl package to allow arbitrary linebreaks in the long URL string.


text:
Q: Adding rows to an empty TableLayout during execution I am trying to add a bunch of rows to an empty Table during execution. I have tried using some test code but for some reason the screen stays empty. If I had elements in the .XML They do show up, but not the table itself, unless I add some rows/elements inside the .XML file as well.
I would really appreciate some help.
My class extends Activity.
Here is the code to update the Table:
public Runnable UpdateUserList = new Runnable() {
    public void run() {

        TableLayout userTable = (TableLayout) findViewById(R.id.listOfUsers);
        for (String user : userNames) {
            TableRow row = new TableRow(getBaseContext());
            row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            TextView field = new TextView(getBaseContext());
            field.setText(user);
            field.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            row.addView(field);
            userTable.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        }
    }
};

I call the code using a Handler this way, from a Thread:
mHandler.post(UpdateUserList);

The code does get run and does not print any error.
This is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:background="@drawable/main_bg"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
        android:layout_marginTop="10px" android:gravity="center_horizontal"
        android:layout_weight="1" android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView android:text="@string/userList"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textSize="25px" />

    </LinearLayout>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/listOfUsers">
    </TableLayout>

</LinearLayout>

Any help would be very useful. I am very stuck right now.
EDIT: Using ListView
private Runnable UpdateUserList = new Runnable() {
    public void run() {
        ListView userTable = (ListView) findViewById(R.id.listOfUsers);
        userTable.setAdapter(new ArrayAdapter<String>(getBaseContext(),
                R.layout.connectserver, userNames));
    }
};

And the XML:
<ListView android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/listOfUsers" />

Rather than the TableLayout.

A: I think you'll find it easier to use a List instead of TableLayout.  One it's built to hold multiple items and can be easily integrated with a java.util.List or Array.  Secondly and more importantly, it is much more memory efficient if you have more than items than are visible.
With a List it only instantiates views for visible rows + 1 for a list of N.  If you use a TableLayout to display the same list it instanties N numbers of views.  So as your list grows so does your memory usage with a TableLayout.  Not so with a List.  It's the same regardless of how many items you have in that list.
Furthermore, it provides better way to track what items were selected when the user clicks on an item.  TableLayout doesn't provide any help in this so you have to roll your own mechanism for doing selection.


text:
Q: Powershell script to create folders from CSV list of users I found a powershell script that creates folders (if they dont exist) and adds appropriate permissions.
Below is the PS1 file (created by someone else)

##################################################################################
#
#
#  Script name: SetFolderPermission.ps1
#  Author:      goude@powershell.nu
#  Homepage:    www.powershell.nu
#
#
##################################################################################

param ([string]$Path, [string]$Access, [string]$Permission = ("Modify"), [switch]$help)

function GetHelp() {

$HelpText = @"

DESCRIPTION:
NAME: SetFolderPermission.ps1
Sets FolderPermissions for User on a Folder.
Creates folder if not exist.

PARAMETERS:
-Path           Folder to Create or Modify (Required)
-User           User who should have access (Required)
-Permission     Specify Permission for User, Default set to Modify (Optional)
-help           Prints the HelpFile (Optional)

SYNTAX:
./SetFolderPermission.ps1 -Path C:\Folder\NewFolder -Access Domain\UserName -Permission FullControl

Creates the folder C:\Folder\NewFolder if it doesn't exist.
Sets Full Control for Domain\UserName

./SetFolderPermission.ps1 -Path C:\Folder\NewFolder -Access Domain\UserName

Creates the folder C:\Folder\NewFolder if it doesn't exist.
Sets Modify (Default Value) for Domain\UserName

./SetFolderPermission.ps1 -help

Displays the help topic for the script

Below Are Available Values for -Permission

"@
$HelpText

[system.enum]::getnames([System.Security.AccessControl.FileSystemRights])

}

function CreateFolder ([string]$Path) {

    # Check if the folder Exists

    if (Test-Path $Path) {
        Write-Host "Folder: $Path Already Exists" -ForeGroundColor Yellow
    } else {
        Write-Host "Creating $Path" -Foregroundcolor Green
        New-Item -Path $Path -type directory | Out-Null
    }
}

function SetAcl ([string]$Path, [string]$Access, [string]$Permission) {

    # Get ACL on FOlder

    $GetACL = Get-Acl $Path

    # Set up AccessRule

    $Allinherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $Allpropagation = [system.security.accesscontrol.PropagationFlags]"None"
    $AccessRule = New-Object system.security.AccessControl.FileSystemAccessRule($Access, $Permission, $AllInherit, $Allpropagation, "Allow")

    # Check if Access Already Exists

    if ($GetACL.Access | Where { $_.IdentityReference -eq $Access}) {

        Write-Host "Modifying Permissions For: $Access" -ForeGroundColor Yellow

        $AccessModification = New-Object system.security.AccessControl.AccessControlModification
        $AccessModification.value__ = 2
        $Modification = $False
        $GetACL.ModifyAccessRule($AccessModification, $AccessRule, [ref]$Modification) | Out-Null
    } else {

        Write-Host "Adding Permission: $Permission For: $Access"

        $GetACL.AddAccessRule($AccessRule)
    }

    Set-Acl -aclobject $GetACL -Path $Path

    Write-Host "Permission: $Permission Set For: $Access" -ForeGroundColor Green
}

if ($help) { GetHelp }

if ($Path -AND $Access -AND $Permission) {
    CreateFolder $Path
    SetAcl $Path $Access $Permission
}

To run this script I use this command.
./SetFolderPermission.ps1 -Path E:\TestFolder\UsernameX -Access Domain\UsernameX -Permission modify
How can I make it so that i can just use one command and call it to create the folders from a CSV file?

A: This should do the trick:-
# Read in List of Users
$ListofUsers=Get-Content "UserList.csv"
foreach ($User in $ListofUsers)
{
SetFolderPermission.ps1 -Path E:\TestFolder\$User
}

A: I would modify Gary's command slightly, and use Import-Csv
# Read in List of Users
$rows=Import-Csv "UserList.csv"
foreach ($row in $rows) {
  $UsernameX = $row.UserName
  ./SetFolderPermission.ps1 -Path E:\TestFolder\$UsernameX -Access Domain\$UsernameX -Permission modify
}


text:
Q: Spring and Thymeleaf form validation using modelandview i am having a problem returning the error on thymeleaf template.
i have this on my controller, viewModel is ModelAndView object.
@PostMapping("/")
public ModelAndView Create(HttpServletRequest request, HttpServletResponse response, @Valid @ModelAttribute("viewModel")TViewModel model,
        BindingResult result, Model m) throws Exception {
   if (result.hasErrors()) {
        viewModel.setViewName("maintenance/role/create");
        viewModel.addObject("viewModel", model);
        viewModel.addAllObjects(result.getModel());

        return viewModel;
    }
        return viewModel;
}

And this is my view

        <input th:field="*{Description}" type="text" class="form-control" />
        Error!

I want to show the Error! when there is an error on description field, can somebody help me with this. i tried every possible way. Thank you.


text:
Q: How do I connect odoo and postgres with docker compose? I have been trying for a while and I can't get this working. I want to connect odoo (openERP) with postgres through docker-compose.
Here is my yml:
# Odoo server
app:
    build: ./containers/odoo
    ports:
      - "8000:8069"
    links:
      - db
    environment:
        POSTGRES_USER: myuser
        POSTGRES_PASSWORD: mypassword

# PostgreSQL server
db:
    build: ./containers/postgres
    environment:
        POSTGRES_USER: myuser
        POSTGRES_PASSWORD: mypassword

Dockerfiles are just like this:
FROM library/odoo

# For customizing purposes

I run it and the db name and password seleccion page apears and works ok. After init process, main page shows up almost in blank.
How do I fix this?
Thanks in advance.

A: Do you check there is no 404 error during page loading (using Developper pane in Chrome F12/Network) ?
Most of the time blank page in Odoo is caused by js/css loading failure. If so, you need to checl NodeJS et less install within your docker image.

A: docker-compose file,
 version: '2'
 services:
  database:
    image: postgres:9.5
    container_name: database
    environment:
      - POSTGRES_USER=odoo
      - POSTGRES_PASSWORD=odoo
    volumes:
      - /data-disk/postgres/data:/var/lib/postgresql/data
    ports:
     - "5432:5432"
  odoo:
    image: odoo8
    container_name: odoov8
    build: .
    ports:
      - "8069:8069"
    links:
      - database
    depends_on:
      - database
    environment:
      - PGHOST=database
      - PGUSER=odoo
      - PGPASSWORD=odoo
    volumes:
     - /home/username/company-files/debian:/etc/odoo


text:
Q: LinkedIn Ads AdAnalyticsV2: Internal Server Error Getting the error when fetching ad analytics from the API. The URL used: https://api.linkedin.com/v2/adAnalyticsV2?q=analytics
Other URL options sent along with the request (dummy account ID used):
{
  'accounts[0]': 'urn:li:sponsoredAccount:1234'
  'dateRange.start.year': 2017,
  'dateRange.start.month': 12,
  'dateRange.start.day': 1,
  'dateRange.end.year': 2017,
  'dateRange.end.month': 12,
  'dateRange.end.day': 22,
  timeGranularity: 'DAILY',
  pivot: [ 'MEMBER_JOB_TITLE' ]
}

So the full request becomes:
GET https://api.linkedin.com/v2/adAnalyticsV2?q=analytics&accounts[0]=urn:li:sponsoredAccount:1234&dateRange.start.year=2017&dateRange.start.month=12&dateRange.start.day=1&dateRange.end.year=2017&dateRange.end.month=12&dateRange.end.day=22&timeGranularity=DAILY&pivot=MEMBER_JOB_TITLE
This request worked earlier today, but now it returns an Internal Server Error. Does anyone else have this issue or know what I might be doing wrong? Thanks in advance.

A: It looks like you may be trying to pass in the options in the request body. To use the Ad Analytics API, you will need to pass in the options as query parameters in a GET request:
GET https://api.linkedin.com/v2/adAnalyticsV2?q=analytics&dateRange.start.month=12&dateRange.start.day=1&dateRange.start.year=2017&timeGranularity=DAILY&pivot=MEMBER_JOB_TITLE&accounts[0]=urn:li:sponsoredAccount:1234


text:
Q: Passing list as an parameter in DRT template of Drools rule engine I am trying to pass an array/list example- tag =["XYZ","ABC","PQR"] as an parameter to my template to generate drl using the java code and drools template API ObjectDataCompiler.
Template:
template header
tag

template "test for list"
rule "list_@{row.rowNumber}"
when
        $list :  List(${tag})
        $value : String() from $list

then
     System.out.println("yeah from template: "+ $value);
     System.out.println("yeah from template: "+ $list.size());
     System.out.println("yeah from template: "+ $list.get(1));
end
end template

Generate DRL file:
rule "list_0"

when
        $list :  List([XYZ, ABC, PQR])
        $value : String() from $list
then
System.out.println("yeah from template: "+ $value);
System.out.println("yeah from template: "+ $list.size());
System.out.println("yeah from template: "+ $list.get(1));

end

Issue facing: I am unable to access the elements from the list. Is there anything that I am doing wrong?
There is no output printed for any of the System.out.println() why?
I tried evening using the tag[] in the template declaration, and in the template I have something like this "@{tag0}", when the rule is generated I get the values as like this "[XYZ" for the first and "PQR]" the last values.
Can you help me as I am getting an  "[" "]" these square brackets for first and last values respectively?