text:
Q: How to format a numeric column as phone number in SQL I have table in the database with a phone number column. The numbers look like this:
123456789

I want to format that to look like this:
123-456-789

A: I do not recommend keeping bad data in the database and then only correcting it on the output.  We have a database where phone numbers are entered in variously as :

*

*(555) 555-5555

*555+555+5555

*555.555.5555

*(555)555-5555

*5555555555

Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules.  I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.
I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.

A: Solutions that use SUBSTRING and concatenation + are nearly independent of RDBMS. Here is a short solution that is specific to SQL Server:
declare @x int = 123456789
select stuff(stuff(@x, 4, 0, '-'), 8, 0, '-')

A: You can also try this:
CREATE  function [dbo].[fn_FormatPhone](@Phone varchar(30))
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)

set     @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
    Case
      When isNumeric(@Phone) = 1 Then
        case
          when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
          when len(@Phone) = 7  then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
          else @Phone
        end
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
      When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      Else @Phone
    End
return  @FormattedPhone

end
use on it select
(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'

Output will be

A: This should do it:
UPDATE TheTable
SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' +
                  SUBSTRING(PhoneNumber, 4, 3) + '-' +
                  SUBSTRING(PhoneNumber, 7, 4)

Incorporated Kane's suggestion, you can compute the phone number's formatting at runtime.  One possible approach would be to use scalar functions for this purpose (works in SQL Server):
CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10))
RETURNS VARCHAR(12)
BEGIN
    RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' +
           SUBSTRING(@phoneNumber, 4, 3) + '-' +
           SUBSTRING(@phoneNumber, 7, 4)
END

A: You Can Use FORMAT if you column is a number Syntax like
FORMAT ( value, format [, culture ] ) In use like
FORMAT ( @d, 'D', 'en-US' ) or FORMAT(123456789,'###-##-####') (But This works for only SQL SERVER 2012 And After)
In Use Like
UPDATE TABLE_NAME SET COLUMN_NAME = FORMAT(COLUMN_NAME ,'###-##-####')
And
if your column is Varchar Or Nvarchar use do like this
CONCAT(SUBSTRING(CELLPHONE,0,4),' ',SUBSTRING(CELLPHONE,4,3),' ',SUBSTRING(CELLPHONE,7,2) ,' ',SUBSTRING(CELLPHONE,9,2) )
You can always get help from

https://msdn.microsoft.com/en-us/library/hh213505.aspx

A: I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:
CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)

IF (LEN(@PhoneNo) <> 10)
    SET @Formatted = @PhoneNo
ELSE
    SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)

RETURN @Formatted
END
GO

Which you can then use like this:
SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable

It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.
EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)

A: Above users mentioned, those solutions are very basic and they won't work if the database has different phone formats like:
(123)123-4564
123-456-4564
1234567989
etc

Here is a more complex solution that will work with ANY input given:
CREATE FUNCTION [dbo].[ufn_FormatPhone] (@PhoneNumber VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
    DECLARE @Phone CHAR(32)

    SET @Phone = @PhoneNumber

    -- cleanse phone number string
    WHILE PATINDEX('%[^0-9]%', @PhoneNumber) > 0
        SET @PhoneNumber = REPLACE(@PhoneNumber, SUBSTRING(@PhoneNumber, PATINDEX('%[^0-9]%', @PhoneNumber), 1), '')

    -- skip foreign phones
    IF (
            SUBSTRING(@PhoneNumber, 1, 1) = '1'
            OR SUBSTRING(@PhoneNumber, 1, 1) = '+'
            OR SUBSTRING(@PhoneNumber, 1, 1) = '0'
            )
        AND LEN(@PhoneNumber) > 11
        RETURN @Phone

    -- build US standard phone number
    SET @Phone = @PhoneNumber
    SET @PhoneNumber = '(' + SUBSTRING(@PhoneNumber, 1, 3) + ') ' + SUBSTRING(@PhoneNumber, 4, 3) + '-' + SUBSTRING(@PhoneNumber, 7, 4)

    IF LEN(@Phone) - 10 > 1
        SET @PhoneNumber = @PhoneNumber + ' X' + SUBSTRING(@Phone, 11, LEN(@Phone) - 10)

    RETURN @PhoneNumber
END

A: I found that this works if wanting in a (123) - 456-7890 format.
UPDATE table
SET Phone_number =  '(' +
                    SUBSTRING(Phone_number, 1, 3)
                    + ') '
                    + '- ' +
                    SUBSTRING(Phone_number, 4, 3)
                    + '-' +
                    SUBSTRING(Phone_number, 7, 4)

A: Updated @sqiller's function for my purposes
CREATE FUNCTION [toolbox].[FormatPhoneNumber] (
    @PhoneNumber VARCHAR(50),
    @DefaultIfUnknown VARCHAR(50)
)
RETURNS VARCHAR(50)
AS
BEGIN
    -- remove any extension
    IF CHARINDEX('x', @PhoneNumber, 1) > 0
        SET @PhoneNumber = SUBSTRING(@PhoneNumber, 1, CHARINDEX('x', @PhoneNumber, 1) - 1)

    -- cleanse phone number string
    WHILE PATINDEX('%[^0-9]%',@PhoneNumber) > 0
        SET @PhoneNumber = REPLACE(@PhoneNumber,
                SUBSTRING(@PhoneNumber,PATINDEX('%[^0-9]%',@PhoneNumber),1),'')

    -- Remove US international code if exists, i.e. 12345678900
    IF SUBSTRING(@PhoneNumber,1,1) = '1' AND LEN(@PhoneNumber) = 11
        SET @PhoneNumber = SUBSTRING(@PhoneNumber, 2, 10)

    -- any phone numbers without 10 characters are set to default
    IF LEN(@PhoneNumber) <> 10
        RETURN @DefaultIfUnknown

    -- build US standard phone number
    SET @PhoneNumber = '(' + SUBSTRING(@PhoneNumber,1,3) + ') ' +
                SUBSTRING(@PhoneNumber,4,3) + '-' + SUBSTRING(@PhoneNumber,7,4)

    RETURN @PhoneNumber
END

A: If you want to just format the output no need to create a new table or a function. In this scenario the area code was on a separate fields.  I use field1, field2 just to illustrate you can select other fields in the same query:
area  phone
213   8962102

Select statement:
Select field1, field2,areacode,phone,SUBSTR(tablename.areacode,1,3) + '-' + SUBSTR(tablename.phone,1,3) + '-' + SUBSTR(tablename.areacode,4,4) as Formatted Phone from tablename

Sample OUTPUT:
columns: FIELD1, FIELD2, AREA, PHONE, FORMATTED PHONE
data:    Field1, Field2, 213,  8962102,  213-896-2102


text:
Q: On array of nav elements, onmouseenter rotate element (like a wheel) and onmouseleave the wheel stops? I hope the way I've explained it in the question makes sense. Basically I have a fullPage.js nav on the left hand side made up of circles with wheels as background images. I want each nav link to spin/rotate onmouseenter and stop in it's tracks onmouseleave. But I don't want the animation to reset to it's initial state hence why I'm using JS otherwise I would use css animations.
In an ideal world I would also want the link to the current or 'active' section spin continuously and stop where it was (not reset) if another nav link is clicked and the clicked link to start. But I have been on this for a couple of days and will settle for just the basic onmouseenter and onmouseleave functionality at this point which is why you won't see any 'active' element defined in the code below.
Currently I'm just getting the wheel jumping in rotation and not rotating continuously.
Rotating code borrowed from answer here: rotating a div element onmouseenter and stop rotation onmouseleave
Thank you!!!
const fullPageNav = document.getElementById('fp-nav');
const fullPageNavLinks = fullPageNav.getElementsByTagName("a");
const fullPageNavLinksArray = Array.prototype.slice.call(fullPageNavLinks);
let x = 0;
let y;

function start() {
      y = setInterval(rotate, 25);
}

function stop() {
   clearInterval(y);
}

for (let i = 0; i < fullPageNavLinksArray.length; i++) {
  fullPageNavLinksArray[i].addEventListener('mouseenter', start, false);
  fullPageNavLinksArray[i].addEventListener('mouseleave', stop, false);
}

function rotate() {
    for (let i = 0; i < fullPageNavLinksArray.length; i++) {
    fullPageNavLinksArray[i].addEventListener('mouseenter', function() {
        fullPageNavLinksArray[i].style.transform = 'rotate(' + (++x % 360) + 'deg)';
        fullPageNavLinksArray[i].style.transition = 'none';
    });
}
}

                Section%201

                Section%202

                Section%203

A: Thank you to @CBroe for the easier answer. Use animation-play-state/animationPlayState instead of trying to be clever with setInterval.
const fullPageNav = document.getElementById('fp-nav');
const fullPageNavLinks = fullPageNav.getElementsByTagName("a");
const fullPageNavLinksArray = Array.prototype.slice.call(fullPageNavLinks);

fullPageNavLinksArray.forEach(fpnla => {
     fpnla.addEventListener('mouseenter', function() {
        fpnla.classList.add('hovering');
    });
    fpnla.addEventListener('mouseleave', function() {
        fpnla.classList.remove('hovering');
    });
});

@keyframes spin {
    from {
        transform: rotate(0);
    }
    to {
        transform: rotate(360deg);
    }
}

#fp-nav ul li a {
    animation: spin 1s linear infinite;
    animation-play-state: paused;
}

#fp-nav ul li a.active {
    animation-play-state: running!important;
}

#fp-nav ul li a.hovering {
    animation-play-state: running!important;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS Rekognition: Add extra faces of same person I can manage to add an image to AWS Rekognition Collection using the IndexFacesRequest.
However, to improve accuracy I would like to add more images of the same user. How do I let the request know it is the same user?

A: Rekognition does not allow you to provide multiple face images for a single face ID. But you can upload multiple faces of the same person and give them the same ExternalImageId. That's the ID that you typically use to correlate a face match to your person database. When your app later presents a face for matching, Rekognition will return zero or more face matches.


text:
Q: How to create wxWidgets application without external dependencies? Please forgive any non-technical terminology, as I am very new to software development and am still trying to wrap my head around how libraries work and are used.
I am running Linux Mint 17.1 with Cinnamon Desktop.
I downloaded the source code for wxWidgets into a local project folder, and then did as follows (from the base wx directory):

*

*mkdir buildgtk

*cd buildgtk

*../configure --with-gtk

*make

(These are the instructions provided in the install.txt that comes with the wxWidgets library).  The first time I attempted this, I got the error stating that the GTK+ development files could not be found.  I used:

sudo apt-get install libgtk2.0-dev

to get them, and then retried the installation.  This time it worked.  However, during the execution of the "make" command (which resulted in a lot of code passing through the terminal very quickly, so I didn't have time to copy the exact phrases) several items were displayed that looked something like:

(nameOfPackage) from where?  (sys)

or something like that.  For example, I believe it said the PNG package, JPEG package, and some other stuff were being pulled from "sys" which I assume means it is pulling from shared libraries on my computer.
If I want to create a truly portable app, how can I compile wxWidgets library without including all these external dependencies?  Any help is very greatly appreciated as I am still trying to understand all the intricacies of the actual compilation process, object files, etc.

A: You won't be able to link everything completely statically. And unless you link GTK+ itself statically (which is not recommended for technical reasons and also has licensing implications), you also shouldn't link libpng used by GTK statically neither.
For the other libraries, e.g. regex, expat, lib{jpeg,tiff}, you can use --with-xxx=builtin configure option to statically link with the version bundled with wxWidgets.
In practice, the usual solution is to just build on a rather old system as all the newer ones will be compatible with it.
P.S. configure output is stored in config.log, you should also be able to use your terminal scrollback buffer to see the output which went by too fast. And, of course, you can always redirect configure output to tee(1) and then use less to view it more comfortably.


text:
Q: Como puedo agrupar por defecto en odoo? Necesito agrupar por defecto una serie de facturas (por años) y tengo esta vista heredada ya dada:
        <record id="view_account_invoice_filter_globalatac" model="ir.ui.view">
        <field name="name">account.invoice.filter.globalatac</field>
        <field name="model">account.invoice</field>
        <field name="inherit_id" ref="account.view_account_invoice_filter"/>
        <field name="arch" type="xml">
            <group position="inside">
                <filter name="date_invoice_year" string="Año" context="{'group_by':'date_invoice:year'}"/>
            </group>
        </field>
    </record>

He visto por ahí que se puede añadir el context por defecto al action pero no me aparece y no se si tengo que crearlo
<field name="context">{'group_default_date_invoice_year': 1}</field>

Estoy intentando heredar tambien la vista para añadir el context nuevo pero no se que poner en el name del field:
<record model="ir.ui.view" id="view_account_invoice_filter_override">
        <field name="name">account.invoice.tree</field>
        <field name="model">account.invoice</field>
        <field name="inherit_id" ref="account.invoice_tree"/>
        <field name="arch" type="xml">
            <field name="aqui no se que poner" position="attributes">
                <attribute name="context">{"search_default_date_invoice_year":1}</attribute>
            </field>
        </field>
    </record>


text:
Q: How to call a lua function in neovim from autocommand or user_command I'm trying to migrate some old vimscript to lua.   I have a bunch of settings for 'prose' and now have these in .config/nvim/plugin/functions.lua as:
function prose()
vim.o.fdo:append('search')
vim.bo.virtualedit = block
-- more commands
end

Then in prose.lua:
local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
  group = "textedit",
  pattern = {"*.adoc", "*.md", "*.tex"},
  callback = "prose",
})

vim.api.nvim_create_user_command(
  'Prose',
  "call prose()",
  {nargs = 0, desc = 'Apply prose settings'}
)````

But either the autocommand on opening an .adoc file or running :Prose on the command line will return:

````E117: Unknown function: prose````

How can I make my 'prose' function available?

A: Commenting on Icheylus's reply.
By assigning the callback like this
callback = require('functions').prose()

You are trying to assign the output of the function to the callback. This would work if your function returned a function, but your function returns nothing.
Thus a simple tweak is to just remove the ()
callback = require('functions').prose

Or you could even create your function if it is really simple right in the callback of the autocommand.
local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
  group = "textedit",
  pattern = {"*.adoc", "*.md", "*.tex"},
  callback = function()
      vim.o.fdo:append('search')
      vim.bo.virtualedit = block
      -- more commands
  end,
})

A: First, your functions.lua file must be in .config/nvim/lua/ directory.
For your autocommand, modify callback to require functions.lua and function prose:
callback = require('functions').prose()

For your user command:
vim.api.nvim_create_user_command('Prose', function()
    require('functions').prose()
  end,
  {nargs = 0, desc = 'Apply prose settings'}
)


text:
Q: Mvc 6 taghelper asp-action route not working I'm using Areas in Mvc 6 and trying to route to each specific area.
For example I have this:
My controller looks is decorated with a Area and route attribute, like so:
[Authorize]
[Area("Test")]
[Route("[area]/[controller]")]
public class TestController : Controller

Then, I have two HTTPGET methods defined like below:
    public IActionResult Index()
    {
        var model = new TestViewModel();
        return View(model);
    }

    public IActionResult Create()
    {
        var model = new TestViewModel();
        return View(model);
    }

Finally my form looks like this:
    <form asp-route-area="Test" asp-controller="Test" asp-action="Create" asp-antiforgery="false" method="get">
        <input type="submit" value="Generate test"/>
    </form>

When I try to post the form it throws the following:

AmbiguousActionException: Multiple actions matched. The following
  actions matched route data and had all constraints satisfied:
Areas.Test.Controllers.TestController.Index
Areas.Test.Controllers.TestController.Create

You would think that it would bind to my Create method when I define it in the asp-action, but when I check the rendered markup of the form it looks like this:
<form method="get" action="/Test/Test">
        <input type="submit" value="Generate test">
 </form>

My method Create isn't handled, It only renders Test/Test (area/controller).
I've also tried to decorate my method with [Route("Create")] and [HttpGet("Create")] without results.
Am I missing out on something obvious here?

A: If you are using RC1 then you can't use areas in tag helpers.
Areas in tag helpers are supported in RC2 link to issue


text:
Q: Azure DevOps Pull work items in tree level in Excel While publishing into project, I can add Tree Level and keep Parent Child in different columns.
But when I pull the tasks, the parent(epic) child(task) come into single column.
How can I pull parent child in different columns.

List Type: Flat

^ This is giving some hints. But how to change it?
Appreciate any tips. Thanks.

A: Ok got it. Had to edit the query in Azure DevOps.
Earlier the Query was just a single level. Now this is how the query looks:

And this is how the Excel looks:


text:
Q: cannot find symbol class BluetoothPan I cannot import BluetoothPan class (import android.bluetooth.BluetoothPan; does not work). What can I do for importing BluetoothPan?

A: I had some research in the Internet and I learn that SDK has some internal APIs and BluetoothPan class is also internal.
You can use internal APIs,you can reach them by importing external jar. After importing it, you should right click jar file and choose "add as library". After that, you can import BluetoothPan and other internal APIs.
You can download external jars:
https://sites.google.com/site/hippunosource/home/android/androidnohide-apiwo-shi-yongsuru-rifurekushonha-wei-shi-yong
I am sure, it helps you!


text:
Q: Why is this PHP download script failing only on Android I have a simple script that allows someone to download a movie file to their device.  The code works well on everything I've tested except for Andriod.  The Android device butchers the name and the file extension.  It might call the file 2.qt or .bin.  Why is this failing?
<?php

        if(isset($_GET['filename'])) {

            header('Content-Description: File Transfer');
            header('Content-Type: movie/quicktime');
            header('Content-Disposition: attachment; filename="'.basename($file).'"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize("$file"));
            ob_clean();
            flush();
            readfile("$file");
    } else {
        echo "Link: Download Video";
    }
?>

A: Because Android doesn't natively support Quicktime, an Apple technology. It's also very possible that the client used to download this app isn't respecting the filename set on the http envelope as the name it uses to write the file to the filesystem, as there is nothing forcing it to.

A: The problem was that the filenames had spaces, and Android doesn't like that. I removed the spaces and everything is fine.


text:
Q: Phoenix Framework: limit Insert into database to one per day I wish to do a "daily votation lunch" app for the people here at work, using the Phoenix Framework. The model I thought of making was Votation, with each Votation containing many embedded Restaurants schemas (Read here for info on embedded schemas). The model is looking like this:
defmodule WhereToLunch.Votation do
  use WhereToLunch.Web, :model

  schema "votations" do
    embeds_many :restaurants, Restaurant
    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
    |> #TODO: Is it !was_votation_inserted_today() ??
  end

  @doc """
  Returns `true` if a `Votation` object was already inserted in the database
  on the same day the function is called. Returns false otherwise.
  """
  def was_votation_inserted_today() do
    #TODO: How to check if a object was already inserted in the database
    #      on the same day the function is called?
  end
end

defmodule WhereToLunch.Restaurant do
  use Ecto.Model

  embedded_schema do
    field :name, :string
    field :votes, :integer, default: 0
  end
end

What I want to do is to not allow more than one Insert in the table where_to_launch.votations per day. What is the best approach for doing that?

A: I'd add a unique index on the expression date_part('day', inserted_at) and let the database handle uniqueness.
To create the unique index, add the following to a new migration:
def change do
  create index(:posts, ["date_part('day', inserted_at)"], name: "post_inserted_at_as_date", unique: true)
end

and then add a unique_constraint to your model's changeset/2:
def changeset(...) do
  ...
  |> unique_constraint(:inserted_at, name: "post_inserted_at_as_date")
end

The database will now disallow creating 2 posts with the same day in inserted_at:
iex(1)> Repo.insert Post.changeset(%Post{}, %{title: ".", content: "."})
[debug] QUERY OK db=0.3ms
begin []
[debug] QUERY OK db=3.4ms
INSERT INTO "posts" ("content","title","inserted_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" [".", ".", {{2017, 2, 6}, {16, 58, 0, 512553}}, {{2017, 2, 6}, {16, 58, 0, 517019}}]
[debug] QUERY OK db=0.9ms
commit []
{:ok,
 %MyApp.Post{__meta__: #Ecto.Schema.Metadata<:loaded, "posts">,
  comments: #Ecto.Association.NotLoaded<association :comments is not loaded>,
  content: ".", id: 1, inserted_at: ~N[2017-02-06 16:58:00.512553], title: ".",
  updated_at: ~N[2017-02-06 16:58:00.517019],
  user: #Ecto.Association.NotLoaded<association :user is not loaded>,
  user_id: nil}}
iex(2)> Repo.insert Post.changeset(%Post{}, %{title: ".", content: "."})
[debug] QUERY OK db=0.4ms
begin []
[debug] QUERY ERROR db=6.6ms
INSERT INTO "posts" ("content","title","inserted_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" [".", ".", {{2017, 2, 6}, {16, 58, 1, 695128}}, {{2017, 2, 6}, {16, 58, 1, 695138}}]
[debug] QUERY OK db=0.2ms
rollback []
{:error,
 #Ecto.Changeset<action: :insert, changes: %{content: ".", title: "."},
  errors: [inserted_at: {"has already been taken", []}], data: #MyApp.Post<>,
  valid?: false>}


text:
Q: can not connect to Xserver while running python file using pyQT4 via ubuntu service I am trying to execute python file which uses PyQT4
I am running below service file
[Unit]
Description = Test
After=multi-user.target

[Service]
Type=simple
ExecStart = /usr/bin/python3 /home/nvidia/main
Restart=on-abort

[Install]
WantedBy =multi-user.target

this file is located under /lib/systemd/system/test.service and I am starting this service by systemctl start Test
but starting of this service results in an error tagged cannot connect to X Server, failed with result exit-code
I am using the script
#!/usr/bin/python

#################################################################################################################################################

# Author          = Rucha
# Version         = V 2.0.3
# Class           = PR01 OOP
# Module          = pyqt4
# Date            = Jan 02 2021

#################################################################################################################################################
import sys
from PyQt4 import QtGui

######################################################################################################################################

class MainWindow:

    def __init__(self):
        self.vbox = QtGui.QHBoxLayout()

    def Title(self,Window,Name):
        Window.setWindowTitle(Name)

    def window(self):

        app = QtGui.QApplication(sys.argv)
        w = QtGui.QWidget()

        w.setGeometry(800,800,500,500)

        self.Title(w,"Test")

        w.show()
        sys.exit(app.exec_())

MainWindow1 = MainWindow()
MainWindow1.window()

A: Commonly a service dont have the same environment than a normal user who is able to login/start the X environment.
Therefore i guess DISPLAY is not set.
Try this in your service file but make sure it will start after X is already running...
ExecStart = env -i DISPLAY=:0.0 /usr/bin/python3 /home/nvidia/main

Example - User root try running something on X - with and without DISPLAY
#kcalc
qt.qpa.screen: QXcbConnection: Could not connect to display
Could not connect to any X display.
#env -i DISPLAY=:0.0 kcalc
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'

You can check this in an XTerm with and/or without DISPLAY variable.

A: [Unit]
Description = Test
After=multi-user.target

[Service]
Type=simple
Environment="DISPLAY=:0"
Environment="XAUTHORITY=/home/nvidia/.Xauthority"
ExecStart = /usr/bin/python /home/nvidia/main
Restart=on-failure

[Install]
WantedBy =graphical.target

I successfully executed GUI using systemd service using the above directive values


text:
Q: How to disable current and past week dates in react js? I am using calendar in react js. I am trying to disable entire current week. Right now, I am able to set min date min={new Date(2019, 7, 29)} so till today past dates are disabled.But as per requirement,if week already started then user can not select entire current week. i.e today's date is 07/29/2019 so till 08/04/2019 dates should be disable. My week starts from Monday and ends on Sunday.I am also using lodash library if any function of it can be usable to achieve this functionality. TIA.

A: check the current date and alter your starting date accordingly.
let minDate = newDate();
const today = new Date();
if (today.getDay() === 0) { // note: this returns 0-7 with 0 being sunday
  // its sunday, set min date to tomorrow(beginning of your week)
  minDate = minDate.setDate(today.getDate()+1);
} else { // now we know its monday - sat
  const offset = 8 - today.getDay(); // this is the number of days till the next week.
  minDate = minDate.setDate(today.getDate()+offset);
}


text:
Q: iPhone openssl not compiling I am trying to compile the sample iphone openssl created by x2on here:
https://github.com/x2on/OpenSSL-for-iPhone
I get the following errors when trying to compile in Xcode 4.3.3:

Undefined symbols for architecture i386:
 "_MD5", referenced from:

     -[ViewController calculateMD5:] in ViewController.o

 "_SHA256_Init", referenced from:

     -[ViewController calculateSHA256:] in ViewController.o

 "_SHA256_Update", referenced from:

     -[ViewController calculateSHA256:] in ViewController.o

 "_SHA256_Final", referenced from:

     -[ViewController calculateSHA256:] in ViewController.o

ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've been trying to troubleshoot this for a day or so and I am stumped on what to do.
I can provide more information if needed.

A: According to this site, it indicates that you need to link with libcrypto.

A: I just figured out why it wasn't working. I never included the shared libraries in the same folder as my project and never linked the header search paths. After cleaning up my project and rebuilding it recognized the Openssl library and it compiled.


text:
Q: C++ h264 ffmpeg/libav encode/decode(lossless) issues Insights to encode/decode video with ffmpeg h264 (lossless)
So I got something working on the encoding part, encode an avi in 264 however VLC wont play it, however Totem will.
Decoding the same file proves troublesome. (I want the exact same data/frame going in as going out), I get these ;
saving frame   5
Video decoding
[h264 @ 0x1d19880] decode_slice_header error
frame :6
saving frame   6
Video decoding
[h264 @ 0x1d19880] error while decoding MB 15 7, bytestream -27
[h264 @ 0x1d19880] concealing 194 DC, 194 AC, 194 MV errors in I frame
frame :7
saving frame   7
Video decoding
[h264 @ 0x1d19880] decode_slice_header error

and ultimatly this
[H264 Decoder @ 0x7f1320766040] frame :11
Broken frame packetizing
[h264 @ 0x1d19880] SPS changed in the middle of the frame
[h264 @ 0x1d19880] decode_slice_header error
[h264 @ 0x1d19880] no frame!
Error while decoding frame 11

GAME OVER.
Now I suspect that I have to go back to 1. the encoding part, there is problary a good reason VLC wont play it!
I encode like this.
void encode(char *Y,char *U,char *V){
av_init_packet(&pkt);
pkt.data = NULL;    // packet data will be allocated by the encoder
pkt.size = 0;
fflush(stdout);

frame->data[0] = (uint8_t*)Y;
frame->data[1] = (uint8_t*)U;
frame->data[2] = (uint8_t*)V;
frame->pts = ++i;

ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
    fprintf(stderr, "Error encoding frame\n");
    exit (EXIT_FAILURE);
}
if (got_output) {
    printf("Write frame %3d (size=%5d)\n", i, pkt.size);
    fwrite(pkt.data, 1, pkt.size, f);
    av_free_packet(&pkt);
}
}

And the codec is setup like this:
AVCodecID dasd = AV_CODEC_ID_H264;
codec = avcodec_find_encoder(dasd);
c = avcodec_alloc_context3(codec);
c->bit_rate = 400000;
c->width = 320;
c->height = 240;
c->time_base= (AVRational){1,25};
c->gop_size = 10;
c->max_b_frames=1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
av_opt_set(c->priv_data, "preset", "slow", 0);
avcodec_open2(c, codec, NULL);

Since I am going for lossless i am not dealing with delayed frames(is this a correct assumption?)
I may not actually be encoding lossless, it seems like I may have to go with something like
AVDictionary *param;
av_dict_set(&param, "qp", "0", 0);

And then open...
So I guess me questions is these :

*

*What are the correct codec params for lossless encoding (and advice if h264 is a terrible idea in this regard).

*Do I need to handle delayed frames when going for lossless?

*Why is VLC mad at me?

Thanks.

A: *

*To achieve lossless: av_dict_set(&param, "crf", "0", 0);

*Delayed frames (B-frames) has nothing to do with lossless. If you need low-delay, then don't use B-frames.

Some thing is seriously wrong in your encoding. The error "MV errors in I frame" is odd one here, there shouldn't be any MVs in I-frame. It seems the header parsing it-self gone wrong. Please share the bit-stream & more details for VLC failure

A: You're writing raw annexb frames into a file without any container wrapping. Use a container like mp4 or matroska and VLC should be happy.


text:
Q: django comments: how to prevent form errors from redirecting the user to the preview page? Currently, django.contrib.comments sends the user to the preview page if there is any error on the form.
I am using comments in the context of a blog and I would much rather that the user stayed on the page they were on if something went wrong with the submission. As far as I can tell though, this is hard-coded in django.contrib.comments.views.comments.post_comment:
# If there are errors or if we requested a preview show the comment
if form.errors or preview:
    template_list = [
        "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")),
        "comments/%s_preview.html" % model._meta.app_label,
        "comments/preview.html",
    ]
    return render_to_response(
        template_list, {
            "comment" : form.data.get("comment", ""),
            "form" : form,
            "next": next,
        },
        RequestContext(request, {})
    )

Is there any way that I can change this behavior without changing the source code to django.contrib.comments?
Any pointer would be appreciated...
Thanks!

A: Looks like you have two real options:

*

*Write your own view.  Possibly copy that view's code to get started.

*Patch that view to take an extra parameter, such as 'preview_on_errors' which defaults to True but can be overridden.  Contribute the patch back to Django so other people can benefit from it.

A: Yes! There's now a way to customize the Comments app. Good luck!


text:
Q: how can I prevent users form extending/ minimizing TextField Django How can I prevent this from happening

A: A Django TextField is rendered as a HTML textarea.
Looking at this question, you could use style="resize: none;".
If you would like to add that in your views/form (and not in the templates), you could try something like:
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['my_field_name'].widget.attrs['style'] = 'resize: none;'

or if you have a form instance
form.fields['my_field_name'].widget.attrs['style'] = 'resize: none;'


text:
Q: Query error in php It says my syntax has errors, I cant seem to find the error.
$query_admin = 'SELECT * FROM `user_accounts` WHERE `id` =1 AND `name` LIKE ' . $login_user_name . ' AND `password` LIKE ' . $login_password . ';
    $query_user = 'SELECT * FROM `user_accounts` WHERE `name` LIKE ' . $login_user_name . ' AND `password` LIKE ' . $login_password . ';

A: What has phpMyAdmin got to do with this?
You should not end your lines with . '. That's what giving you syntax errors.
Just remove them and you should be fine.

A: try this i think you forget to put ' at the end of your query string :
$query_admin = "SELECT * FROM `user_accounts` WHERE `id` =1 AND `name` LIKE '$login_user_name' AND `password` LIKE ' $login_password'";
$query_user = "SELECT * FROM `user_accounts` WHERE `name` LIKE '$login_user_name ' AND `password` LIKE '$login_password' ";

or this:
$query_admin = "SELECT * FROM `user_accounts` WHERE `id` =1 AND `name` LIKE {$login_user_name} AND `password` LIKE {$login_password}";
$query_user = "SELECT * FROM `user_accounts` WHERE `name` LIKE {$login_user_name} AND `password` LIKE {$login_password}";

A: I didn't test it. Seems to be that you have a ' to many at the end.
'SELECT * FROM `user_accounts` WHERE `id` =1 AND `name` LIKE ' . $login_user_name . ' AND       `password` LIKE ' . $login_password ;


text:
Q: Expanding an existing table in Excel using Apache POI I've got an table in excel with formulae I would like to add data to.

My motivation for this is the fact that tables in excel can dynamically expand to the range of data you add to them, meaning that the formula rows automatically keep up with the amount of data rows.
I'm however having a hard time finding out if this is possible using apache-POI.
One thing I was going to try (see code below) was to expand the AreaReference of the table to cover the data, however both AreaReference(CR,CR2); (as used in this example) and AreaReference(CR,CR2, SpreadsheetVersion.EXCEL2007) (seen in the apache docs) give "constructor is undefined".
No idea what is causing that constructor error as I do have org.apache.poi.ss.util imported.
The other option on the apache docs AreaReference(java.lang.String reference) lets me compile and run but instead gives a "NoSuchMethod" error.
        List<XSSFTable> tableList = spreadSheet.getTables();
        CellReference CR = new CellReference(0, 0);
        CellReference CR2 = new CellReference(5, 2);
        AreaReference my_data_range = new AreaReference(CR,CR2);
        tableList.get(0).setArea(my_data_range);

Any help will be appreciated.

A: The main problem using apache poi until now is that it is not ready to be used without having detailed knowledge about Microsoft Office as such and about the storage of Microsoft Office files. There are many things only half way ready and there are regressions often in new versions (bugs occur again which were solved already).
So your requirement: "Expanding an existing table in Excel using Apache POI" is not possible only simply using apache poi. One must know that Office Open XML files *.xlsx are simply ZIP archives which can be unzipped. And after unzipping we find /xl/tables/table1.xml for storage of the table. This XML we can analyzing and comparing it with XML which was created using Excel's GUI. So we can find problems which results from shortcomings of apache poi. Same is with the sheet's XML in /xl/tables/sheet1.xml.
Also we need to know that apache poi builds on the low level classes of ooxml-schemas. Partially we need using those classes because of the halfway readiness of apache poi. In the following example we need ooxml-schemas-1.4.jar additionally because apache poi's poi-ooxml-schemas-4.0.0.jar has not included org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableFormula until now. Unfortunately there is no documentation about ooxml-schemas public available. So we need downloading the sources and doing javadoc our own.
The following example works for me using apache poi 4.0.0. If you get problems while compiling or running, the reason might be that multiple different versions of apache poi jars are in class path while compile time and/or run time. Do not mix different apache poi versions. Also, as said already, my code needs the full jar of all of the schemas ooxml-schemas-1.4.jar.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;

class ExcelExpandingTable {

 static void addRowToTable(XSSFTable table) {

   int lastTableRow = table.getEndCellReference().getRow();
   int totalsRowCount = table.getTotalsRowCount();
   int lastTableDataRow = lastTableRow - totalsRowCount;

   // we will add one row in table data
   lastTableRow++;
   lastTableDataRow++;

   // new table area plus one row
   AreaReference newTableArea = new AreaReference(
                                 table.getStartCellReference(),
                                 new CellReference(
                                  lastTableRow,
                                  table.getEndCellReference().getCol()
                                 ),
                                 SpreadsheetVersion.EXCEL2007
                                );

   // new table data area plus one row
   AreaReference newTableDataArea = new AreaReference(
                                     table.getStartCellReference(),
                                      new CellReference(
                                       lastTableDataRow,
                                       table.getEndCellReference().getCol()
                                      ),
                                      SpreadsheetVersion.EXCEL2007
                                    );

   XSSFSheet sheet = table.getXSSFSheet();
   if (totalsRowCount > 0) {
    //if we have totals rows, shift totals rows down
    sheet.shiftRows(lastTableDataRow, lastTableRow, 1);

    // correcting bug that shiftRows does not adjusting references of the cells
    // if row 3 is shifted down, then reference in the cells remain r="A3", r="B3", ...
    // they must be adjusted to the new row thoug: r="A4", r="B4", ...
    // apache poi 3.17 has done this properly but had have other bugs in shiftRows.
    for (int r = lastTableDataRow; r < lastTableRow + 1; r++) {
     XSSFRow row = sheet.getRow(r);
     if (row != null) {
      long rRef = row.getCTRow().getR();
      for (Cell cell : row) {
       String cRef = ((XSSFCell)cell).getCTCell().getR();
       ((XSSFCell)cell).getCTCell().setR(cRef.replaceAll("[0-9]", "") + rRef);
      }
     }
    }
    // end correcting bug

   }

   // if there are CalculatedColumnFormulas do filling them to the new row
   XSSFRow row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
   int firstTableCol = table.getStartCellReference().getCol();
   for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
    if (tableCol.getCalculatedColumnFormula() != null) {
     int id = (int)tableCol.getId();
     String formula = tableCol.getCalculatedColumnFormula().getStringValue();
     XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
     cell.setCellFormula(formula);
    }
   }

   table.setArea(newTableArea);

   // correcting bug that Autofilter includes possible TotalsRows after setArea new
   // Autofilter must only contain data area
   table.getCTTable().getAutoFilter().setRef(newTableDataArea.formatAsString());
   // end correcting bug

   table.updateReferences();

 }

 public static void main(String[] args) throws Exception {
  try (Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
       FileOutputStream out = new FileOutputStream("SAMPLE_NEW.xlsx")) {

   XSSFSheet sheet = ((XSSFWorkbook)workbook).getSheetAt(0);
   XSSFTable table = sheet.getTables().get(0);

   addRowToTable(table);

   workbook.write(out);
  }
 }
}

The above was 2018. Now we have 2022.
Using current apache poi 5.2.2 the code may be like follows:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;

class ExcelExpandingTable {

 static XSSFRow addRowToTable(XSSFTable table) {

   int lastTableRow = table.getEndCellReference().getRow();
   int totalsRowCount = table.getTotalsRowCount();
   int lastTableDataRow = lastTableRow - totalsRowCount;
   int firstTableCol = table.getStartCellReference().getCol();

   // we will add one row in table data
   lastTableRow++;
   lastTableDataRow++;

   // new table area plus one row
   AreaReference newTableArea = new AreaReference(
                                 table.getStartCellReference(),
                                 new CellReference(
                                  lastTableRow,
                                  table.getEndCellReference().getCol()
                                 ),
                                 SpreadsheetVersion.EXCEL2007
                                );

   XSSFSheet sheet = table.getXSSFSheet();
   if (totalsRowCount > 0) {
    //if we have totals rows, shift totals rows down
    sheet.shiftRows(lastTableDataRow, lastTableRow, 1);
    //correct all sheet table-reference-formulas which probably got damaged after shift rows
    for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
     if (tableCol.getCalculatedColumnFormula() != null) {
      int id = (int)tableCol.getId();
      String formula = tableCol.getCalculatedColumnFormula().getStringValue();
      int rFirst = table.getStartCellReference().getRow() + table.getHeaderRowCount();
      int rLast = table.getEndCellReference().getRow() - table.getTotalsRowCount();
      int c = table.getStartCellReference().getCol() + id - 1;
      sheet.getWorkbook().setCellFormulaValidation(false);
      for (int r = rFirst; r <= rLast; r++) {
       XSSFRow row = sheet.getRow(r); if (row == null) row = sheet.createRow(r);
       XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
       cell.setCellFormula(formula);
      }
     }
    }
   }

   // if there are CalculatedColumnFormulas do filling them to the new row
   XSSFRow row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
   for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
    if (tableCol.getCalculatedColumnFormula() != null) {
     int id = (int)tableCol.getId();
     String formula = tableCol.getCalculatedColumnFormula().getStringValue();
     XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
     cell.getSheet().getWorkbook().setCellFormulaValidation(false); // see https://bz.apache.org/bugzilla/show_bug.cgi?id=66039
     cell.setCellFormula(formula);
    }
   }

   // copy cell styles to the new row from the row above
   row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
   XSSFRow rowAbove = sheet.getRow(lastTableDataRow - 1); if (row == null) row = sheet.createRow(lastTableDataRow - 1);
   for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
    int id = (int)tableCol.getId();
    XSSFCell cellAbove = rowAbove.getCell(firstTableCol + id - 1);
    if (cellAbove != null) {
     XSSFCellStyle styleAbove = cellAbove.getCellStyle();
     XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
     cell.setCellStyle(styleAbove);
    }
   }

   // set new table area
   table.setArea(newTableArea);

   // update table references
   table.updateReferences();

   return sheet.getRow(lastTableDataRow);

 }

 public static void main(String[] args) throws Exception {
  try (Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
       FileOutputStream out = new FileOutputStream("SAMPLE_NEW.xlsx")) {

   XSSFSheet sheet = ((XSSFWorkbook)workbook).getSheetAt(0);
   XSSFTable table = sheet.getTables().get(0);

   XSSFRow row = addRowToTable(table);

   workbook.write(out);
  }
 }
}

According to FAQ, this code needs poi-ooxml-full-5.2.2.jar instead of ooxml-schemas-1.4.jar now for run using apache poi 5.2.2.
Some bugs are fixed. But there is one new bug when using XSSFCell.setCellFormula when formula contains table references. But XSSFWorkbook.setCellFormulaValidation(false) avoids this.


text:
Q: Microsoft SQL Server 2008 encryption over multiple DB versions I have about 5 clients deployed running different versions of SQL Server 2008 (Some standard, some enterprise, etc.) And I am being tasked with encrypting the data so:

*

*The software we are using can still query the data with decent efficiency.

*DBA's can still get into the data through Management Studio.

*If someone were to obtain a copy of the backup files (being stored on an external HDD), they would be unable to restore the database.

It seemed as if Transparent Data Encryption would be perfect, and I have it functioning, but "This feature is only available in Enterprise and Developer Editions of SQL Server 2008".
I want to have the method of encryption standard over all of the deployed servers.
What is a good method to do so?  Should I simply encrypt the HDDs?
Also, am I missing any other way that a person could potentially get a copy of database (Assuming no passwords are breached)?

A: Requirement 2 requires the data be stored "normally": that is, you can't use encryption in the client for all data. Encrypting data in the client also contradicts requirement 1
Requirement 3 requires the media or the actual backups are encrypted. Encrypting the HDDs isn't reliable because once someone has the actual media then it can normally be unencrypted by a sysadmin.
So, I'd suggest using a 3rd party tool like Red Gate SQL Backup Pro or LiteSpeed by Quest to secure your backups. Points 1 and 2 are satisfied because the on-line database is unchanged


text:
Q: How can I find the version for Heroku's Redis add-on version? We run a Redis add-on on Heroku and I'd like to define the same version in a Puppet provisioning step. Heroku doesn't seem to expose Redis version information anywhere, though. I've tried:

*

*https://devcenter.heroku.com/articles/heroku-redis

*https://devcenter.heroku.com/articles/managing-add-ons

*The add-on's 'Settings' page

I would prefer not to discover this information programmatically like this question's answer.

A: If you're OK with using RedisToGo as in the question you linked to, the information is here:

All new RedisToGo instances run with 2.8.9 as default. If you have an
  existing instance and need your version upgrading then please drop us
  a line and we'll get you set up.


text:
Q: General Formula for an arbitrary Rotation of Sphere I am currently reading F. Klein's book "Lectures on the Icosahedron and the Solution of Equations of the Fifth Degree" and in Part 1, Chapter 2, we desire to deduce a general formula for an arbitrary rotation of sphere. The idea is as follows: first we use stereographic projection to identify $S^2 = \{(\xi,\eta,\zeta)\in \mathbb{R}^3| \quad  \xi^2+\eta^2+\zeta^2=1\}$ with Riemann sphere $\mathbb{C} \cup \{\infty\}$ via the following formula: $z = x + i y = \frac{\xi+i\eta}{1-\zeta}$. If we further identify $\mathbb{C}\cup \{\infty\}$ with $\mathbb{CP}^1$, we can conclude every rotation will be represented by a fractional linear substitution.
Now, given a rotation which fixes antipodal points $(\xi,\eta,\zeta), (-\xi,-\eta,-\zeta)$ , which correspondences to $\frac{\xi+i\eta}{1-\zeta}, -\frac{\xi+i\eta}{1+\zeta}$ in $\mathbb{C}\cup \{\infty\}$  and rotate through an angle $\alpha$ counterclockwise. Above process can be decomposed into two steps: first we move $-\frac{\xi+i\eta}{1+\zeta}$ to $0$ and move $\frac{\xi+i\eta}{1-\zeta}$ to $\infty$, which corresponds to the following fractional linear substitution up to some constant:
$$
C\cdot \frac{z+\frac{\xi+i\eta}{1+\zeta}}{z -\frac{\xi+i\eta}{1-\zeta} }
$$
Then we get our new $0,\infty$ axis and then we rotate our $(\xi',\eta')$-plane (equatorial plane) by an angle $\alpha$ counterclockwise, which correspond to multipyling factor $e^{i\alpha}$.
Suppose $z'$ is the coordinate after the rotation, we must have:
$$
\frac{z'+\frac{\xi+i\eta}{1+\zeta}}{z' -\frac{\xi+i\eta}{1-\zeta} } = e^{i\alpha}\frac{z+\frac{\xi+i\eta}{1+\zeta}}{z -\frac{\xi+i\eta}{1-\zeta} } \quad(*)
$$
The author claimed that if we do the following change of notation:
$$
\xi \sin(\frac{\alpha}{2})=a, \quad \eta \sin(\frac{\alpha}{2})=b, \quad \zeta\sin(\frac{\alpha}{2})=c, \quad \cos(\frac{\alpha}{2})=d,
$$
Then $(*)$ can be rewritten as
$$
z' = \frac{(d+ic)z-(b-ia)}{(b+ia)z+(d-ic)} \quad (**)
$$
That is where I stuck. I think I understand the process of deduction of general rotation formula but I am not sure how to get the simple form $(**)$. Now the problem is purely elementary and I try to verify $(**)$ by brute force but it doesn't seem to be a correct way . I guess it will involve with some trigonometric formulas to simplify the computation. Could you please offer me some suggestions on how to start from $(*)$ to derive $(**)$? Thank you in advance.

A: Letting $A:=\frac{\xi+i\eta}{1+\zeta}$ and $B:=\frac{\xi+i\eta}{1-\zeta}$ we obtain from $(*)$:
\begin{align*}
e^{-i\frac{\alpha}{2}}\ \frac{z^{\prime}+A}{z^{\prime}-B}&=e^{i\frac{\alpha}{2}}\ \frac{z+A}{z-B}\\
e^{-i\frac{\alpha}{2}}\left(z^{\prime}+A\right)\left(z-B\right)&=e^{i\frac{\alpha}{2}}(z+A)\left(z^{\prime}-B\right)\\
e^{-i\frac{\alpha}{2}}\left(zz^{\prime}+Az-Bz^{\prime}-AB\right)
&=e^{i\frac{\alpha}{2}}\left(zz^{\prime}-Bz+Az^{\prime}-AB\right)\tag{1}\\
\end{align*}
Extracting $z^{\prime}$ from (1) we obtain
\begin{align*}
\color{blue}{z^{\prime}}&=\frac{\left(Be^{i\frac{\alpha}{2}}+Ae^{-i\frac{\alpha}{2}}\right)z
+AB\left(e^{i\frac{\alpha}{2}}-e^{-i\frac{\alpha}{2}}\right)}
{\left(e^{i\frac{\alpha}{2}}-e^{-i\frac{\alpha}{2}}\right)z+Ae^{i\frac{\alpha}{2}}+Be^{-i\frac{\alpha}{2}}}\\
&\,\,\color{blue}{=\frac{\left(Be^{i\frac{\alpha}{2}}+Ae^{-i\frac{\alpha}{2}}\right)z
+2iAB\sin\left(\frac{\alpha}{2}\right)}
{2i\sin\left(\frac{\alpha}{2}\right)z+Ae^{i\frac{\alpha}{2}}+Be^{-i\frac{\alpha}{2}}}}\tag{2}
\end{align*}
Since we want to derive (**):
\begin{align*}
z' = \frac{(d+ic)z-(b-ia)}{(b+ia)z+(d-ic)}
\end{align*}
and the coefficient of $z$ of the denomintor in (2) is $2i\sin\left(\frac{\alpha}{2}\right)$ instead of $b+ia$, we consequently expand numerator and denominator of (2) with
\begin{align*}
\frac{b+ia}{2i\sin\left(\frac{\alpha}{2}\right)}
\end{align*}
We calculate the constant part of the denominator of (**) from (2) and obtain
\begin{align*}
&\color{blue}{\frac{b+ia}{2i\sin\left(\frac{\alpha}{2}\right)}}
\color{blue}{\left(Ae^{i\frac{\alpha}{2}}+Be^{-i\frac{\alpha}{2}}\right)}\\
&\quad=\frac{b+ia}{2i\sin\left(\frac{\alpha}{2}\right)}
\left(\frac{a+ib}{\sin\left(\frac{\alpha}{2}\right)+c}\,e^{i\frac{\alpha}{2}}
+\frac{a+ib}{\sin\left(\frac{\alpha}{2}\right)-c}\,e^{-i\frac{\alpha}{2}}\right)\tag{3}\\
&\quad=\frac{a^2+b^2}{2\sin\left(\frac{\alpha}{2}\right)}
\left(\frac{e^{i\frac{\alpha}{2}}}{\sin\left(\frac{\alpha}{2}\right)+c}
+\frac{e^{-i\frac{\alpha}{2}}}{\sin\left(\frac{\alpha}{2}\right)-c}\right)\\
&\quad=\frac{1}{2\sin\left(\frac{\alpha}{2}\right)}
\left(e^{i\frac{\alpha}{2}}\left(\sin\left(\frac{\alpha}{2}\right)-c\right)
+e^{-i\frac{\alpha}{2}}\left(\sin\left(\frac{\alpha}{2}\right)+c\right)\right)\tag{4}\\
&\quad=\frac{e^{i\frac{\alpha}{2}}+e^{-i\frac{\alpha}{2}}}{2}
-\frac{c}{\sin\left(\frac{\alpha}{2}\right)}\frac{e^{i\frac{\alpha}{2}}-e^{-i\frac{\alpha}{2}}}{2}\\
&\quad=\cos\left(\frac{\alpha}{2}\right)-ic\\
&\,\,\quad\color{blue}{=d-ic}
\end{align*}
according to the claim. The coefficients of the numerator in (**) can be calculated similarly.
Comment:

*

*In (3) we use
\begin{align*}\xi \sin\left(\frac{\alpha}{2}\right)=a,\
\eta \sin\left(\frac{\alpha}{2}\right)=b,\
\zeta \sin\left(\frac{\alpha}{2}\right)=c,\
\cos\left(\frac{\alpha}{2}\right)=d\text{.}
\end{align*}

*In (4) we use $a^2+b^2+c^2=\sin^2\left(\frac{\alpha}{2}\right)$ since $\xi^2+\eta^2+\zeta^2=1$. This implies \begin{align*}
a^2+b^2&=\sin\left(\frac{\alpha}{2}\right)^2-c^2\\
&=\left(\sin\left(\frac{\alpha}{2}\right)-c\right)\left(\sin\left(\frac{\alpha}{2}\right)+c\right)
\end{align*}


text:
Q: Problems using AWS S3 assembly with C# I am trying to use AWS S3 library to upload files to S3.
The issue is, when I add the S3 Library and call its function, it gives me the error below:

An unhandled exception of type 'System.MissingMethodException' occurred in AnotherS3Test.exe
Additional information: Method not found: 'System.IAsyncResult Amazon.Runtime.SharedInterfaces.ICoreAmazonS3.BeginDelete(System.String, System.String, System.Collections.Generic.IDictionary`2, System.AsyncCallback, System.Object)'.

I am using Visual Studio 2015 and get the S3 packages using NuGet Package Manager. Everything works fine if I change the version of the app to use .Net 3.5, but as soon as I change the version to 4, 4.5 or 4.6, I start getting the error above even if I create a new project and get the S3 assembly again from NuGet Package Manager to make sure the app uses the correct AWS libraries (compatible with the current version of .Net selected).
Can someone please help? maybe its something basic I've missed

A: My guess is you somehow got the .NET 3.5 version of the AWS SDK for .NET installed into the GAC. .NET will pick the GAC version versus your directly referenced version. It is the evil of the GAC. This might help inspect your GAC. https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-view-the-contents-of-the-gac

A: This error as here says https://learn.microsoft.com/en-us/dotnet/api/system.missingmethodexception?view=netframework-4.8  means you are accessing something does not exist.
1- Did you add AWS SDK for NET4.5 ? there are two folders in AWS SDK if you see,
2- my general suggestion is to move to 2019 i had few issues with 17 even.


text:
Q: Empty term document matrix I seem to run into a problem whenever I try to inspect my freq. words and associations.
When I make the tdm I get this info:
TermDocumentMatrix
I can see I have plenty of terms to use, in plenty of documents.
However!
When I try to inspect the content of "tdm", I get this info:
Inspecting the TDM
Howcome the tdm all of a sudden is empty?
Hope someone can help
tweets <- userTimeline("RDataMining", n = 1000)

(n.tweet <- length(tweets))
tweets[1:3]

#convert tweets to a data frame
tweets.df <- twListToDF(tweets)
dim(tweets.df)

##Text cleaning
library(tm)
#build a corpus and specify the source to be a character vector
myCorpus <- Corpus(VectorSource(tweets.df$text))

#convert to lower case
myCorpus <- tm_map(myCorpus, content_transformer(tolower))

#remove URLs
removeURL <- function(x) gsub ("http[^[:space:]]*","",x)
myCorpus <- tm_map(myCorpus,content_transformer(removeURL))

#remove anything other than English letters or space
removeNumPunct <- function(x) gsub("[^[:alpha:][:space:]]*","",x)
myCorpus <- tm_map(myCorpus,content_transformer(removeNumPunct))

#remove stopwords + 2
myStopwords <- c(stopwords('english'),"available","via")
#remove "r" and "big" from stopwords
myStopwords <- setdiff(myStopwords, c("r","big"))
#remove stopwords from corpus
myCorpus <- tm_map(myCorpus,removeWords,myStopwords)
#remove extra whitespace
myCorpus <- tm_map(myCorpus, stripWhitespace)

#keep a copy of corpus to use later as a dictionary for stem completion
myCorpusCopy <- myCorpus

#stem words
library(SnowballC)
myCorpus <- tm_map(myCorpus,stemDocument)
stemCompletion2 <- function(x,dictionary) {
x <- unlist(strsplit(as.character(x),""))

#because stemCompletion completes an empty string to a word in dict. Remove empty string to avoid this

 x <- x[x !=""]
 x <- stemCompletion(x, dictionary = dictionary)
 x <- paste (x,sep = "",collapse = "")
 PlainTextDocument(stripWhitespace(x))
}

myCorpus <- lapply(myCorpus, stemCompletion2, dictionary = myCorpusCopy)
myCorpus <- Corpus(VectorSource(myCorpus))

#count freq of "mining"
miningCases <- lapply(myCorpusCopy,
                  function(x) {grep(as.character(x),pattern = "\\<mining")})
sum(unlist(miningCases))

#count freq of "miner"
miningCases <- lapply(myCorpusCopy,
                  function(x) {grep(as.character(x),pattern = "\\<miner")})
sum(unlist(miningCases))

#count freq of "r"
miningCases <- lapply(myCorpusCopy,
                  function(x) {grep(as.character(x),pattern = "\\<r")})
sum(unlist(miningCases))

#replace "miner" with "mining"
myCorpus <- tm_map(myCorpus,content_transformer(gsub),
               pattern = "miner", replacement = "mining")

tdm <- TermDocumentMatrix(myCorpus, control = list(removePunctuation =    TRUE,stopwords = TRUE))
tdm

##Freq words and associations
idx <- which(dimnames(tdm)$Terms == "r")
inspect(tdm[idx + (0:5), 101:110])

#inspect frequent words
(freq.terms <- findFreqTerms(tdm, lowfreq = 15))
term.freq <- rowSums(as.matrix(tdm))
term.freq <- subset(term.freq,term.freq >= 15)
df <- data.frame(term = names(term.freq), freq = term.freq)

A: I've been using the following Twitter query to test your code:
tweets = searchTwitter("r data mining", n=10)

and I think the problem is with your function stemCompletion2, which should look something like this:
stemCompletion2 <- function(x,dictionary) {
  x <- unlist(strsplit(as.character(x)," "))
  print("before:")
  print(x)

  #because stemCompletion completes an empty string to a word in dict. Remove empty string to avoid this
  x <- x[x !=""]
  x <- stemCompletion(x, dictionary = dictionary)
  print("after:")
  print(x)
  x <- paste(x, sep = " ")
  PlainTextDocument(stripWhitespace(x))
}

The modifications are as follows: before you had
x <- unlist(strsplit(as.character(x),""))

which was creating a list with all the characters of in each of the documents, and I've modified it to
x <- unlist(strsplit(as.character(x)," "))

to create a list of words. Similarly, when recomposing your documents, you where doing
x <- paste (x,sep = "",collapse = "")

which was creating the long strings you mention in your post, and I've modified it to:
x <- paste(x, sep = " ")

to recompose the words.
One example of the completions would be for my data:
[1] "before:"
 [1] "rt"             "ebookdealalert" "r"              "datamin"        "project"        "learn"          "data"           "mine"
 [9] "realworld"      "project"        "book"           "solv"           "predict"        "model"
[1] "after:"
               rt    ebookdealalert                 r           datamin           project             learn              data              mine
             "rt" "ebookdealalerts"               "r"      "datamining"        "projects"           "learn"            "data"                ""
        realworld           project              book              solv           predict             model
      "realworld"        "projects"            "book"           "solve"      "predictive"        "modeling"

After that step, you may be able to work with TermDocumentMatrix as expected.
Hope it helps.


text:
Q: Украшения для баннера ssh. SSH motd Возможно моя проблема покажется тривиальной, но я не могу понять по какой причине cowsay не может вывести цитаты из fortune в баннер при входе по ssh, при том что сама корова рисуется и выводит, описанную в скрипте информацию, но не может подтянуть fortune и переменную $USER ?
Однако, когда этот-же скрипт просто вызывается из оболочки (в моем случае bash), то такой проблемы не возникает и даже сохраняется форматирование, т.е облако с фразой отображается ровно, ее края образуют ровные столбцы, а не разъезжаются на разные расстояния.
Вот исходный текст моего скрипта
#!/bin/sh
# (1)
#!/bin/bash
# (2)
# (1) if this text is update-motd.d's scripts (2) if this text is normal
# bash script
#i3-nagbar -t warning -m 'Проверка вызова нагбара через скрипт' -b 'Закрыть'
curHour=$(date "+%H")
if [ $curHour -lt 12 -a $curHour -ge 0 ]; then curTime="Доброе утро"
elif [ $curHour -lt 17 -a $curHour -ge 12 ]; then curTime="Добрый день"
else curTime="Добрый вечер"
fi

clever=`/usr/games/fortune`

#System uptime
uptime=`cat /proc/uptime | cut -f1 -d.`
Days=$((uptime/60/60/24))
Hours=$((uptime/60/60%24))
Mins=$((uptime/60%60))
Mem1=`free -t -m | grep "buffers/cache" | awk '{print $3" MB";}'`
Mem2=`free -t -m | grep "Mem" | awk '{print $2" MB";}'`
Procs=`ps aux | wc -l`
IP=`hostname --all-ip-addresses`

if [ $curHour -lt 12 -a $curHour -ge 0 ]; then echo $curTime $USER\
" с момента запуска прошло $Days дней $Hours часов $Mins минут(ы)" | cowsay -b
elif [ $curHour -lt 17 -a $curHour -ge 12 ]; then printf "$curTime $USER\n
 с момента запуска прошло $Days дней $Hours час(ов) $Mins минут(ы)\n  $Procs процессов запущено\n
 Адресс хоста: $IP\n  $clever"| cowsay
else echo $curTime $USER | cowsay -d
fi

echo ля-ля-ля
echo $Mem1
echo $Mem2

Примечание.
Пакеты cowsay и fortune (fortunes-rus) установлены соответственно.
Везде в предложениях вида :

if [ ... ]; then ...

используется функция printf.
Данный скрипт запускается в качестве баннера из директории /etc/update-motd.d/{название-скрипта}
Дистрибутив raspbian-buster


text:
Q: Edit a unique field used as foreignkey in Django I have two models, one Price and Market:
class Market(models.Model):
    market_name = models.CharField(max_length=3, unique=True)

class Price(models.Model):
    market = models.ForeignKey(Market, on_delete=models.CASCADE, to_field="market_name")

I want to be able to edit the market_name field on the Market model and have the subsequent Price objects updated without causing errors.
update or delete on table "appname_market" violates foreign key constraint "appname_price_market_id_5f75a816_fk_appnames" on table "appname_price"
DETAIL:  Key (market_name)=(Cute Martket Name) is still referenced from table "appname_price".

Pointing them on the pk is one the solution, but I want to stick to using market_name as foreignkey for a reason. How would you do that ?
I imagined a method for pre_save :
@receiver(pre_save, sender=Market)
def update_market_field(sender, instance, *args, **kwargs):
    try:
        obj = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        pass  # Object is new, so field hasn't technically changed, \
              # but you may want to do something else here.
    else:
        if not obj.market_name == instance.market_name:  # Field has changed
            Price.objects.filter(market=obj.market_name).update_or_create(market=instance)

But this still producing errors because actually the Market object hasn't been saved yet. A half solution also is to delete all Prices with that obj.martket_name in this pre_save method, and I have seen that it effectively update the unique field but ...

A: Maybe you can override the save method to achieve this:
class Market(...):

   def save(self, *args, **kwargs):
      prices = None
      if self.pk:
           obj = self.__class__.objects.get(pk=self.pk)
           if obj.market_name != self.market_name:
               prices = obj.price_set.all()
      super().save(*args, **kwargs)
      if prices is not None:
           prices.update(market_id=self.market_name)


text:
Q: Display alert before deleting I got an action-link passing an ID to a Deletemethod in my controller.
@Html.ActionLink("Delete", "DeleteContent", new { xid = item.Id })

I would like som kind of "confirm action"-alert that gets triggered when the link is clicked.
Lets say the alert has two options, "Delete" and "Cancel".
If the user hits cancel I dont want the method to excecute.
Any tips on how to accomplish that?

A: You can add a confirm box
@Html.ActionLink("Delete", "DeleteContent", new { xid = item.Id,onclick="return confirm('Are you sure you want to delete?');" })


text:
Q: How can I tell if a Dialog is being Stopped by it closing or by the application being minimized? I implement a dialog that should update its calling activity when it is closed. However, I've found that it is updating the activity when the entire application is minimized, which is not acceptable for my purposes.
The update to the activity occurs in the dialog's onStop() method, which is called either when the dialog is closed or the application itself is stopped. How can I handle things differently based on whether the dialog was closed or the application itself was stopped?  Thanks!
For some more context, here is the piece of my dialog's onStop(), which resumes the timer of the underlying activity. I don't want the timer resumed if the user is leaving the app.
if (activity instanceof QuizActivity) {
            if( ((QuizActivity) activity).getTimer() == null) {
                ((QuizActivity) activity).resumeTimer();
            }
        }

A: I think I just solved this. My Dialog's onStop() was being called manually from my Activity's onStop(). So I put a call to my pauseTimer() method after calling the dialog's onStop() in the activity's onStop(). Effectively, the dialog is resuming the timer and then the activity is immediately pausing it again as part of its onStop() method. It doesn't feel very clean, but hopefully it at least holds together.


text:
Q: Rust overflowing shift left I'm trying to combine 4 bytes into a u32, and the compiler telling me that the shift has overflown.
This is my code:
pub fn get_instruction(file: &[u8], counter: usize) {
    let ins = u32::from(file[counter] << 24)
        | u32::from(file[counter + 1] << 16)
        | u32::from(file[counter + 2] << 8)
        | u32::from(file[counter + 3]);
    println!("{:x}", ins);
}

A: You got your operator priority and cast wrong:
pub fn get_instruction(file: &[u8], counter: usize) {
    let ins = u32::from(file[counter]) << 24
        | u32::from(file[counter + 1]) << 16
        | u32::from(file[counter + 2]) << 8
        | u32::from(file[counter + 3]);
    println!("{:x}", ins);
}

You were casting after trying to shift a u8 24 bits, which was your problem.

A: It's not necessary to twiddle the bits yourself – you can use the function u32::from_be_bytes() instead:
pub fn get_instruction(file: &[u8], counter: usize) {
    let ins_bytes = <[u8; 4]>::try_from(&file[counter..counter + 4]).unwrap();
    let ins = u32::from_be_bytes(ins_bytes);
    println!("{:x}", ins);
}


text:
Q: PHP mail function (2) Hi I am using php mail function to send mails from my contact section. But the mails are not geting me. If i use gmail id its working but if I use any other email ids like hr@sbnphpjobs.com not geting.

A: It's better to use PHPMailer or Swift Mailer in combination with a smtp server (e.g. gmail). Mail send from php (mail()) is often seen as spam by a lot of spamfilters...

A: Your smtp server might only send email to a white list of domain name. I had the same issue with a customer smtp. We bought another solution to solve it.

A: Did you get a chance to check mail logs? There can be a hint to why mails are not going through. If you are running your own server, then a dedicated IP will make sure that you are not having an ip that is blocked by anti spam databases.


text:
Q: Problem using JS ES6 promises in React - TypeError: Cannot read property 'then' of undefined I import the function getWeather from another .js file I've written. The result is a json blob. I've verified that I get the JSON blob back, but when I try to call the getWeather function and use .then to wait for a response and set my state I get a TypeError.
getWeather(parseFloat(lat),parseFloat(long)).then((data) =>{
  this.setState({weatherType: data.currently.icon, temp: data.currently.temperature})
  return data
}).catch((error) => {
  console.log(error.message);
})

The getWeather function is here:
export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          return data.json();
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.log(error);
        });
    }

A: You need to return fetch() in order to make the promise accessible from another function. Also, I would probably handle logging and errors in the calling function as when you log the data you are no longer returning it.
export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      return fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          if (!data.ok) { return new Error('custom error message here') }
          return data.json();
        });
    }

A: You are most probably return that blob from the getWeather function without creating a Promise.
Try something like this:
function getWeather() {
// create blob as usual
  return Promise.resolve(blob);
}

or if you already inside a then you must just retrun something from it:
      fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          return data.json();
        })
        .then(res => {
          console.log(res);

          retrun res; // return something

        })
        .catch(error => {
          console.log(error);
        });
    }


text:
Q: In how many ways can a committee of $5$ members be formed from $4$ women and $6$ men such that at least $1$ woman is a member of the committee.
In how many ways can a committee of $5$ members be formed from $4$ women and $6$ men such that at least $1$ woman is a member of the committee.

I know that the correct answer is:
$\binom{10}{5} - \binom{6}{5} = 246$
In hindsight (after reading the solution guide), that all makes sense (All Groups - Just those with $5$ Men). However, I can't figure out why my original solution doesn't work. I would choose $1$ of the women, and then choose any $4$ from the remaining $9$ people. This gives us:
$\binom{4}{1}\binom{9}{4} = 504$
Can anyone explain why that doesn't work? Thank you for your help!

A: Your solution counts twice the configuration with two women, three times the configurations with $3$ women, etc.
Imagine that the question was to form a committee with four women. Your solution would yield "choose one woman (4 options) and then there are ${3\choose 3}=1$ way to choose the remaining three, so four ways altogether (where the answer is obviously $1$: take all four women).

A: \begin{array}{c|c|c|c|c|c|c}
4 \mbox{ Women}&6\mbox{ Men}&\mbox{Number of Selections}\\\hline
1&4&^4C_1\times^6C_4=60\\
2&3&^4C_2\times^6C_3=120\\
3&2&^4C_3\times^6C_2=60\\
4&1&^4C_4\times^6C_1=6\\
\
\\
\end{array}
Now the total number of ways of forming a committee of $5$ members with at least $1$ women is $60+120+60+6=246$ ways.

A: If you want to use that method it would be:
$$^9C_4 + ^8C_4 + ^7C_4 + ^6C_4 = 246$$
Otherwise you are double counting.

A: The number of groups with exactly $k$ of the four women and $5 - k$ of the six men is
$$\binom{4}{k}\binom{6}{5 - k}$$
so the number of groups with exactly $k$ women is
\begin{align*}
\sum_{k = 1}{4} \binom{4}{k}\binom{6}{5 - k} & = \binom{4}{1}\binom{6}{4} + \binom{4}{2}\binom{6}{3} + \binom{4}{3}\binom{6}{2} + \binom{4}{4}\binom{6}{1}\\
& = 4 \cdot 15 + 6 \cdot 20 + 4 \cdot 15 + 1 \cdot 6\\
& = 60 + 120 + 60 + 6\\
& = 246
\end{align*}
as you found more easily by subtracting the number of groups of five people with no women from the number of groups of five people that can be formed without restriction.
Suppose the women are Angela, Brenda, Charlotte, and Denise and that the men are Edward, Frank, George, Henry, Ivan, and Jeffrey.  By designating a particular woman as the representative of the women in the group, you count each group the number of times as the number of women in the group.  For instance, consider the group consisting of the four women and Edward.  You count it in each of the following ways:
\begin{array}{c c}
\text{designated woman} & \text{additional members of the group}\\ \hline
\text{Angela} & \text{Brenda, Charlotte, Denise, Edward}\\
\text{Brenda} & \text{Angela, Charlotte, Denise, Edward}\\
\text{Charlotte} & \text{Angela, Brenda, Denise, Edward}\\
\text{Denise} & \text{Angela, Brenda, Charlotte, Edward}
\end{array}
Notice that
$$\color{red}{\binom{1}{1}}\binom{4}{1}\binom{6}{4} + \color{red}{\binom{2}{1}}\binom{4}{2}\binom{6}{3} + \color{red}{\binom{3}{1}}\binom{4}{3}\binom{6}{2} + \color{red}{\binom{4}{1}}\binom{4}{4}\binom{6}{1} = 504$$
where the factor $\color{red}{\binom{k}{1}}$ is the number of ways of designating one of the $k$ women in the group as the representative of the women in the group.


text:
Q: Design Decision - WCF Service or Shared Class Library (DLL) I am presently designing a message queue system that will be used by various applications and am having a difficult time trying to decide whether to use WCF to provide the services or use a shared class library (DLL) and deploy the DLL with the clients.
For some additional information:
•   The queue is stored in a SQL database.
•   We expect to have approximately 3-7 different applications/clients using this message queue system.
•   The clients/applications may or may not run all on one machine.
•   We do not expect a heavy load of messages being queued on a daily basis (approx 1000-10000 per day (gross estimates btw))
•   Somewhat "mission critical" – several clients/applications cannot do its job if this service is unavailable.
•   Everything operates within the corporate network – no access to Internet required.
I have given some though to the pros and cons for each decision:
WCF Service
Pros:
•   Can update the logic in the Queue system without having to update the clients
•   Room for scalability – but most likely not going to be an issue.
Cons:
•   More difficult to diagnose/debug
•   More effort required when deploying
•   Queue System unavailable if the service is down (unless we cluster/farm)
Shared Class Library (DLL)
Pros:
•   Easier to debug
•   Easier development efforts
•   Only have to ensure that the DB is available – no dependence on another service/machine.
Cons:
•   Deployment headaches when we make updates to the DLL – we may forget to update all the applications that depend on the DLL.
If anyone can provide more arguments for a solution – that would be helpful! If you have an opinion to what you believe is the best direction, please do tell! I'll appreciate any input that will help make me a decision.
Thanks for your time,
Adrian

A: You can do both:

*

*Implement a class library that encapsulates all the functionality you wish to expose. Consumers that wish that level of control can reference the library directly.

*Develop a WCF service that only acts as a Remote Facade for the class library. It would only expose and translate the class library into DTOs/messages, and contain no logic in itself.

In other words, the class library is your Domain Model, and the service is just a thin Facade in front of that model. That's the way any WCF service should be developed in any case.

That said, I you must choose one or the other, I'll try to add my own thought to yours (which I find most reaonable).
One disadvantage of WCF that you forgot is that it does add some processing overhead because it must serialize and deserialze messages.
Even so, selecting the best model is not only about counting the number of bullets in each pro/con section, as each bullet has different weights.
Without knowing your exact situation and requirements, I would still consider the deployment/versioning issue that relates to direct use of a class library to be a very strong argument against that strategy.
A web service interface will allow you to vary service and each client independently of each other as long as the contract remains stable. That could also be made possible with a class library, but is more difficult.
An interoperable web service interface also gives you a better ability to grow and respond to new business opportunities, as the clients are not constrained to .NET applications. You may have only .NET applications today, but are you sure it will stay that way forever?
If, on the other hand, you decide to go the class library route, make sure to have each client consume abstract base classes, because that will provide you with the most flexible options of changing the implementation without breaking existing clients.
Given the information you provided, I don't think there's a clear-cut winner here. I lean slightly towards WCF despite the added complexity, because I consider the flexibility it provides gives you better options for responding to unforseen changes.


text:
Q: Change parents theme functionality All I need to change is __( 'Expiry (MM/YY)', 'woocommerce' ) to Expiration Date .
I have tried creating a file just like it to see if it overriders the parents theme /wp-content/themes/customizr-child/woocommerce/includes/abstracts/abstract-wc-payment-gateway.php but that didn't work.
public function credit_card_form( $args = array(), $fields = array() ) {

    wp_enqueue_script( 'wc-credit-card-form' );

        ...

    id ) . '-card-expiry">' . __( 'Expiry (MM/YY)', 'woocommerce' ) . ' *

        ...
    );
}

How do I change plugins functionality (just msg) with out hard coding the plugin itself

A: You can use gettext filter to translate string with text domain.
function __text_string_translate( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Expiry (MM/YY)' :
        $translated_text = __( 'Expiration Date', 'woocommerce' );
        break;
    }
    return $translated_text;
}
add_filter( 'gettext', '__text_string_translate', 20, 3 );


text:
Q: Secure db queries in single page web app I'm creating single page web app with ArangoDB for storage. Arango provides awesome ways for accessing and manipulating data. One of them is classic JS API. It would be easy to write straightforward DB queries in client side JS which would be direct queries for DB. So no server application in middle.
Of course, this is really unsecure pattern. So I should write some sort of REST-full API service that queries data from server via URL and later server queries the DB. But this is really inconvenient, since I'd need to write two or three times more code (first query for my server, second query for DB, and perhaps some translator between the two queries). Also, I think that API calls for my server would look almost same as API calls for DB.
I don't want to go for full abstraction since the app should be complex and there would be a lot of types of API request, which would only bring bugs and eat more time.
So what is the best way for requesting data in client app from DB in terms of, firstly, security and, secondly, ease of coding?

A: I'd really suggest to write REST API calls (or generally URL calls) to access your data. Anything what run on the client side or any traffic from the client can be accessed and manipulated. That comes with authentication and SQL calls themselves.
What you want to secure? DB client authentication? If you encrypt it, you need to decrypt it on the client side. SQL calls - if you build and transmit them, the client could manipulate them to get / update ANY data with ANY values. Really no easy way around..
So - to be safe - stick to the patterns here..

A: I found a GraphQL with Relay by Facebook which solves this problem best.


text:
Q: word-wrap not working on a floating text Let's say I have this.

lalalala

css:
#lala
{
   float:left;
   word-wrap:break-word;
}

if the text inside #lala is big, it will look like this.
|                              |
|                              |
| lalalalalalalalalalalalalala | lalalalalala <-- these won't be show.
|                              |
|                              |

If I remove float:left; this will be the result.
|                              |
|                              |
| lalalalalalalalalalalalalala |
| lalalalalala                 |
|                              |

How can I have the second result while still using float?

A: give the element a fixed width so we know where to break the word:
#lala
{
float:left;
word-wrap:break-word;
width:?px;
}

The word-wrap:break-word property should only apply if the element has a visual rendering, is an inline element with explicit height/width, is absolutely positioned and/or is a block element.


text:
Q: How many irrationals $x$ appear infinitely often in this set of open intervals? The setup: Let $q_1,q_2,q_3,\dots$ be an enumeration of the rationals in the unit interval $I=[0,1]$.  Then let $K_i=\{q_j\mid j \le i\}$, and $K=\bigcup_i{K_i} = \{q_i\} = \mathbb{Q}\cap I$.
Define a set of open intervals $S=\bigcup_i{S_i}$ where $S_i = \{(q-2^{-i},q+2^{-i})\mid q \in K_i\}$.
For any $x \in I$ count the number of elements of $S$ for which $x$ is a member:
$$ \#(x) = |\{s \mid  x \in s \in S\}|$$
Clearly $\#(x)=\infty$ for any rational $x$, but what about irrational $x$?
My question: for 'how many' irrational $x$ does $\#(x)=\infty$?  The categories 'none', 'at least one', 'most', 'all' are good enough here.
Bonus question: can we construct or otherwise characterize such points $x$?
Motivation: We know that there is no sequence of continuous functions that pointwise converges to $\chi_K$, the characteristic function of the rationals in $I$.  This has been asked and answered on this site at Exists continuous $f_n: [0,1] \to \mathbb{R}$ that converges pointwise, as $n \to \infty$, to $\chi_\mathbb{Q}$? and Existence of a sequence of continuous functions convergent pointwise to the indicator function of irrational numbers.  There is also an elementary proof at https://math.stackexchange.com/a/1444407/1257.
Nevertheless, in the spirit of squaring the circle, let's try to build such a sequence and then troubleshoot.  The construction is inspired by this article, but seems to be fairly common.
The members of the sequence are
$$
f_i(x) = \max(0,1-2^i d(x,K_i)),
$$
where $d(x,A)$ is the distance between the point $x$ and the nearest point in $A$.
Note that the support of $f_i$ is $S_i$, a set of open intervals defined earlier.
The sequence ${f_i}$ obviously converges to 1 on the rationals, but because of the impossibility of converging to $\chi_K$ we can conclude that it is not converging to $0$ on least one irrational $x$.  So at $x$ it either converges to a value other than $0$ (doubtful), or never converges at all.  Either way, $x$ is in an infinite number of the intervals in $S=\bigcup_i{S_i}$.  Which would mean that an answer to the main question stated above would be 'at least one'.
To me this is vaguely plausible, but also surprising because the measure of the intervals in  $S_i$ is decreasing exponentially.  In fact we could rejig the definitions to make the measures decrease at arbitrarily large rates.  But my knowledge of real analysis is very limited, so it is quite possible I've made an error in reasoning, or that my intuition is insufficiently developed.

A: Fix an enumeration of $S$ as $S=\{s_n:n\in\mathbb{N}\}$.  Let $A_m=\bigcup_{n\geq m}s_n$ and $A=\bigcap_n A_n$.  Note that $\#(x)=\infty$ iff $x\in A$.  I will show there are ways in which $A$ is "small" and also ways in which $A$ is "large".
First, $A$ is small in the sense of measure.  Indeed, if $\mu$ is Lebesgue measure, note that $\sum_n \mu(s_n)=\sum_i \frac{i}{2^{i-1}}<\infty$.  This implies $\mu(A_m)\to 0$ as $m\to\infty$, since $\mu(A_m)\leq \sum_{n\geq m}\mu(s_n)$ and these tail sums must go to $0$ for the sum $\sum_n \mu(s_n)$ to converge.  Thus $\mu(A)=0$.
On the other hand, $A$ is large in the sense of category.  In particular, notice that for each $m$, $A_m$ is a dense open subset of $I$.  So, $A$ is a set of second category in $I$.  In particular, for instance, this means that for any countable set $C$, $A\setminus C$ is dense in $I$, so $A$ must contain uncountably many irrational numbers and the irrational numbers in $A$ must be dense in $I$.


text:
Q: Tabular: define label and caption manually I'm trying to define the label of my table to match with the numbering of the section. Note that I also numbered my chapters and sections manually. So instead of Tabelle 1 I need Tabelle 2.1 Any one can help?
\chapter*{Kapitel 2}
\section*{bla bla bla}
\subsection*{bla blu bli}

\begin{table}[htbp]
 \centering
 \caption{Zusammensetzungen einiger SX-Nickelbasislegierungen in wt\%.}
 \label{tbl:1}
  \begin{tabular}{c d{2.1} d{2.1} d{2.1} d{1.1} d{1.1} d{1.2} d{1.1} d{1.1} d{1.1} d{1.1} d{1.0} d{1.2}}
   \toprule
    Alloy & \mc{Ni} & \mc{Cr} & \mc{Co} & \mc{Mo} & \mc{W} & \mc{Al} & \mc{Ti} & \mc{Ta} & \mc{Re} & \mc{Nb} & \mc{V} & \mc{Hf} \\
   \midrule
    \mcTwo{First generation} & & & & & & & & & & & \\
   \midrule
    PWA~1480    & 62.5 & 10   &  5   & \mc{---} & 4        & 5    & 1.5      & 12   & \mc{---} & \mc{---} & \mc{---} & \mc{---} \\[1ex]
    Ren{\'e}~N4 & 62.6 &  9   &  8   & 2        & 6        & 3.7  & 4.2      &  4   & \mc{---} & 0.5 & \mc{---} & \mc{---}      \\[1ex]
    CMSX-2      & 66.6 &  8   &  4.6 & 0.6      & 7.9      & 5.6  & 0.9      &  5.8 & \mc{---} & \mc{---} & \mc{---} & \mc{---} \\[1ex]
    SRR~99      & 66.5 &  8.5 &  5   & \mc{---} & 9.5      & 5.5  & 2.2      &  2.8 & \mc{---} & \mc{---} & \mc{---} & \mc{---} \\
   \midrule
    \mcTwo{Second generation} & & & & & & & & & & & \\
   \midrule
    PWA~1484    & 59.4 &  5   & 10   & 2        & 6        & 5.6  & \mc{---} &  9   & 3        & \mc{---} & \mc{---} & \mc{---} \\[1ex]
    Ren{\'e}~N5 & 61.8 &  7   &  8   & 2        & 5        & 6.2  & \mc{---} &  7   & 3        & 0.5      & \mc{---} & 0.2      \\[1ex]
    CMSX~4      & 61.8 &  6.5 &  9   & 0.6      & 6        & 5.6  & 1        &  6.5 & 3        & \mc{---} & \mc{---} & 0.1      \\[1ex]
    CMSX~6      & 70.4 & 10   &  5   & 3        & \mc{---} & 4.8  & 4.7      &  2   & \mc{---} & \mc{---} & \mc{---} & 0.1      \\[1ex]
   \midrule
    \mcTwo{Third generation} & & & & & & & & & & & \\
   \midrule
    CMSX-10     & 69.6 &  2   &  3   & 0.4      & 5        & 5.7  & 0.2      &  8   & 6        & 0.1      & \mc{---} & 0.03     \\[1ex]
    Ren{\'e}~N6 & 57.4 &  4.2 & 12.5 & 1.4      & 6        & 5.75 & 0        &  7.2 & 5.4      & 0        & 0        & 0.15     \\
   \bottomrule
  \end{tabular}
\end{table}

A: The heading style you show is the default layout in book class so there is no need for manual numbering at all.

\documentclass{book}

\usepackage[german]{babel}

\begin{document}

\chapter{something}
\section{blah blah}

xxx

\end{document}

A: Strange, but if you wish:
\documentclass{book}

\begin{document}

\chapter*{Kapitel 2}
\section*{bla bla bla}
\subsection*{bla blu bli}

\def\thetable{\thechapter.\arabic{table}} %PS

\setcounter{chapter}{2} %PS

\begin{table}[htbp]
 \centering
(Meaningless) % tabular removed -- PS
 \caption{Zusammensetzungen einiger SX-Nickelbasislegierungen in wt\%.}

 \label{tbl:1}
\end{table}

\end{document}

Here it is named Table, but in your language version it should be Tabelle.


text:
Q: Can't get user description in Redux + Firebase Although I have successfully fetched users and profiles but I don't know why this error below occurs:

Cannot read property 'content' of undefined

{content: "Hello world", status: 2}

Initially, I use Firestore and this time fetch 2 docs from different collections, users and profiles.
redux code:
export function fetchUser(id) {
  return dispatch => {
    usersRef
      .doc(id)
      .get()
      .then(doc => {
        profilesRef
          .where("uid", "==", id)
          .where("status", "==", doc.data().current_status)
          .get()
          .then(function(querySnapshot) {
            querySnapshot.forEach(function(snapshot) {
              const profileItems = { ...doc.data(), profiles: snapshot.data() };
              dispatch({
                type: FETCH_USER,
                payload: profileItems
              });
            });
          });
      });
  };
}

In container:
import { FETCH_USER } from "../actions";

const initialState = {};

export default (state = initialState, action) => {
  switch (action.type) {
    console.log("action", action.payload)
    // successfully fetched, user info and profiles: profiles info
    case FETCH_USER:
      return action.payload;

    default:
      return state;
  }
};

In view:
function mapStateToProps({ users }) {
  console.log("content", user.profiles.content)
  // Cannot read property 'content' of undefined

  return { user: users, profiles: user.profiles };
}

reducer file:
import { createStore, applyMiddleware, combineReducers } from "redux";
import UsersReducer from "./reducer_users.js";

const rootReducer = combineReducers({
  users: UsersReducer,
});

const store = createStore(rootReducer, applyMiddleware(reduxThunk));
export default store;

A: Here you are making mistack you are accessing user instead of users
function mapStateToProps({ users , content }) {

  console.log("content", user.profiles.content) // change user to users
 console.log("content",content) // you can directly access content here

  return { user: users, profiles: user.profiles };
}

you can initialize default state here
add one more type FETCH_USER_COMPLETE
import { FETCH_USER } from "../actions";

const initialState = {
  content : '',
  users : ''
};

export default (state = initialState, action) => {
  switch (action.type) {
    console.log("action", action.payload)
    // successfully fetched, user info and profiles: profiles info
    case FETCH_USER:
      return { ...state , action.payload };

 case FETCH_USER_COMPLETE :
      return { ...state , users : action.payload.users , content : action.payload.users.profiles.content };

    default:
      return state;
  }
};

A: I think it might not be best practice but I have solved like this:
from:
querySnapshot.forEach(function(snapshot) {
  const profileItems = { ...doc.data(), profiles: snapshot.data() };
  dispatch({
    type: FETCH_USER,
    payload: profileItems
  });
});

to:
querySnapshot.forEach(function(snapshot) {
  const userItems = { ...doc.data(), ...snapshot.data() };
  dispatch({
    type: FETCH_USER,
    payload: userItems
  });
});

I can get content like {user.content}.


text:
Q: How to process a large number of records in aspnetboilerplate framework Used following syntax to insert 500 rows, it takes a lot of time. How to insert/update/delete a large number of records in the boilerplate asp.net core framework. Is there any option in ABP to work with large data?
using (var unitOfWork = _unitOfWorkManager.Begin())
{

  Context.Configuration.AutoDetectChangesEnabled = false;
  foreach (var element in list)
  {
      _repository.Add(element);
  }
  unitOfWork.Complete();
}

A: If you are wondering about deadlocks and transaction is not a issue for you if something fails. Than you can do it: TransactionScopeOption.Suppress. Please see this link or this one.
 using (var unitOfWork = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
 {

    Context.Configuration.AutoDetectChangesEnabled = false;
    foreach (var element in list)
    {
      _repository.Add(element);
    }
    unitOfWork.Complete();
 }