text:
Q: Função mail() está chegando em linha Estou tendo dificuldade na quebra de linha no corpo do email.
tentei varias forma e não consigo.
<?php  function enviarMensagem($dados) {
                // Dados dos funcionarios
$nome_usuario = $dados['nome'];

$email_usuario = $dados['email'];

$telefone_usuario = $dados['telefone'];

$assunto_usuario = $dados['subject'];

$mensagem_usuario = $dados['mensagem'];

// Criar variaveis de envio
$destino = "marlonxm@hotmail.com";

$remetente = "http://www.marlonmarques.com.br/"; $assunto = "Mensagem do Site";

// Corpo do email
$mensagem  = "Usuario(a) " . $nome_usuario . " mandou uma mensagem." . "
";

$mensagem .= "email: " . $email_usuario . "
";

$mensagem .= "Telefone: " . $telefone_usuario . "
";

$mensagem .= "Assunto: " . "
";

$mensagem .= $assunto_usuario . "
";
$mensagem .= "Mensagem: " . "
";
$mensagem .= $mensagem_usuario;
return mail($destino, $assunto, $mensagem, $remetente);
}
 ?>

Eu tentei vários jeitos na parte de mensagem e essas são as formas que tentei.

$mensagem  = "Usuario(a) " . $nome_usuario . " mandou uma mensagem." . "
";
$mensagem .= "email: " . $email_usuario . "
";
$mensagem .= "Telefone: " . $telefone_usuario . "
";
$mensagem .= "Assunto: " . "
";
$mensagem .= $assunto_usuario . "
";
$mensagem .= "Mensagem: " . "
";
$mensagem .= $mensagem_usuario;

===================================================================
$mensagem  = "Usuario(a) " . $nome_usuario . " mandou uma mensagem." . "\r\n";

$mensagem .= "email: " . $email_usuario . "\r\n";

$mensagem .= "Telefone: " . $telefone_usuario . "\r\n";

$mensagem .= "Assunto: " . "\r\n";

$mensagem .= $assunto_usuario . "\r\n";

$mensagem .= "Mensagem: " . "\r\n";

$mensagem .= $mensagem_usuario;

================================================

$mensagem  = "Usuario(a) " . $nome_usuario . " mandou uma mensagem." . "\r\n";

$mensagem .= "email: " . $email_usuario . "\r\n";

$mensagem .= "Telefone: " . $telefone_usuario . "\r\n";

$mensagem .= "Assunto: " . "\r\n";

$mensagem .= $assunto_usuario . "\r\n";

$mensagem .= "Mensagem: " . "\r\n";

$mensagem .= $mensagem_usuario;
$mensagem = nl2br($mensagem);

nenhuma dessas formas deu certo.
o email está chegando em linha.
Alguem pode ajudar com esse problema?


text:
Q: print duplicate elements in array I want to find duplicate elements in a dynamic array. In most cases it works, but how can it work for this case. I'm finding duplicate elements in a given array. But there is one problem that my duplicate elements can repeat too. How can I solve that part.
      #include <iostream>

      int main() {
      unsigned n;
      std::cin >> n;
      int count = 0;
      int* dynArr = new int[n];
      for (int i = 0; i < n; i++) {
          std::cin >> dynArr[i];
      }
      for(int i = 0; i < n; i++){
          for(int j = i + 1; j < n; j++){
               if(dynArr[j] == dynArr[i]){
                   std::cout<<dynArr[j]<<" ";
                   break;
               }
           }
       }
     }

I have a problem with this part. When I'm inputting a my array length 6, and elements {1,1,2,1,2,2}.
I got (1,1,2,2).
But I need to get only 1,2.
input 6
      1 1 2 1 2 2
output 1 1 2 2

but must be
output 1 2

A: Here's a simple and fast solution.
  std::map<int,size_t> element_count;

  for(int i = 0; i < n; i++){
      if ( ++element_count[dynArr[i]] == 2 ){
               // Only report on the second occurrance
               std::cout<<dynArr[j]<<" ";
       }
   }

A: const int listSize = 5;
int list1[listSize] = {0,0,1,1,3};
bool dupList[listSize] = {false};
for (int index = 0; index < listSize; index++) {
    int val = list1[index];
    for (int i = 0; i < listSize; i++) {
        if (i != index) {
            if (list1[i] == val) {
                dupList[index] = true;
            }
        }
    }
}
int printList[listSize];
int addNum = 0;
for (int index = 0; index < listSize; index++) {
    if (dupList[index] == true) {
        bool run = true;
        int print = list1[index];
        for (int i = 0; i < listSize; i++) {
            if (printList[i] == print) {
                run = false;
            }
        }
        if (run == true) {
            std::cout << print << " ";
            printList[addNum] = print;
            addNum++;
        }
    }
}

Note this code will NOT run quickly at all only use it if the operation does not need to get run very many times but it will only display the single numbers that are duplicates. It will defernatly need to get optimised more

A: You can simply get it done using two std::set<int>s.
#include <set>
#include <iostream>

int main() {
    unsigned n;
    std::cin >> n;
    int count = 0;
    std::set<int> all;
    std::set<int> redundant;

    for (int i = 0; i < n; i++) {
        int input = 0;
        std::cin >> input;

        // You cant enter the entry because its present. This will return a std::pair<,> with the second value false.
        if (!all.insert(input).second)
            redundant.insert(input);    // We store this in another set so we dont duplicate the redundant entries.
    }

    for (auto itr = redundant.begin(); itr != redundant.end(); itr++)
        std::cout << *itr << " ";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Displaying server's response on activity as textview I am making a social app in which I am getting response from server side.. i.e emails of profilr friends. I want to take that response to next activity and display as the textview.
How to do this?? Can anyone help me over this??

A: In firstActivity.java take the response in String and then pass the value to secondActivity.java with the help of Intent.putExtra and fetch, assign to the related TextView
To Put
Intent i = new Intent(firstActivity.this, secondActivity.class);
i.putExtra("key", responseString);
startActivity(i);

To fetch
String stringOnTextView =getIntent().getExtras().getString("key");


text:
Q: How to Make this SQL Task Faster to Complete Suppose table 1 Have 1,000,000 rows. In table 2 there are 50,000 rows
INPUT
Table 1
Id    User   InternetAmountDue
1     joe    NULL

Table 2
InternetUserId   UserName AmountDue
21                kay     21.00
10091             joe     21.00

I want to merge data from table 2 to table 1 as follows:

*

*If user exists in Table 1, update InternetAmountDue Column

*Else, insert new user

OUTPUT
Table 1
Id    User   InternetAmountDue
1     joe    21.00
2     kay    21.00

How can this be done fast given the large volume of data involved?

A: SQL Server 2008 provides special construct MERGE just for your case:
MERGE
INTO    table1 AS t1
USING   table2 AS t2
ON      t2.UserName = t1.user
WHEN MATCHED THEN
        UPDATE
        SET    t1.AmountDue = t2.AmountDue
WHEN NOT MATCHED THEN
        INSERT (user, InternetAmountDue)
        VALUES (t2.UserName, t2.AmountDue)

A: INSERT INTO Table1 (User)
SELECT UserName
FROM Table2
WHERE UserName not in (SELECT User FROM Table1)
 --
UPDATE t1
SET t1.InternetAmountDue = t2.AmountDue
FROM Table1 t1
  JOIN Table2 t2
  ON t1.User = t2.UserName

Make sure that Table2.UserName is indexed.
Make sure that Table1.User is indexed.

A: Assuming that you want to merge the data dynamically in a query, you could do the following:
select
  t1.id,
  t1.user,
  case
     when t2.AmountDue is not null then t2.AmountDue
     else t1.InternetAmountDue
  end as InternetAmountDue
from table1 t1
left join table2 t2
on t1.user = t2.username

It is of course equally easy to update table 1 with the new amount.

A: Try this.
UPDATE [Table 1]
SET InternetAmountDue = t2.AmountDue
FROM [Table 1] t1
INNER JOIN [Table 2] t2
ON t1.User = t2.UserName

INSERT INTO [Table 1] ( User, InternetAmountDue )
SELECT UserName, AmountDue
FROM [Table 2] t2
LEFT OUTER JOIN [Table 1] t1
ON t1.User = t2.UserName
WHERE t1.User IS NULL

A: Check out the UPSERT statement. It might be what you're looking for.

A: This will work fastest if done by the ID rather than the name.  Since you are joining by Name, you will suffer slower performance and possible dups.
Once you resolve the dups and are ready to do the updates, you should:
You should perform the updates first
Then do the inserts
Consider re-indexing


text:
Q: Normality of pullback of topological spaces $X$ and $Y$. Let $X$ and $Y$ be disjoint normal topological spaces and, $A\subseteq X$ a closed subset with $f:A\rightarrow Y$  a continuous function. Please help me to show in detail that the pullback of $X$ and $Y$ which is the quotient space $X+_f Y$, is a normal space.
Many Thanks

A: Sketch of proof, based on Dugundji (Topology, p. 146/147):
let $p$ be the quotient map from $X + Y$ to $X \cup_f Y$, the adjunction space of $X$ to $Y$ via $f$. If $F_1, F_2$ are disjoint and closed in $X \cup_f Y$, then $Y \cap p^{-1}[F_i]$ $i=1,2$ are closed and disjoint in $Y$, so there are $V_i$ open in $Y$ such that $Y \cap p^{-1}[F_i] \subseteq V_i, i=1,2$ and $\overline{V_1} \cap \overline{V_2} = \emptyset$. Then both $p[\overline{V_i}]$ are closed in $X \cup_f Y$ (check this!) and both $X\cap p^{-1}[F_i \cup p[\overline{V_i}]]$ are closed and disjoint in $X$, so these sets can be separated in $X$ by disjoint open subsets $U_i$ in $X$. Then check that for both $i$, $F_i \subseteq p[(U_i \setminus A) \cup V_i]$ and the latter sets are open and disjoint in $X \cup_f Y$.


text: Q: Is it possible to use React-Bootstrap and bootstrap.js on the same page? We have an existing Bootstrap 3 (Rails) app to which we've been adding React views. We'd now like to use a component that depends on React-Bootstrap. However, since React-Bootstrap has its own React-based implementation of Bootstrap's JavaScript logic, it doesn't want or like bootstrap.js being included. If you use both, you get problems like events being handled twice in the React-Bootstrap views. Given that the non-React views depend on bootstrap.js, is there any way to get them to co-exist? Some of our React views (particularly modals) are on the same page as non-React Bootstrap components (particularly navs), so we can't just selectively load bootstrap.js. React-Bootstrap doesn't interfere with non-React components, and I'm wondering if there's some technique for getting bootstrap.js not to interfere with the React ones.


text:
Q: Use Azure Blob storage instead of S3 buckets in Apache Superset cache I'm trying to enable thumbnail caching in my Superset instance.  The official docs provide an example of caching the thumbnail images on Amazon S3.  But I'm on the Azure cloud.  How could I rework this block of code to work with an Azure blob (or other appropriate Azure storage) instead?
From the docs:
from flask import Flask
from s3cache.s3cache import S3Cache

...

class CeleryConfig(object):
    broker_url = "redis://localhost:6379/0"
    imports = ("superset.sql_lab", "superset.tasks", "superset.tasks.thumbnails")
    result_backend = "redis://localhost:6379/0"
    worker_prefetch_multiplier = 10
    task_acks_late = True

CELERY_CONFIG = CeleryConfig

def init_thumbnail_cache(app: Flask) -> S3Cache:
    return S3Cache("bucket_name", 'thumbs_cache/')

THUMBNAIL_CACHE_CONFIG = init_thumbnail_cache
# Async selenium thumbnail task will use the following user
THUMBNAIL_SELENIUM_USER = "Admin"

I have the rest of my caching working with Redis.  I see these Python packages that look relevant: https://github.com/alejoar/Flask-Azure-Storage and https://pypi.org/project/azure-storage-blob/ but I'm not sure where to go next.


text:
Q: How to get a output response as integer from a stored procedure in SQL Server I'm trying to get the following response from a stored procedure to authenticate the user and read a response from stored procedure based on the user input.
CREATE Procedure sp_UserAuthentication
@UserName varchar(20),
@UserPassword varchar(20),
@Resp int output
AS
DECLARE @Count int;
DECLARE @IsAdmin bit;
DECLARE @IsActive bit;
Select @Count = COUNT(UserName) from tbl_UserDetails where UserName = @UserName and UserPassword = @UserPassword
IF @Count = 1
BEGIN

Select @IsActive = IsActive, @IsAdmin = @IsAdmin from tbl_UserDetails where UserName = @UserName and UserPassword = @UserPassword
IF @IsActive = 0 -- InActive user
BEGIN
    SET @Resp = 3
END
ELSE IF @IsAdmin = 1 -- Admin user
BEGIN
    SET @Resp = 2
END
ELSE -- Normal user
BEGIN
    SET @Resp = 1
END
END
ELSE -- InValid user
BEGIN
   SET @Resp = 0
END

GO

I'm getting response as always 1 for a valid user and 0 for invalid user. I'm not getting the response as 2 for admin and 3 for an inactive user.
DECLARE @Res int
exec sp_UserAuthentication 'user', 'pwd', @Res out
SELECT @Res

Table:
Create Table tbl_UserDetails(
UserName Varchar(20) primary key,
UserPassword Varchar(20) NOT NULL,
IsAdmin Bit Default 0,
IsActive Bit Default 1
);

A: Keep in mind everybody's stern reprimands about storing clear text passwords. You desperately need to read about and understand how to encrypt these. But your entire procedure could be greatly simplified to something like this.
CREATE Procedure UserAuthentication
(
    @UserName varchar(20),
    @UserPassword varchar(20),
    @Resp int output
)
AS
    set @Resp = 0 --This sets the response to invalid unless we actually find a user

    Select @Resp =
        case when IsActive = 0 then 3 --Inactive User
            when IsAdmin = 1 then 2 --Admin user
            else 1 --Normal user
        end
    from tbl_UserDetails
    where UserName = @UserName
        and UserPassword = @UserPassword

A: Let's ignore that you're putting usernames and passwords into a table.  Please don't do that, and if you do, please use some kind of encryption/hashing.  But look in your SELECT statement in the middle:
Select @IsAdmin = @IsAdmin

You are setting @IsAdmin to @IsAdmin, you need to set that to just IsAdmin.


text:
Q: Ordering advertisements/offers to increase revenue (confidence algorithm?) I have a site where there will be a list of offers that the user can fill out for virtual currency. What's a decent algorithm to decide what order to arrange them by?
What's important:

*

*New offers move up so more people see them in order to get some
metrics on them

*Highest EPC offers are on top (best money makers, highest converting)

The metrics I have:
 - Tags (if the user likes movies, the offers tagged with movies should move up)
 - Reported EPC - EPC of the offer according to the affiliate network
 - Network EPC  - EPC of the offer across all of our sites
 - Site EPC     - EPC of the offer on this site
 - Source EPC   - EPC of the offer from a certain source (there can be multiple per user)
 - Payout       - How much the offer pays per conversion (lead)
 - Clicks       - Clicks network-wide, site-wide, and from a certain source

Is there any recommended algorithm for this kind of problem? I was thinking some sort confidence algorithm (like the Wilson sorting algorithm) but I haven't a clue how to implement that with the metrics I have. Any ideas?

A: You are basically trying to build a ad recommender system. This should be a good starting point: http://pages.cs.wisc.edu/~beechung/icml11-tutorial/ . Take a look at the netflix challenge (movie recommender), KDD cup 2011 challenge (Music recommender) etc


text:
Q: Problems with starting Virtualbox I try to start the Virtualbox, this are my steps
vagrant box add jhcook/osx-yosemite-10.10
mkdir test
cd test
vagrant init jhcook/osx-yosemite-10.10

modify the vagrant file like this:
 config.vm.provider "virtualbox" do |vb|
# Don't boot with headless mode
vb.gui = true
vb.cpus = 2

# Use VBoxManage to customize the VM. For example to change memory:
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--graphicscontroller", "vboxvga"]
vb.customize ["modifyvm", :id, "--accelerate3d", "on"]
vb.customize ["modifyvm", :id, "--ioapic", "on"]
vb.customize ["modifyvm", :id, "--vram", "128"]
vb.customize ["modifyvm", :id, "--hwvirtex", "on"]

end
and than I get
vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'jhcook/osx-yosemite-10.10'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'jhcook/osx-yosemite-10.10' is up to date...
==> default: Setting the name of the VM: VagrantTest_default_1428936332822_32428
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
The guest machine entered an invalid state while waiting for it
to boot. Valid states are 'starting, running'. The machine is in the
'gurumeditation' state. Please verify everything is configured
properly and try again.

If the provider you're using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you're using VirtualBox, run `vagrant up` while the
VirtualBox GUI is open.

I try different version of the Virtualbox and searching for answers in the internet. But I really don't see my mistake, I would be happy if somebody could help me  :)

A: It looks like this issue is about VirtualBox, not about Vagrant.
According to this article - http://www.macbreaker.com/2015/01/virtualbox-yosemite-zone.html :

If your version of Virtualbox asks you to choose between 64-bit and 32-bit, be sure to choose 64-bit. Choosing 32-bit will result in a critical "Guru Meditation" error later on.

May be this is your case too? What if you will try install Yosemite by using mentioned article without Vagrant?


text:
Q: Learning C : noob suitable debugger Greetings!
Finally stared learning C and I think the time has come to start working with a debugger. At this time I'm using Gvim for editor and command line for compiling. After trying few debuggers ( KDbg, ddd,insight ) running gdb seems to be the simplest and least overwhelming at the moment.
I'm I on the right path or is there a better way to go about it?
I also tried NetBeans and Anjuta, but they feel like a little bit much for this step of the journey.
Thanks in advance.

A: If you are comfy on a command line, then gdb will load you with the least conceptual chaff.
If you are on Windows, well, Visual Studio is pretty friendly.
Eclipse's CDT is not bad, but it takes some learning to get your project into it to the point where you can debug.

A: I'm using gdb for my university assignments, and it's going pretty well. For the most part, the debuggers in the IDEs you've listed (NetBeans, Anjuta) actually rely on an external program such as gdb for the debugging.
There are graphical interfaces for gdb; however, I personally find many of them to be pretty clunky. Hooking up gdb with Code::Blocks did turn out pretty well though, for me.

A: vim/gvim + gdb is a good path
Quite often you will be left with remote connection to a linux box and gdb so it's quite useful to know how to use gdb from command line.
If you're debugging on a local box with GUI you might try ddd or any other gui debugger. Gui debuggers provide easier ways of inspecting values of variables in memory for example if you have nested structures. However if you are linking additional libraries and you want to jump into them gdb is easier compared to for example Visual Studio.
If you setup Makefile in your project directory you can simply from inside vim use:
:mak

To build your code and it will jump into the first warning/error. You can move to next error with:
:cn

Or view list of errors:
:cope

Jump between open multiple subwindows:
ctrl-w ctrl-w

Hide list of errors, go to the window that shows errors and:
:clo

A: Learning gdb can't hurt, certainly.  It's pretty ubiquitous.  A nice GUI debugger can certainly speed things up.

A: It is probably overwhelming at the beginning but it still is a good idea to use gdb, this will help you debug in any system with no IDEs installed. If you are an emacs user, you can even single step visually.


text:
Q: How can I allow my function to accepts two different objects in swift? I have a function which takes one argument. I wanted my function to accept two object types. How can I do it? Here is the example below:
func accept(user: Customer) {
  ...
}

It should accept Customer and Employee object reference.
accept(objRefCustomer)
accept(objRefEmployee)

Please help me in this case.

A: Alternative to super-classing: use protocols
You needn't necessarily use a superclass for this case (if Customer and Employee are struct value types; superclass option is not possible), but can rather use the more generic approach of protocols.
Define a protocol Users which blueprints properties and methods for your Customer and Employee instances (if we let Customer and Employee conform to Users, then we promise that instances of these two structures will have accessible the blueprinted properties and methods):
protocol Users {
    var name: String { get }
    func printTypeOfUser()
}

Define the Customer and Employee structures, and their conformance to the protocol Users:
struct Customer : Users {
    let name: String
    init(name: String) { self.name = name }

    func printTypeOfUser() {
        print("Is a Customer!")
    }
}

struct Employee : Users {
    let name: String
    let id: Int
    init(name: String, id: Int) { self.name = name; self.id = id }

    func printTypeOfUser() {
        print("Is an Employee!")
    }
}

Now you can define a generic function where its generic, say T, is type constrained to types conforming to the protocol Users, which in this case is equivalent to the Customer or Employee types
func accept<T: Users>(user: T) {
    print("Name of user: \(user.name) [\(user.dynamicType)]")
    user.printTypeOfUser()

    // do something additional employee-specific if user is an employee?
    if let employee = user as? Employee {
        print("User is an employee with id: \(employee.id)")
    }
}

Example usage of this function for Employee as well as Customer instances:
let employee = Employee(name: "John", id: 1)
let customer = Customer(name: "Sarah")

accept(employee) /* Name of user: John [Employee]
                    Is an Employee!
                    User is an employee with id: 1 */

accept(customer) /* Name of user: Sarah [Customer]
                    Is a Customer!                 */

A: Instead of changing your Class structure and code base, you can use AnyObject. It will also be easier for you if, for example, in future you have to make this function accept parameters of class WaterMelon. Making all these classes inherit from a common parent class would be unnecessary overhead, not to mention hectic.
AnyObject is swift equivalent of objective c id. AnyObject is a protocol that can represent an instance of any class type.
It also has a more general counterpart, Any, which can represent any type at all (including structs and enums).
Following code will accept any class type parameter you pass:
func accept(sender : AnyObject) { //Or AnyObject? if you want to handle nil as well
      ...
    }

To access properties of the classes you pass as AnyObject, you can use type casting.
For example below code will check sender type and typecast it for you:
if let customerRef = sender as? Customer {
    // ...
    // Sender is of customer class type. Use it with customerRef that we created
    let customerName = customerRef.dynamicType.sampleNameProperty //Access a property of class Customer
    customerRef.funcOfCustomerClass() //Call a method of class Customer
}
else{
 //Sender is not of customer class type.
//Then it must be Employee??? Handle cases for employee here.
}

A: create a protocol, and use it as argument type. protocol can be also empty, it will work anyway. Works with struct and class as well;
ex:
protocol SomeFakeProtocol {}
class SomeClass: SomeFakeProtocol { //code here }
struct SomeStruct: SomeFakeProtocol { //code here }

func someFunction(arg: SomeFakeProtocol) { //code here }

Benefits - you can allow to use only types you want to. And, sure, you can do things like this:
extension String: SomeFakeProtocol {}

A: You can create a super class called People of Cutomer and Employee.
Then set user as type of People:
func accept(user: People) {
  ...
}

A: You don't need a super class, you can just pass an object of type AnyObject and in your function check the type of the object passed:
func accept(user: AnyObject) {
    if let usr = user as? Person {
        ...
    }
}

But if you have many types you want to pass you may want to make a protocol or a super class.


text:
Q: How can I convert this column value to an integer? My C# code looks like this:
myNum = dt.Columns[0];

myNum is an integer and dt is a datatable.  The value in column 0 of dt is a string ("12"), but I'd like to convert it to an integer.  How can I do this?
I've tried:
myNum = int.Parse(dt.Columns[0]);

...but that doesn't work.  Any ideas?

A: Your parse wasn't working because the parse method takes a string, and the data comes back as a simple object.
Also, the data is in the rows, so you have two options really, (I prefer the first):
// This converts the object directly to an integer
myNum = Convert.ToInt32(dt.Rows[0][0]);

// This converts the object to a string, and then parses it into an integer
myNum = int.Parse(dt.Rows[0][0].ToString());

A: The values are stored in rows and not columns. Try this instead:
myNum = int.Parse(dt.Rows[0][0].ToString());

A: if Parse throws an exception, this means dt.Columns[0] is not a valid input. If you want to avoid exception, you can use int.TryParse which returns a boolean telling if the conversion was done or not successfully
EDIT: BTW, Darin must be right: your value is not stored in a column but in a cell

A: Use TryParse method to parse the Value :
int myNum = 0;
int.TryParse(dt.rows[0][0].ToString() , out myNum);

with above code , If an error occurs , The value of variable will be zero

A: Convert.ToInt32(dt.Rows[0][0])

The above would be better, if you are dealing with a variety of types, eg doubles (1.0).


text:
Q: Display current date in XML element I'm using an XSL to transform one XML into another. My problem is that in one element I have to display the current date with the format:YYYYMMDD.
I tried using a variable like these:
<xsl:variable name="dateNow" select="current-dateTime()"/>
<xsl:variable name="dateNow2" select="current-date()"/>

And then tried to format then, but no success.
<FRUEHESTER_LIEFERTERMIN><xsl:value-of select="format-dateTime($dateNow, '[Y0001][M01][D01]')"/></FRUEHESTER_LIEFERTERMIN>

A: What exactly is happening (what does "no success" mean).  What XSLT processor are you using?
Here is a minimal test case of what you are trying to do (input XML document doesn't matter)
    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"     xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"  exclude-result-prefixes="xs fn">

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:variable name="dateNow" select="current-dateTime()"/>
    <xsl:variable name="dateNow2" select="current-date()"/>

    <xsl:template match="/">
        <FL><xsl:value-of select="format-dateTime($dateNow, '[Y0001][M01][D01]')"/></FL>
    </xsl:template>

</xsl:stylesheet>

and here is what it produces -- do you get the same if you try this test case?
<?xml version="1.0" encoding="UTF-8"?>
<FL>20120111</FL>

A: If you want to show date in the following format Wed, 27-Oct
Use following code in XML
                 <TextClock
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:format12Hour="EE, dd-MMM"
                  android:textColor="@color/gray_100"
                  android:textSize="15sp"
                  android:layout_gravity="center"
                  android:padding="5dp"
                  android:textStyle="bold" />

If you want to show time like 09:08
Use the following code in XML
                  <TextClock
                    android:id="@+id/time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:format12Hour="hh:mm"
                    android:textColor="@color/gray_100"
                    android:textSize="60sp" />

if you want to show time with AM and PM use following code in XML
                 <TextClock
                    android:id="@+id/time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:format24Hour="HH:mm"
                    android:textColor="@color/gray_100"
                    android:textSize="60sp" />


text:
Q: What is the "reciprocity" of Stack Overflow? During yesterday's podcast, Joel mentioned the reciprocity ratio and also said that the sweet spot for successful sites is 14%. I'm curious to know what the rate is for Stack Overflow itself.

Reciprocity is "What percentage of users both asked and answered?"

*

*Joel Spolsky SE Podcast #06 ~16:31

Can we please get this number published for each site? This would be an especially interesting statistic for Area 51 beta sites. (Either on Area 51 by each site, or elsewhere.)

A: From your definition/this query run on data.stackexchange.com, about 19.45%.
DECLARE @UserCount decimal(19,5)
SELECT @UserCount = COUNT(Users.Id) FROM Users

SELECT COUNT(Users.Id) / @UserCount * 100
FROM Users
WHERE Users.ID IN (SELECT OwnerUserId FROM Posts WHERE Posts.PostTypeId = 1)
AND Users.ID IN (SELECT OwnerUserId FROM Posts WHERE Posts.PostTypeId = 2)

A: Data for Feb 2011:
Site            Peeps   Askers  Ansrrs  Both    Reciprocity
Skeptics        60      34      51      25      42%
Quantitative    147     88      103     44      30%
Project Mana    133     60      109     36      27%
Code Golf       160     55      147     42      26%
Role-playing    118     49      99      30      25%
Science Fict    214     86      180     52      24%
Area 51 Disc    268     148     185     65      24%
GIS             290     182     175     67      23%
TeX - LaTeX     551     425     243     117     21%
StackOverflow   70933   46127   39581   14775   21%
Homebrew        73      42      45      14      19%
Physics         423     296     208     81      19%
Cooking         345     161     247     63      18%
Stack Apps      77      60      31      14      18%
WordPress       684     454     353     123     18%
Gaming          697     347     475     125     18%
Mathematics     1214    908     519     213     18%
Photography     347     167     240     60      17%
IT Security     122     59      84      21      17%
Graphic Desi    158     103     82      27      17%
Database Adm    159     106     80      27      17%
English Lang    854     506     492     144     17%
Audio Record    84      53      45      14      17%
Apple           637     343     399     105     16%
Board and Ca    114     43      89      18      16%
Ubuntu          1532    839     932     239     16%
Theoretical     277     164     156     43      16%
Atheism         106     34      88      16      15%
Statistical     393     253     199     59      15%
Bicycles        97      39      72      14      14%
Programmers     2628    985     2020    377     14%
Electronics     352     205     197     50      14%
Home Improve    212     134     106     28      13%
ServerFault     4677    2987    2305    615     13%
Android Enth    417     232     236     51      12%
Game Develop    493     254     299     60      12%
Personal Fin    171     95      96      20      12%
Code Review     299     148     185     34      11%
User Interfa    215     93      146     24      11%
SuperUser       4783    2771    2545    533     11%
Unix and Lin    517     280     294     57      11%
Writers         239     77      188     26      11%
Guitars         92      43      59      10      11%
Webmasters      548     333     270     55      10%
OnStartups      493     208     330     45      9%
Web Apps        561     295     317     51      9%

*

*Peeps = Number of people who posted (asked or answered)

*Askers = Number of people who asked a question

*Ansrrs = Number of people who answered

*Both = Number who both asked and answered

*Reciprocity = Percentage of users who both asked and answered in the same month

Hypothesis: High reciprocity denotes a conversational site, low reciprocity denotes a one-sided site where experts help novices. Either extreme is unhealthy.
None of these metrics is really strong enough to base policy on, so publishing the numbers regularly or even using them to drive policy in Area51 is probably not warranted.
This is the SQL used to produce this data:
select (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId in (1,2)) as "Recent Users",
       (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId = 1) as "Askers",
       (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId = 2) as "Answerers",
       (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId = 1) +
       (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId = 2) -
       (select count(distinct OwnerUserId) from Posts
         where CreationDate >= '2011-02-01' and CreationDate < '2011-03-01'
           and OwnerUserId is not null
           and OwnerUserId > 0
           and PostTypeId in (1,2)) as "Double Threats"

Suggestions for improving the SQL would be most welcome :P


text:
Q: Combine array of objects inner array based on property say I have a data structure that looks like this:
data = [
        {title: "Alpha", content: [{ // 1 item }]},
        {title: "Beta", content: [{ // 10 items }]},
        {title: "Beta", content: [{ // 12 items }]},
        {title: "Beta", content: [{ // 8 items }]}
       ]

I'd like to figure out a reduce function that would return the following structure:
data = [
        {title: "Alpha", content: [{ // 1 item }]},
        {title: "Beta", content: [{ // 30 items }]}
       ]

I've tried looking at some answers where reduce is used based on title but it did not return the new structure with the accumulated content array such as:
data = data.reduce((x, e) => {
          x.push(
            Object.assign(
              {},
              e,
              messages.find((x) => x.title == e.title)
            )
          )
          return x
        }, [])

Any help would be great.

A: This might help -

var data = [{
    title: "Alpha",
    content: [1, 2, 3, 4, 5]
  },
  {
    title: "Beta",
    content: [6, 7, 8, 9, 10]
  },
  {
    title: "Beta",
    content: [11, 12, 13, 14, 15]
  },
  {
    title: "Beta",
    content: [16, 17, 18, 19, 20]
  }
]

data = data.reduce((array, item) => {
  const existingItem = array.find(innerItem => innerItem.title === item.title);
  if (!!existingItem) {
    existingItem.content = [...existingItem.content, ...item.content];
  } else {
    array.push(item);
  }
  return array;
}, []);

console.log(data);

A: You don't need to use .find, which has to search the entire array every iteration.
Using reduce and an object map to collect dupes, Object.values to unwrap object to array.  spread syntax to feed as push arguments.

data = [
        {title: "Alpha", content: [{ 1:1 }]},
        {title: "Beta", content: [{2:2 }]},
        {title: "Beta", content: [{ 3:3}]},
        {title: "Beta", content: [{4:4}] }
       ]
console.log(
Object.values(data.reduce((acc,{title,content})=>{
  acc[title] ?
    acc[title].content.push(...content) :
    acc[title] = { title, content }
  return acc
},{})
))

If IE compatible is needed, there is a polyfill on the above linked documentation.  This will also work:

data = [
        {title: "Alpha", content: [{ 1:1 }]},
        {title: "Beta", content: [{2:2 }]},
        {title: "Beta", content: [{ 3:3}]},
        {title: "Beta", content: [{4:4}] }
       ]
function values(obj){
  return Object.keys(obj).map(k=>obj[k])
}
console.log(
values(data.reduce((acc,x)=>{
  acc[x.title] = acc[x.title] || {title: x.title, content: []}
  acc[x.title].content = acc[x.title].content.concat(x.content)
  return acc
},{})
))

A: I made small changes from @user120242 code.

data = [
        {title: "Alpha", content: [{ 1:1 }]},
        {title: "Beta", content: [{2:2 }]},
        {title: "Beta", content: [{ 3:3}]},
        {title: "Beta", content: [{4:4}] }
       ]
let acc={};
data.forEach((x)=>{
  acc[x.title] = acc[x.title] || {title: x.title, content: []}
  acc[x.title].content = acc[x.title].content.concat(x.content)
}
)
console.log(acc)


text:
Q: Proof about chromatic number of graph Let G be a graph of degree n with degree sequence $d_1 ≥ d_2 ≥ d_3 ≥ ⋯d_n$. Show that the chromatic number satisfies:
$$χ(G) ≤ 1 + max_i(min(d_i , i − 1))$$
Hint: Assign colors to vertices in order of non-increasing degrees such that no conflict arises.  This will produce a valid coloring.
Any ideas on how to prove this question? I don't exactly understand what the formula is saying.

A: I found the following answer to my question:

*

*We apply greedy coloring to the vertices in non-increasing order of degree.

*When we color the $i^{th}$ vertex $v_i$, it has at most $\min\{d_i,i-1\}$ earlier neighbors, so at most this many colors appear on its earlier neighbors.

*Hence the color we assign to $v_i$ is at most $1+\min\{d_i,i-1\}$.

*This holds for each vertex, so we maximize over $i$ to obtain the upper bound on the maximum color used.

This proof is mentioned in the question previously asked here:
Proof of $\chi(G)\leq 1+\max_i\min\{d_i,i-1\}$ in graph theory

A: http://www.ucdenver.edu/academics/colleges/CLAS/Departments/math/graduateprograms/alumni/alumni/Documents/Student%20Theses/Mitchell_MSThesis.pdf
Page 15 in here kind of answers it.
Did you find anything better?


text:
Q: Redirect .jpg to Html without Changing the extention of .jpg images on the webpage This is what i am looking for
http://more-sky.com/data/out/2/IMG_21306.jpg
How it redirect to its parent page i.e (http://more-sky.com/WDF-21306.html)
This above link is redirecting from .jpg to .html but its still showing the images(.jpg)
For Example
I want to redirect

www.domain.com/images/Apple.jpg

to

www.domain.com/Apple.html

(Brief Explanation : Image  is on page www.domain.com/Apple.html. whenever anyone open www.domain.com/images/Apple.jpg it should redirect to www.domain.com/Apple.html)

A: You can try setting a rule that makes a redirect to the correct page in your web server. For example if you are using Apache you can try using rewrite


text:
Q: $Y\subseteq X$ and $\exists f:X\to Y$ injection, then $X$ and $Y$ are in bijective correspondence $Y\subseteq X$ and $\exists f:X\to Y$ injection, then $X$ and $Y$ are in bijective correspondence
if $ Y=X$, we're done, since Identity map servers our  purpose
assume $Y\neq X \rightarrow X\setminus Y \neq 0$
define $A= f^{n}(X\setminus Y)$
define $g:X\to Y$
$x \mapsto f(x) $ if $x\in A$ and
$x \mapsto x $ if $x\notin A$
It is well defined.
if $g(x)=g(y)$
then if both $x,y \in A\rightarrow f(x)=f(y) \rightarrow x=y $
else if both $x,y \notin A \rightarrow x=y$
if $x\in A $ and $y\notin A$
then $g(x)=g(y)\rightarrow f(x)=y$
as $x\in A \rightarrow \exists m\in N\cup\{0\} $ and $\exists z\in X\setminus Y$ such that $x=f^m (z)\rightarrow y=f(x)=f^{m+1}(z) \in A$ contradiction
so $g$ is injective
How can I show that this map is surjective?

A: I assume you mean $A = \bigcup_{n=0}^\infty f^n(X\setminus Y).$ To see $g$ is surjective, let $y\in Y.$ If $y\notin A,$ then $y=g(y).$ If $y\in A,$ then since $y\notin X\setminus Y,$ $y=f(x)$ for some $x\in A,$ so $y=g(x).$

A: As $Y\subset X$, you can consider the injective embedding $Y \rightarrow X$. As there is alzó An injective function $X \rightarrow Y$, it follows by Cantor-Bernstein theorem that $|Y|=|X|$, i.e., there is a bijection between these two sets.


text:
Q: Как проверить с помощью регулярных выражений город, который введет пользователь? Нужна проверка с помощью регулярных выражений.
Каждый город должен распознаваться, если пользователь пишет его с маленькой буквы или меняет окончание (использовать регулярные выражения). Если пользователь вводит город неправильно, следует предложить ему варианты городов, в которые есть рейсы.
Написал вот такой код:
import re

city = 'Лондон, Париж, Москва'
user_city = 'лондоне'
if re.search(user_city,city,flags=re.IGNORECASE):
    print('cool')
else:
    print('bad')

Но он не ищет, если вводить другие окончания. После того, как совпало, надо еще менять значение на правильное, лондоне на Лондон...

A: Регулярными выражениями такое сделать сложновато будет. Лучше использовать так называемый "нечёткий поиск":
from fuzzywuzzy import fuzz
import re

city = re.findall('\w+', 'Лондон, Париж, Москва')
user_city = 'лондоне'
score = list(map(lambda x: fuzz.QRatio(x.lower(), user_city), city))
max_score = max(score)
if max_score > 80:
    print('cool')
    print([c for (c,s) in zip(city, score) if s == max_score])
else:
    print('fuck')

Вывод:
cool
['Лондон']

Хотя выбором конкретной функции нечёткого сравнения (их там несколько) и подбором коэффициента похожести, возможно, придётся поиграться.


text:
Q: Adding Figure to JPanel, then to another JPanel and then a JFrame For my project I have to display three different figures on one frame. The way that I thought that I could do this is by having one main panel that is added to the frame and then three other frames added to the main frame. The first is four circles that are filled in at certain spots, the second is a graph, and the third a clock. Currently I am just trying to make the first one work so that I can apply that to the other two. My program compiles but when I run it I just get a blank window. What is causing it not to show the graphic? The n00832607 class is named that way and is lowercase because of a formality with turning projects in on my schools system, please ignore that.
import java.awt.*;
import javax.swing.*;
import java.util.*;

public class n00832607 extends JFrame {

private JPanel panelMain;
private FourFans panelfans;

public n00832607() {

//Main Panel
panelMain = new JPanel();
add(panelMain);

//Creating Fans
panelfans = new FourFans();
panelMain.add(panelfans);

}

 //Main Method

public static void main(String[] args) {
n00832607 frame = new n00832607();
frame.setVisible(true);
frame.setSize(400, 400);
frame.setTitle("Project 6");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}
//n00832607 Class Finish

class FourFans extends JPanel
{
  public FourFans()
  {
  JPanel panel = new JPanel();
  panel.setLayout(new GridLayout(2, 2));
  panel.add(new Fan());
  panel.add(new Fan());
  panel.add(new Fan());
  panel.add(new Fan());
  }

}

//Responsible for creating Fan

class Fan extends JPanel {

protected void paintComponent(Graphics g)
{
  super.paintComponent(g);
  int height = getHeight();
  int width = getWidth();
  g.setColor(Color.BLACK);
  g.drawOval((int)(0.09 * width), (int)(0.09*height), (int)(0.825 * height), (int)    (0.825 * height));
  g.fillArc((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 20, 30);
  g.fillArc((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 110, 30);
  g.fillArc((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 200, 30);
  g.fillArc((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 290, 30);
 }
}

EDIT
I've got what you suggested to work and now the fans show up, they are very small but I can try to deal with that later since they actually show up now. I have tried to apply this to the next figure but it isn't seeming to work. The first part now looks like
public class n00832607 extends JFrame {

private JPanel panelMain;
private FourFans panelfans;
private SquareFunction panelfunction;

public n00832607() {

//Main Panel
panelMain = new JPanel();
add(panelMain);

//Creating Fans
panelfans = new FourFans();
panelMain.add(panelfans);

//Creating Function
panelfunction = new SquareFunction();
panelMain.add(panelfunction);

}

//Main Method

public static void main(String[] args) {
n00832607 frame = new n00832607();
frame.setSize(400, 400);
frame.setTitle("Project 6");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
}

This is the code for SquareFuction that I am working with. When I run the fans show up small and there is plenty of whitespace where the SquareFunction could show up in. Here is a picture of it
class SquareFunction extends JPanel
{
  public SquareFunction()
  {
     add(new GraphMaker());
  }
}

//Responsible for creating the graph

class GraphMaker extends JPanel {

protected void paintComponent(Graphics g)
{
  super.paintComponent(g);
  double scaleFactor = 0.1;
  Polygon p = new Polygon();
  int y = 0;
  for(int x = -100; x <= 100; x++)
  {
     if(y < 200 - (int)(scaleFactor * x * x))
     {
        y = 200 - (int)(scaleFactor * x * x);
     }
     p.addPoint(x+200,200-(int)(scaleFactor * x * x));
  }
  g.setColor(Color.BLACK);
  g.drawLine(20, y+1, getWidth() - 50, y+1);
  g.drawLine(200, 0, 200, y+1);
  g.drawString("X", 345, 200);
  g.drawString("Y", 200, 9);
  g.setColor(Color.BLUE);
  g.drawPolygon(p);
  g.setColor(Color.WHITE);
  g.drawLine(50, 200 - (int)(scaleFactor * 100 * 100), 300, 200 - (int)(scaleFactor * 100 * 100));
}
}

A: I would suggest you move the setVisible call to last line in the method and try adding one of your panels to it, for example...
public static void main(String[] args) {
    n00832607 frame = new n00832607();
    frame.setSize(400, 400);
    frame.setTitle("Project 6");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

This ensures that you've finished modifying the frame BEFORE you try and use it
Next...
class FourFans extends JPanel {

    public FourFans() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2));
        panel.add(new Fan());
        panel.add(new Fan());
        panel.add(new Fan());
        panel.add(new Fan());
    }

}

This doesn't make sense.  You've extended FourFans from JPanel then created another JPanel within in...Instead, simply try adding the Fans directly to it...for example...
class FourFans extends JPanel {

    public FourFans() {
        setLayout(new GridLayout(2, 2));
        add(new Fan());
        add(new Fan());
        add(new Fan());
        add(new Fan());
    }

}

Updated based on changes to the question
The main reason you're getting the result your are is because panelMain is using a FlowLayout by default.
Try changing it to use a BorderLayout instead, for example...
panelMain.setLayout(new BorderLayout());
You may need to change this in the future to a GridLayout, but this will get you started ;)


text:
Q: How to use objects to make a chatbot that can send messages based on your response? I'm trying to make a simple chatbot in JavaScript that can send messages based on the user's input through an input field. How can I make it so the bot moves the conversation to the next index if it recognizes any of the options as correct input?
BOT: Hello!
BOT: How are you feeling today?
ME: Im feeling good.
BOT: Happy to hear that!
BOT: If you want to hear a joke say JOKE.
ME: JOKE
BOT: Two guys stole a calendar. They got six months each.

This is what I've got so far. I have been stuck on this for quite a while, so any help would be appreciated!
const story1 = {
    messages: ["Hello!", "How are you feeling today?"],
    options: {
      "good": 2, // Check if this word is in a sentence
      "bad": 3 // Index of story
    }
}

const story2 = {
    messages: ["Happy to hear that!", "If you want to hear a joke say JOKE."],
    options: {
      "JOKE": 4
    }
}

const story3 = {
    messages: ["Sorry to hear that!", "Do you want a hug?"],
    options: {
      "yes": 5,
      "no": 6
    }
}

const story4 = {
    messages: ["Two guys stole a calendar. They got six months each."],
    options: {
      "haha": 7 // Etc...
    }
}

const step = 0;

const stories = [
    story1,
    story2,
    story3,
    story4
    ...
]


text:
Q: Is using Timeline for scheduling correct I've found a lot of suggestions to use Timeline with KeyFrame.onFinished to schedule tasks in the JavaFX. But the AnimationTimer doc says, that its handle method is called 60 times per second.
It is unclear from documentation but it seems that Timeline uses AnimationTimer internally. Does that means that the timeline solution for scheduling imposes CPU-intensive polling mode? If that is actually how JavaFX works, what other methods for scheduling is recommended?

A: Advised Usage Rules for Scheduling in JavaFX
Given how Timeline works (see below), some basic rules can be derived:

*

*Use a Timeline when you want to schedule quick operations that modify attributes of the scene graph.

*Do not use a Timeline when you want to do any of the following:

*

*Perform operations that are themselves time-consuming (e.g. the work for a given scheduled activity takes longer than 1/30th of a second).

*Perform work which really doesn't have anything to do with the scene graph.

*Have real-time scheduling at a resolution greater than a pulse (1/60th of a second).

*Control your scheduling using traditional java.util.concurrent mechanisms or a third party library.

*Run your scheduled tasks on their own threads.

Also, for a one-off execution that updates the scene graph after a fixed delay, I like to use a PauseTransition.
Answers to specific questions and concerns

It is unclear from documentation but it seems that Timeline uses AnimationTimer internally.

No, Timeline does not use AnimationTimer internally.  However, Timeline is still pulse based and will receive code to update the current state of the timeline will be invoked on each pulse (usually 60 times a second).  To understand what a pulse is read the background section below.

Does that means that the timeline solution for scheduling imposes CPU-intensive polling mode?

Yes, there is some overhead, but it is likely minimal enough that it can be disregarded.  The JavaFX system is going to be running some work on each pulse anyway, regardless whether you create any timelines yourself.  Unless you are heavily animating objects or doing a lot of work on each pulse, then the time to process each pulse will be completely trivial as there is simply very little work to be done on each pulse.

If that is actually how JavaFX works, what other methods for scheduling is recommended?

There are numerous alternatives to Timeline:

*

*Use a javafx.concurrent facility such as a Task or Service, and specifically a ScheduledService.

*

*This is good if you want to provide feedback (such as progress, message updates and return values) to the JavaFX UI.

*Use a java.util.concurrent facility.

*

*This is good if you don't need the additional features of javafx.concurrent for progress and messaging or if you want the additional control provided by java.util.concurrent facilities.

*If you use this, you can still get intermittent or final feedback to your JavaFX UI by invoking Platform.runLater().

*Use a java.util.TimerTask.

*

*Simpler API than java.util.concurrent, no direct interface for JavaFX feedback, though again you can use Platform.runLater() for that.

*Use a third party scheduling system (such as Quartz):

*

*More complicated than other solutions, but also more flexible, though it adds a dependent library and requires Platform.runLater if you want to modify scene graph elements.

If you do use something other than a timeline, you need to take care:

*

*You invoke Platform.runLater if you want to modify anything on the scene graph from your non-JavaFX application threads.

*You don't invoke Platform.runLater too often so as to overload the JavaFX application thread (e.g. by coalescing update calls).

Background Info
Timeline Operation
For example, let's say you have a Timeline which has a Keyframe that has a duration of 1 second.  The internal Timeline will still be updated each pulse.  This is required because a Timeline is more than just a scheduler, it has other properties and tasks.  For instance the Timeline has a currentTime property.  The currentTime will be updated each pulse, so that it always reflects the current time accurately.  Similarly, internal logic with the Timeline will check to see if there are any KeyValues associated with the Timeline, and update their values on each pulse, in accordance with their associated Interpolator.  And the internal logic will check on each pulse to see if the Timeline is finished, to call the onFinished handler.   It will also evaluate the current time versus the duration of each keyframe and, if there is a match, fire the appropriate action event for the keyframe.
So the Timeline is acting like a scheduler in that it can execute key frames at specific times, but it is more than a scheduler as it also maintains it's current time, current state and ability to continuously vary associated key values.  Additionally, you can vary the rate, direction and number of cycles of a timeline, as well as pause it in position, then resume it, which also differs from a traditional scheduler.
An aspect of the Timeline is that because it is based upon callbacks from pulses in the JavaFX system; everything runs on the JavaFX application thread.  Therefore, when you use timelines (even 1000 of them), no additional threads are spawned, so from that perspective it is lightweight.  Also all logic invoked by the timeline occurs on the JavaFX application thread.  Because everything runs on the JavaFX application thread, this makes the Timeline nice for manipulating elements and attributes of the active JavaFX scene graph (such manipulations must be performed on the JavaFX application thread).  However, a timeline would be a bad choice if you wanted to do a lot of CPU time-consuming work or blocking I/O in the associated timeline keyframes.  This is because the JavaFX application thread will be blocked while that work occurs, freezing your UI.
Pulses
The JavaFX runtime system is based upon pulses.

A pulse is an event that indicates to the JavaFX scene graph that it is time to synchronize the state of the elements on the scene graph with Prism. A pulse is throttled at 60 frames per second (fps) maximum and is fired whenever animations are running on the scene graph. Even when animation is not running, a pulse is scheduled when something in the scene graph is changed. For example, if a position of a button is changed, a pulse is scheduled.
When a pulse is fired, the state of the elements on the scene graph is synchronized down to the rendering layer. A pulse enables application developers a way to handle events asynchronously. This important feature allows the system to batch and execute events on the pulse.

The JavaFX animation system stores a list of all of the animations and animation timers which been created and not garbage collected.  On each pulse it will iterate through this list.  Each animation timer will have it's handle callback invoked on each pulse.  Each timeline or transition will similarly have its internal state update and update any associated key values or fire key frame action events as appropriate.

A: You can use ScheduledExecutorService
final Runnable runnable = new Runnable() {
    public void run() {
        //Code goes here
    }
}
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);


text:
Q: Modifying custom designs for chapter and appendix heading pages I have made to following book class MWE that uses this template for making the chapter heading pages look pretty.
\documentclass[12pt,a4paper,titlepage,twoside,openright]{book}

\usepackage[titletoc]{appendix}

%%%%%
% v chapter heading style from http://zoonek.free.fr/LaTeX/LaTeX_samples_chapter/0.html
%%%%
\makeatletter
 \def\thickhrulefill{\leavevmode \leaders \hrule height 1ex \hfill
 \kern \z@}
 \def\@makechapterhead#1{%
 \reset@font
  \vspace*{10\p@}%
  {\parindent \z@
    \begin{flushright}
  \reset@font \scshape \bfseries \Huge \thechapter \par
\end{flushright}
\hrule
\begin{flushright}
  \reset@font \LARGE \strut #1\strut \par
\end{flushright}
\vskip 100\p@
}}
 \def\@makeschapterhead#1{%
  \reset@font
  \vspace*{10\p@}%
  {\parindent \z@
    \begin{flushright}
      \reset@font \scshape \bfseries \Huge \vphantom{\thechapter} \par
    \end{flushright}
    \hrule
    \begin{flushright}
      \reset@font \LARGE \strut #1\strut \par
    \end{flushright}
    \vskip 100\p@
  }}
%%%%%

\begin{document}

\tableofcontents

  \chapter{title of this chapter}

some text

\begin{appendices}

  \chapter{Title of this appendix}\label{apx:f}

  \section{an appendix section}

\end{appendices}

\end{document}

Currently this produces simple numbers for chapter headings (i.e. "1" instead of "Chapter 1"). This is what I want.
It also does a similar trick to appendices (i.e. "A" instead of "Appendix A"). I don't want this.
How can I change the script to give me appendix titles like: "Appendix A"?

A: You can easily do that with the apptools package, which defines booleans and conditional related with being in an appendix. B.t.w., to have bold small caps with Computer Modern, you have to load cm-super, i.e. load the T1 font encoding:
\documentclass[12pt,a4paper,titlepage,twoside,openright]{book}
\usepackage[T1]{fontenc}
\usepackage[titletoc]{appendix}
\usepackage{apptools}

%%%%%
% v chapter heading style from http://zoonek.free.fr/LaTeX/LaTeX_samples_chapter/0.html
%%%%
\makeatletter
 \def\thickhrulefill{\leavevmode \leaders \hrule height 1ex \hfill
 \kern \z@}
 \def\@makechapterhead#1{%
 \reset@font
  \vspace*{10\p@}%
  {\parindent \z@
    \begin{flushright}
  \reset@font \scshape \bfseries \Huge\IfAppendix{Appendix}{} \thechapter \par
\end{flushright}
\hrule
\begin{flushright}
  \reset@font \LARGE \strut #1\strut \par
\end{flushright}
\vskip 100\p@
}}
 \def\@makeschapterhead#1{%
  \reset@font
  \vspace*{10\p@}%
  {\parindent \z@
    \begin{flushright}
      \reset@font \scshape \bfseries \Huge\vphantom{\thechapter} \par%
    \end{flushright}
    \hrule
    \begin{flushright}
      \reset@font \LARGE \strut #1\strut \par
    \end{flushright}
    \vskip 100\p@
  }}
\makeatother
%%%%%

\begin{document}

\tableofcontents

  \chapter{title of this chapter}

some text

\begin{appendices} \appendixtrue

  \chapter{Title of this appendix}\label{apx:f}

  \section{An appendix section}

\end{appendices}

\end{document}


text:
Q: Как вернуть массив строк разделенных 0x0A Друзья, сразу прошу строго не судить, я только учусь.
Передомной стоит четкая задача:
1) Есть скрипт который посылает на мой сервер GET запрос. В ответ на этот запрос я должен вернуть ему массив строк в таком формате:
номер строки; имя пользователя; пароль;0x0A - это окончание каждой строки я так понимаю?
Вопрос что как это сделать? я пробовал так:
echo "1;D;".date("d.m.Y H:i:s")."\n";
echo "2;C;".$data_card['code'].";0; ;".mb_substr($data_card['owner'], 0, 16, "UTF-8").";0;01.12.2300\n";
echo "3;L;1;26.10.2016;30.10.2016;777;".$data_card['dt'].";5.00;26.10.2016 09:01:23\n";
echo "4;t;1\n";
echo "5;e;2\n";
echo "6;#";

но как я понял это я вывел чисто строки на экран а не вернул массив строк, так ведь? у меня задача вернуть массив строк что бы скрипт его обработал. как реализован скрипт и что внутри - не ясно, эта информация не доступна


text:
Q: Boundedness of Riemann-like sums on unbounded interval Hi
I am trying to find suitable conditions (integrability, growth...) on a function $f:\mathbb{R}\to \mathbb{R}$ such that:
\begin{equation}
\sum_{k\in\mathbb{Z}}f(kh)h= \mathcal{O}(1),\qquad h\to 0^+.
\end{equation}
In other words I am trying to find conditions on $f$ such that the above sum is bounded for $h$ small enough. Alternatively, can I impose conditions of $f$ that make $\sum_{k\in\mathbb{Z}}f(kh)h \to_{h\to0} \int_R f (x)dx$? Many thanks.
Francesco


text:
Q: order/sort by a field in database Hi would it be possible to sort the records on agestart field when displayed in the webpage.
This is the code it works ok but I can;t get it to sort.
case 'lookagestart':
    $data = $osDB->getAll ( $sqlSelect.$same_lookagestartsql, array( USER_TABLE, $user['username'], $user['lookagestart'],'active',$active_lang ) ) ;
    $t->assign('showhead',get_lang('above_lookagestart'));

    break;

A: Without access to your system, I won't know for sure but...
What if you tried this?
case 'lookagestart':
    $sort_clause = ' ORDER BY `lookagestart` ';
    $data = $osDB->getAll ( $sqlSelect.$same_lookagestartsql.$sort_clause, array( USER_TABLE, $user['username'], $user['lookagestart'],'active',$active_lang ) ) ;
    $t->assign('showhead',get_lang('above_lookagestart'));

    break;


text:
Q: CNTK and UserMinibatchSource prefetch If I implement an UserMinibatchSource in python, will the minibatch data be prefetched when training?

A: The prefetching functionality is part of the Deserializer classes in C++. Therefore, prefetching will not be available for custom data unless you write some C++ code.


text:
Q: Is there a polynomial whose Coefficients in $\mathbb Q$ such that none of roots of this polynomial be in the root closure of $\mathbb Q$? For example, we know that  $x^5-x+1$ is a polynomial of degree five over $\mathbb Q$ that is not solvable by radicals. Which means that one of  the roots of this polynomial  is not in root closure of $\mathbb Q$. Is there a polynomial whose coefficients in $\mathbb Q$ such that none of  the roots of this polynomial be in the root closure of $\mathbb Q$?
In the other hand, can we find a polynomial over $\mathbb Q$ such that none of the roots of this polynomial Obtained by  the operations  multiplying, suming, Subtracting, Divising and rooting from elements of $\mathbb Q$


text:
Q: Can the difference of means be seen as a fulfilled precondition for simple mediation analysis? The preconditions for a simple mediation analysis according to Hayes (2013) are statistically significant associations between X (the independent variable) and M (the mediator) as well as associations between M and Y (the dependent variable). In the case of a dichotomous independent variable with the values 0 and 1: could a significant difference of the means of M between the two groups 0 and 1 be considered as a fulfilled precondition/significant association, so that carrying out a mediation analysis is justified?
My own thoughts on this question: Firstly, the term association confuses me. Unfortunately Hayes doesn't give a definition of "association". Other sources that I have consulted yet define association as covariation and link it to correlation and regression. The difference of means isn't mentioned as a measure of association. But doesn't the difference of means also indicate covariation in certain cases? For example, I have a dichotomous variable that indicates membership in a trauma survivor or a non-trauma group.  If I find significant differences between the two groups in an outcome like depressive symptoms, I could interpret it as the following: depressive symptoms covary with trauma exposure; therefore the difference of means is an indicator of covariation. Furthermore the non-standardized regression coefficient in a linear regression model with an independent dichotomous variable (values 0,1) is the difference of the means of Y between 0 and 1. The regression coefficient is considered as a measure of association. As a result, in a regression-based simple mediation model with a dichotomous variable as X, the path coefficient from X to M is the difference of the means of M between 0 and 1.
Thank you for your responses

A: No that's evidence, or a precondition, of effect modification.


text:
Q: Unique combinations of 0 and 1 in list in prolog I have problem, because I want to generate permutations of a list (in prolog), which contains n zeros and 24 - n ones without repetitions. I've tried:findall(L, permutation(L,P), Bag) and then sort it to remove repetitions, but it causes stack overflow. Anyone has an efficient way to do this?

A: Instead of thinking about lists, think about binary numbers. The list will have a length of 24 elements. If all those elements are 1's we have:
?- X is 0b111111111111111111111111.
X = 16777215.

The de fact standard predicate between/3 can be used to generate numbers in the interval [0, 16777215]:
?- between(0, 16777215, N).
N = 0 ;
N = 1 ;
N = 2 ;
...

Only some of these numbers satisfy your condition. Thus, you will need to filter/test them and then convert the numbers that pass into a list representation of its binary equivalent.

A: Select n random numbers between 0 and 23 in ascending order. These integers give you the indexes of the zeroes and all the configurations are different. The key is generating these list of indexes.
%
% We need N monotonically increasing integer numbers (to be used
% as indexes) from [From,To].
%

need_indexes(N,From,To,Sol) :-
   N>0,
   !,
   Delta is To-From+1,
   N=<Delta,               % Still have a chance to generate them all
   N_less is N-1,
   From_plus is From+1,
   (
      % Case 1: "From" is selected into the collection of index values
      (need_indexes(N_less,From_plus,To,SubSol),Sol=[From|SubSol])
      ;
      % Case 2: "From" is not selected, which is only possible if N<Delta
      (N<Delta -> need_indexes(N,From_plus,To,Sol))
   ).

need_indexes(0,_,_,[]).

Now we can get list of indexes picked from the available possible indexes.
For example:
Give me 5 indexes from 0 to 23 (inclusive):
?- need_indexes(5,0,23,Collected).
Collected = [0, 1, 2, 3, 4] ;
Collected = [0, 1, 2, 3, 5] ;
Collected = [0, 1, 2, 3, 6] ;
Collected = [0, 1, 2, 3, 7] ;
...

Give them all:
?- findall(Collected,need_indexes(5,0,23,Collected),L),length(L,LL).
L = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 5], [0, 1, 2, 3, 6], [0, 1, 2, 3, 7], [0, 1, 2, 3|...], [0, 1, 2|...], [0, 1|...], [0|...], [...|...]|...],
LL = 42504.

We are expecting: (24! / ((24-5)! * 5!)) solutions.
Indeed:
?- L is 20*21*22*23*24 / (1*2*3*4*5).
L = 42504.

Now the only problem is transforming every solution like [0, 1, 2, 3, 4] into a string of 0 and 1. This is left as an exercise!

A: Here is an even simpler answer to generate strings directly. Very direct.
need_list(ZeroCount,OneCount,Sol) :-
   length(Zs,ZeroCount),maplist([X]>>(X='0'),Zs),
   length(Os,OneCount),maplist([X]>>(X='1'),Os),
   compose(Zs,Os,Sol).

compose([Z|Zs],[O|Os],[Z|More]) :- compose(Zs,[O|Os],More).
compose([Z|Zs],[O|Os],[O|More]) :- compose([Z|Zs],Os,More).
compose([],[O|Os],[O|More])     :- !,compose([],Os,More).
compose([Z|Zs],[],[Z|More])     :- !,compose(Zs,[],More).
compose([],[],[]).

rt(ZeroCount,Sol) :-
   ZeroCount >= 0,
   ZeroCount =< 24,
   OneCount is 24-ZeroCount,
   need_list(ZeroCount,OneCount,SolList),
   atom_chars(Sol,SolList).

?- rt(20,Sol).
Sol = '000000000000000000001111' ;
Sol = '000000000000000000010111' ;
Sol = '000000000000000000011011' ;
Sol = '000000000000000000011101' ;
Sol = '000000000000000000011110' ;
Sol = '000000000000000000100111' ;
Sol = '000000000000000000101011' ;
Sol = '000000000000000000101101' ;
Sol = '000000000000000000101110' ;
Sol = '000000000000000000110011' ;
Sol = '000000000000000000110101' ;
....

?- findall(Collected,rt(5,Collected),L),length(L,LL).
L = ['000001111111111111111111', '000010111111111111111111', '000011011111111111111111', '000011101111111111111111', '000011110111111111111111', '000011111011111111111111', '000011111101111111111111', '000011111110111111111111', '000011111111011111111111'|...],
LL = 42504.


text:
Q: for calculating the number of insulator disks needed for creepage is line to line voltage or phase voltage used? For example, I am calculating the number of disks required for a 330kV line. Assuming medium pollution (20mm/kV) and each disk having 405mm would my number of disks be 17 (based off line voltage) or 10 (based off phase voltage)

A: From comments: -
What does the insulator connect to on both its ends? If it is suspended from a pylon then it will be ground on one end but there's no clue in your question. Only you know this part of the puzzle.

My apologies, I thought that was obvious when I mentioned that its a
transmission line. Yes it is insulating the tower (ground) from the
transmission line.

In that case you should consider the worst case scenario phase voltage that might be seen. The normal case is just the phase voltage (as per line voltage divided by \$\sqrt3\$) but, if there is a phase lost during distribution and the sourcing transformer is a delta output (no neutral) then there is a possibility that the insulator might see somewhere between phase voltage and line voltage.
You should also consider that lightning strikes are quite common on pylons and this will make an impact so, is there a top earth wire running from pylon-to-pylon that can partially umbrella protect the lines? These are things you might need to consider as per this: -

Picture from this answer


text:
Q: Chained Select Boxes - Basic I have built this page: http://excelwrestling.com/poola.php for an upcoming dual tournament.  I have most all of the data being pulled from my mySQL database, with just some sample data in there now.
I am looking to chain the select boxes, so when the user chooses TEAM 1 (at the top), then it will update all of the WRESTLER 1 select boxes with only names from that team.  Same thing for team 2.
Another part of this is, is when a person chooses WRESTLER 1 vs WRESTLER 2, I want those two names to fill in the WINNER field, so the user can choose between those two names only.
Anything you can explain to me, or code you could post would be much appreciated.
Thank you!

A: You probably want to use special queries to get wrestlers from teams. Then use a while loop to update all the wrestlers on a team from an array. Then assign the array to special select index numbers from the database.  Can you show whats in the database? I need to know in order to help. Since I don't know whats in your database. I'll just guess how your database is organized. Say that your team drop down list is called team_select and that each wrestler in the wrestler table had a wrestler_id wrestler_name and a team_id.
You would do the following code
     $team_select = $_POST['team_select']

            $wrestler_query = "SELECT wrestler_name FROM wrestler WHERE team_id = "
. $team_select;

            $query = mysqli_query($connection, $wrestler_query);
            //Repeat code from here... (see bottom)
            while( $team_select = mysqli_fetch_assoc($query));
            {
               echo '<option class="Select1" value="' . $team_select['wrestler_name'] . '">'</option>
            }
        <?
          </select>

        <?php
        mysqli_data_seek($accounts,0);
     //..to here for other drop down lists (except give the different names of different drop down lists in the html.)

Also don't forget, the connection variable is the database access credentials.


text:
Q: Remove duplicates from list elements I am trying to remove rows that have duplicate entries, as defined by two columns, from multiple dataframes located in a single list.
Simple data:
aa <- data.frame(a=rnorm(100),b=rnorm(100),x=rnorm(100),y=rnorm(100),Z=rep(1:4, each=25))
split.aa<-split(aa, aa$Z)

For each df in the list 'split.aa' I am trying to remove rows with duplicated x,y pairs.
I could do this one df a time with:
split[[z]][!duplicated(split[[z]][,c('x','y')]),]

where z is the name of each df within 'split.aa'.
How would I write this into lapply so that the action is performed on each element?
I am having a hard time wrapping my head around how to refer to the specific list elements within the lapply function.

A: lapply(split.aa, function(x) x[!duplicated(x[c("x", "y")]), ])

will do the trick.

A: just define a function in lapply
lapply(split.aa, function(x) x[!duplicated(x[c("x", "y")]), ])


text:
Q: What function is for embeding exif data?
Possible Duplicate:
How do I add exif data to an image?

exif_read_data() is for reading exif data, but what function is for embeding exif data?

A: Looks like there's no built-in support for that (?).
However I found something called phpExifRW which seems to do the job. I haven't tried it.

A: There's no native means of writing EXIF data (although you can natively write IPTC data via iptcembed which might be sufficient).
However, you might want to take a look at the pel library - it's actively developed and has good examples, etc.

A: I would use Imagick. It's very fast and powerfull and has it's own PHP extension. It has a setImageProperty method.
Example from the docs:
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');

PEL seems fine though, just used to do it with Imagick.


text:
Q: Mac disk randomly filling up so a few days ago I deleted some files I didn't need on my MacBook Pro(macOS Mojave), to free up around 6 gb of space. But then today, I got this notification from finder saying im out of storage. Definitely didn't download 6gb worth of files.
Did some digging and found that kernel_task wrote 190gb of data, much more than my disk space (121gb) just curious what happened and how I fix this. activity monitor image


text:
Q: Make an Angular *ngFor draw two different columns of data I'm trying to make a *ngFor directive to put data in two columns, instead of just one column as usual. I even followed an example I saw over there, but it didn't work at all. Let's start with the graphic part:
I've got this:

... but I want it to look like this (so I can fit more items than before without making the card bigger):

This is the code I currently have, which does absolutely nothing (it just shows the first image):

              {{ level?.label || level }}

              {{ level?.label || level }}

This uses the following CSS:
.left-style{
    float:left;
    width:45%;
}
.right-style{
    float:right;
    width:45%;
}

I know it wouldn't be needed in this example, but it was just a try. I'm quite confused why this is not working at all. Inside the created divs, the bootstrap classes (col-md-6) are not being applied at all.
Why is this happening?
EDIT:
Let me expand a little how the app looks like so it's easy to find out what's going on. After trying other methods that didn't really work, I guess it's time to give you a wider view of what this looks like in order to find out how to fix this weird thing.
The parent component uses "cards" like the one you see upper in this post. So, the main template looks like this:

The "cards" component has a ng-content which draws inside another component that I provide, as you could see in the parent component's implementation. This is the cards component:
import { Component, Input } from '@angular/core';

@Component({
    selector: "card",
    styleUrls: ["./card.css"],
    template: `

        {{title}}

      <ng-content></ng-content>

    `
})

export class Card{

    @Input() title: string;

    constructor(){

    }

}

Somehow, just as I stated in the comments of the first proposed answer, the divs aren't compiling the bootstrap classes as they normally would:

It's becoming really weird at this moment. Can anyone spot what's wrong here?

A: The issue is that you have two class attributes for each div, so Angular is taking the later class only.
Simply merge the class attribute like:

And both classes will be applied.
You can actually use less html and use ngClass as follows

          {{ level?.label || level }}

A: Easy way:
I am making the Angular demo Tour of Heroes and i wanted to divide in two columns the dashboard data *ngFor display;(like this)

this is code it works for me right now:

          {{hero.name}}


text:
Q: Georeferencing Old Mining Maps (Floetzkarte des Oberschlesische) in QGIS? I am trying to georeference some old mining maps (Floetzkarte des Oberschlesische) in QGIS 2.9. I have already tried to do that by marking known points on present satelite photos, but the results were poor. Then I used some other old, but already georeferenced maps (Messtischblatt) and marked triangulation points present on both maps. Georeference based on these points was quite good, but unfortunately I noticed that not all Messtischblatt contain traingulation points at all, so this method doesn't work for all maps.
The maps use some strange coordinate systems, totally incomprehensible for me. The reference point (null point) which is located at sheet no. 3 (TPL at the picture), seems to be located at (491138, 282639) EPSG:2180, (18.8752414523, 50.4108051983) WGS84.

Each Floatzkarte's sheet contains coordinates in meters relative to this null point. The coordinates are in corners of the maps as well as on its borders.

Could you provide me with some information about the CRS used on these  maps and/or instruction on how to prepare proper proj4 parameters for it, so that I could use that in georeferencing process?

A: If those "strange" coordinates do not fit to Gauss-Krueger coordinate systems, they might be similar to the "preußisches Koordinatensystem". You will find some links to that in my answer to
Conversion of coordinates of "Bochum coordinate system"
You have to put up a custom CRS on the point "Trockenberg" in Cassini-Soldner projection, which was common at that time:
+proj=cass +lat_0=50.4108051983 +lon_0=18.8752414523 +k=1 +x_0=0 +y_0=0 +ellps=bessel +towgs84=0,0,0,0,0,0,0 +units=m +no_defs


text:
Q: Set theory and intersection For example, if we have some numbers $x,y,z,$ from $x=y-z,$ we can infer $y=x+z.$
Is there such a simple way of looking at sets?
Suppose for some sets $A,B,C$ if we have $A=B \cap C$ how can we think of $B$ in terms of $A$ and $C?$

A: You see, being 'analogous' in math roughly means generalization of the specific object of study. For e.g. real numbers can be 'analogous' to Hermitian operators and adjoint of an operator can be 'analogous' to conjugate of complex numbers.
In your question, numbers are not generalized by sets. Hence, 'computational' work on sets consists of different rules. There are bunch of set rules introduced in the beginning of any set theory book. You should refer to them and work it out accordingly.

A: I agree with the Chrystomath's comment, there is not much to say. The best we can do is saying that $B \subseteq A \cup C^{c}$ (where $C^c$ is the complementary set of $C$).
Although I found the following formulation for $B,$ but not just in terms of $A$ and $C.$ I had to add also $B$ because there are several sets that may hold the condition stated above.

Let $A, B,$ and $C$ be sets, such that $A = B \cap C.$ Then $B = A \cup (B \setminus C).$
Proof: Suppose that $A = B \cap C.$ Let $x \in B.$ We have that either $x \in C,$ or $x \notin C.$ In the former case, $x \in B \cap C,$ so $x \in A.$ It follows that $x \in A \cup (B \setminus C).$ In the latter case, $x \in B \setminus C,$ so $x \in A \cup (B \setminus C).$ Therefore $B \subseteq A \cup (B \setminus C).$ Now, let $y \in A \cup (B \setminus C).$ Then $y \in A,$ or $y \in B \setminus C.$ In the former case, $y \in B \cap C,$ so $y \in B$ and $y \in C,$ and in particular, $y \in B.$ In the latter case, $y \in B \setminus C,$ then $y \in B$ and $y \notin C.$ In particular $y \in B.$ Therefore $A \cup (B \setminus C) \subseteq B.$ Since $B \subseteq A \cup (B \setminus C) \subseteq B,$ we deduce that $B = A \cup (B \setminus C).$ $\square$


text:
Q: Firebase Licence For Open Source Project Is there any free Firebase License available for Open source projects?? I have searched their website but not able to find anything.

A: Firebase has a generous Free Plan that allows to up to 100 concurrent connections. There are no plans specialized for open-source projects. However, the Free Plan tends to suit most OSS needs.


text:
Q: Inconsistency in the definition of electrostatic work Sorry if there this is a duplicate but I can't find anything that deals with this.
I have a point charge $q$ sitting at the origin. It takes no work for me to put it there.
Then, I bring $-q$ out from infinity and spread it around over a sphere of radius $a$ centered at the origin. It takes $dW = 1/4\pi \epsilon_0 (-q dq/a)$ to bring $-dq$ of charge in. The surface element is $dq = \sigma a^2sin\theta d\theta d\phi$. In total, we have
$$W = \frac 1 2\int_S \frac{q}{4\pi\epsilon_0}\sigma a^2sin\theta d\theta d\phi = -\frac{q\sigma a}{2\epsilon_0} = -\frac{q^2}{8\pi\epsilon_0 a},$$
since $q = 4\pi a^2 \sigma$ over the sphere. This leaves me very confused, because this formula is the same as the amount of work it takes to construct the same spherical shell, but without the extra $q$ in the middle (e.g. Griffiths ex. 2.9).
I know about the inconsistencies about dealing with the work it takes to assemble point charges and charge distributions. However, I'm at a loss about where I've gone wrong above.
How do I deal with finding the work it takes to assemble a configuration with both point charges and charge distributions?

A:
This leaves me very confused, because this formula is the same as the amount of work it takes to construct the same spherical shell, but without the extra $q$ in the middle.

Not quite. Since in the first case you didn't consider the work done to create the point charge; as you said it and to bring it to the origin from infinity for free, you also should not consider this in the second case.You also didn't consider, in this case, *the work it took to spread out the charge over the sphere, assuming there might be any). So you should also not consider this in the second case.
Situation 2: Let's reverse the situation where there is no point charge and we create the sphere first. If we want to just consider a charged sphere in a vacuum (not accounting for creating the charges and any work it may have taken to create that configuration on the sphere again) then, when you dump $q$ on the sphere you get that for free. Moreover, since there are no other charges around, you also get to bring the whole sphere in from infinity for free. That is, $W=0$ at this point. Now, if you bring a point charge $q$ in from infinity you will see that $W$ is identical to the previous situation.
We can see that this is expected if we consider the formula for $W$ given by
$$W = \int \int \frac{\rho_1(\mathbf{r})\rho_2(\mathbf{r}')}{|\mathbf{r-r'}|} \ d^3r' d^3r.$$

A:
This leaves me very confused, because this formula [$W = -\dfrac{q^2}{8\pi\epsilon_0 a}$] is the same as the amount of work it takes to construct the same spherical shell, but without the extra q in the middle (e.g. Griffiths ex. 2.9).

Your value for the work done by an external force in assembling a shell of total charge $-q$ cannot be correct as it implies (negative sign) that work is done on the external force rather than the expectation (repulsive force between negative charges) that work is done by the external force.
The correct value of the amount of work done is $W =+\dfrac{q^2}{8\pi\epsilon_0 a}$

Having assembled these negative charges note that there is no electric field inside $r<a$ the charge distribution and so the electric potential inside the distribution is constant.
Outside $r\ge a$ the charge distribution the electric field is $E(r)=-\dfrac {q}{4\pi \epsilon_0\,r^2}$ and the electric potential is $V(r)=-\dfrac {q^2}{4\pi \epsilon_0\,r}$
Now bring in the $+q$ charge from infinity to $r=a$ and the work done by a external force is $qV(r)=-\dfrac {q^2}{4\pi \epsilon_0\,a}$ and then no work is done in bringing the positive charge to the centre of the negative charge distribution $r=0$.
So the total work done in assembling the charges, which is the electric potential energy of the system is $-\dfrac {q^2}{4\pi \epsilon_0\,a}+\dfrac{q^2}{8\pi\epsilon_0 a}= -\dfrac{q^2}{8\pi\epsilon_0 a}$.

Starting with the positive charge and then assembling the negative charges requires $\displaystyle \int_0^q \int ^a_\infty \dfrac{q-Q}{4\pi \epsilon_0\,r^2}\,dr\,dQ$ of work to be done by the external force which gives $-\dfrac{q^2}{8\pi\epsilon_0 a}$ as before and in one of the intermediate steps you should recognise two terms, one for assembling the negative charges and the other when bringing in the positive charge.

Another way of looking at the problem is to use the energy density of an electric field $\dfrac 12 \epsilon_0 |E|^2$ and the integrate over the appropriate volume $\displaystyle \int_V \dfrac 12 \epsilon_0 |E|^2 \,dV$.
In the case of just assembling the negative charges the volume is for all $r\ge a$ and for assembling the positive and negative charges the volume is between $r=0$ and $r=a$ as in this case there is no electric field outside the negative charge distribution.


text:
Q: Java heap when there is no load on the program We've a java program (micro-service) that shows below heap pattern when there's no load on the program ( program is doing nothing)

A: This is a healthy looking 'saw-tooth' pattern of memory allocation.  Memory is being allocated for objects and being garbage collected when it's not being referenced.
The fact that your program is "doing nothing" doesn't mean that the libraries\frameworks\application servers you're are using are also doing nothing.  These tools will be using using resources: maintaining threads, waiting for connections on ports, managing resources etc.  This ensures requests to your micro-service are handled as efficiently as possible, but will require system resources.
Problems occur when resources are allocated but can't be recovered, which isn't happening in the graph above.


text:
Q: Laravel&Socialite&Nginx : Production Problems with login in services I'm working in a Laravel project, i've developed, using Socialite, the Facebook, Twitter & Google Login. In local environment: no problem, everything is working good. When I upload to production server, (and change to correct apps configurations, of course), cannot login with any service.
Composer:

*

*Laravel: 5.2

*Socialite: ^2.0

at config/session.php -> 'domain' is configured with correct domain
client_id & client_secret for all services are ok (as they're working in local env)
When I try to FB login, the result is:

Client error: POST https://graph.facebook.com/oauth/access_token
  resulted in a 400 Bad Request response: {"error":{"message":"Missing
  authorization
  code","type":"OAuthException","code":1,"fbtrace_id":"HVyIquI4FAD"}}

When I try to Twitter/Google login, the result is:

InvalidArgumentException in TwitterProvider.php line 15: Invalid
  request. Missing OAuth verifier.

The callback URI seems to be OK... so I'm very confused.
This is my nginx block config:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

(I tried others... without work)
As I've investigated a lot, seems to be some workaround with nginx or php (cookie config, maybe). Any idea? Thanks

A: After googling around for 3 days, losing my mind over this bull of a thing, I finally found out that I had a redirection error in my Nginx sites-enabled configuration.
what I had
location / {
    try_files \$uri \$uri/ /index.php?\$query_string;
}

what I changed it to
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

I hope that I saved someone as blind as me 3 days worth of time.


text:
Q: deep learning with kfold cross validation I am new into neural networks, I want to use K-fold cross-validation to train my neural network.
I want to use 5 folds
50 epochs
and a batch size of 64
I found a function in scikit for k-fold cross validation
model_selection.cross_val_score(model_kfold, x_train, y_train, cv=5)

and my code without cross validation is
history = alexNet_model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1,validation_data=(x_validation, y_validation))

I don't know how to implement this with batch size and epochs in python using keras and scikit.
any idea?

A: Be sure to use test data when validating your model, not the same training data.  Using training data to validate will bias your results.
In your example, I would use the KerasClassifier module instead of the numpy KFolds module.
from keras.wrappers.scikit_learn import KerasClassifier

After you've imported the module, your code would be (with results output:
evaluator=KerasClassifier(build_fn=baseline_model, epochs=50, batch_size=64)
kfold=KFold(n_splits=5, shuffle=True, random_state=random_seed)

results=cross_val_score(evaluator, x_test, onehot_y_test, cv=kfold)
print("Model: %.2f%% (%.2F%%)" % (results.mean()*100, results.std()*100))


text:
Q: In a finite monoid, any left inverse is also a right inverse Let $M$ be a finite monoid with identity $e$. If $x\in M$ has a left inverse $b$, I want to show that $b$ is also a right inverse.
There's already a proof here In a non-commutative monoid, is the left inverse of an element also the right inverse?.
However, in my book the hint to this problem goes as follows. Since the set $\{x^n: n\in \mathbb N\}$ is finite, there are two distinct positive integers $l,k$ with $x^l=x^k$. But because $M$ is not a group there's no cancellation law. How should I proceed?

A:
"But because $M$ is not a group, there's no cancellation law"...

But $x$ has a left inverse, so you can certainly cancel $x$ on the left: if $xr=xs$, then multiplying by $b$ on the left you get $bxr = bxs$, hence $er=es$, so $r=s$.
Remember, the cancellation law holds in groups because you have inverses. In a monoid, the existence of a (one-sided) inverse for $x$ means that you can cancel $x$ (on one side).
Assuming that $l\lt k$, from $x^l=x^k$ you get, multipying on the left by $b^l$, that $e=x^{k-l}$.
Now consider $xb$. Multiplying on the right by $x^{k-l}$ we get
$$xb = xbe = xbx^{k-l} = x(bx)x^{k-l-1} = xex^{k-l-1} = xx^{k-l-1}=x^{k-l}=e.$$
Now that we know that $b$ is a two-sided inverse, we may deduce that $b=x^{k-l-1}$.


text:
Q: How to create editable drop down in struts 1.3 I'm using struts drop down list in my application. But i would like make a drop down as editable one. User either can select from option or able to type it manually. I Google out but couldn't find out. Yeah, i know it not possible only struts. I just want to know how to incorporate struts with Java script.
Please sort out the issue.. Thanks in advance !!


text:
Q: Is the entire Universe the same age? Is all of the visible Universe exactly the same age everywhere? What about the Universe beyond what we can see?

A: Ben Hocking is right that the Universe we observe is not the same age everywhere: the further away we look, the younger things are, simply because the light from faraway objects takes time to reach us.
But you may be wondering about more than that: what if we could remove those light-travel-time delays and consider the Universe as it is now, as opposed to the way we see it (with greater delays for more distant objects)? Would it all be the same age in that case?
That turns out to be a more subtle question than you might think, because of relativity. Relativity says, among other things, that different choices of reference frame lead to different notions of time -- things that are simultaneous in one reference frame are not simultaneous in another. When you consider what a distant object is like now, you have to be careful to specify what reference frame you're talking about, because different frames lead to different "nows."
At each point in spacetime, there is a reference frame that seems like the "most natural" one to use, namely the one in which the expansion of the Universe looks roughly the same in all directions. Cosmologists tend to use that reference frame to define and synchronize their clocks. That is, the time coordinate at any point in spacetime is, by definition, the amount of time that would have elapsed according to an observer who'd been at rest in that reference frame since the Big Bang. That time coordinate is often called "cosmic time."
If you use cosmic time as your time coordinate, then it is true that, at any fixed moment of time, all points in the Universe have the same age. But it's true pretty much because of the way we defined our time coordinate, so this is kind of a vacuous statement!
Update: Based on the comments, I realize I should have explained some things explicitly. I'm considering here "cosmological" effects, meaning I'm ignoring things that are due to small-scale inhomogeneities and thinking about large scales, on which the Universe is approximately homogeneous. If, for instance, you hang around near the horizon of a black hole, you'll age at a different rate from someone else. Even if you avoid such extreme cases, small-scale variations in the gravitational potential will lead to small-amplitude age variations. In fact, the definition of cosmic time only really makes sense in the approximation where we're willing to average over small-scale inhomogeneities. If you're not willing to do that, then different prescriptions for synchronizing your clocks, no one of which is obviously more natural than another, will lead to small differences in ages of things.

A: No, the further away we look, the younger the Universe becomes. That's why we're able to see galaxies that were forming when the Universe was approximately a half billion years old. Although it's possible there is an unknown portion of the Universe beyond what we can see, we currently have no reason to believe such a region exists. Rather, the boundaries of what we can see are dictated by when light decoupled from matter.


text:
Q: Azure functions upload file broken? When I upload function files via the portal, all files get this prefix
------WebKitFormBoundary2prVJaVBFIetixZM
Content-Disposition: form-data; name="file"; filename="index.js"
Content-Type: text/javascript

and this suffix
------WebKitFormBoundary2prVJaVBFIetixZM--

this used to work a couple of days ago.

A: Cosmin,
The portal has been recently updated and it looks like this is a regression.
We've openeed this issue and will address the problem ASAP.
Thank you for reporting this!


text:
Q: group by CASE in SQL Server/SQLAlchemy in Sqlalchemy (0.8.2) I am trying to SELECT CASE GROUP BY CASE
something like that:
query = """
     SELECT count([HR_PERSONNEL].[S_HR_PERSONNEL_ID]) AS value,
       CASE
         WHEN (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / 365.25) < 15) THEN 15
         WHEN (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / 365.25) BETWEEN 15 AND 19) THEN 19
         ELSE 100 END AS anon_1
      FROM [HR_PERSONNEL]
      GROUP BY CASE
        WHEN (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / 365.25) < 15) THEN 15
        WHEN (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / 365.25) BETWEEN 15 AND 19) THEN 19
        ELSE 100 END"""

the plain text SQL query can be executed with SA without a problem:
>>> for i in mssql_engine.execute(query):
        print i

(11, 15)
(1097, 19)
(63878, 100)

but I have a problem with the same query in SQLAlchemy ORM:
>>> age_case_groups =case([( floor_function  < 15, 15)\
                                ,(between(floor_function,15,19), 19)],else_=100)
>>> vols_by_age = session.query(func.count(HrPersonnel.S_HR_PERSONNEL_ID).label('value'),age_case_groups)\
                .group_by(age_case_groups)
>>> vols_by_age.all()

 Traceback (most recent call last):
      File "<pyshell#43>", line 1, in <module>
        vols_by_age.all()
      File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2104, in all
        return list(self)
      File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2216, in __iter__
        return self._execute_and_instances(context)
      File "build\bdist.win32\egg\sqlalchemy\orm\query.py", line 2231, in _execute_and_instances
        result = conn.execute(querycontext.statement, self._params)
      File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 662, in execute
        params)
      File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 761, in _execute_clauseelement
        compiled_sql, distilled_params
      File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 874, in _execute_context
        context)
      File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1024, in _handle_dbapi_exception
        exc_info
      File "build\bdist.win32\egg\sqlalchemy\util\compat.py", line 163, in raise_from_cause
        reraise(type(exception), exception, tb=exc_tb)
      File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 867, in _execute_context
        context)
      File "build\bdist.win32\egg\sqlalchemy\engine\default.py", line 324, in do_execute
        cursor.execute(statement, parameters)

ProgrammingError: (ProgrammingError) ('42000', "[42000]
  [Microsoft][ODBC SQL Server Driver][SQL Server]Column
  'HR_PERSONNEL.D_DATE_OF_BIRTH' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause. (8120) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server
  Driver][SQL Server]Column 'HR_PERSONNEL.D_DATE_OF_BIRTH' is invalid in
  the select list because it is not contained in either an aggregate
  function or the GROUP BY clause. (8120); [42000] [Microsoft][ODBC SQL
  Server Driver][SQL Server]Column 'HR_PERSONNEL.D_DATE_OF_BIRTH' is
  invalid in the select list because it is not contained in either an
  aggregate function or the GROUP BY clause. (8120); [42000]
  [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not
  be prepared. (8180)") u'SELECT
  count([HR_PERSONNEL].[S_HR_PERSONNEL_ID]) AS value, CASE WHEN
  (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH],
  CURRENT_TIMESTAMP) / ?) < ?) THEN ? WHEN (floor(datediff(day,
  [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / ?) BETWEEN ?
  AND ?) THEN ? ELSE ? END AS anon_1 \nFROM [HR_PERSONNEL] GROUP BY CASE
  WHEN (floor(datediff(day, [HR_PERSONNEL].[D_DATE_OF_BIRTH],
  CURRENT_TIMESTAMP) / ?) < ?) THEN ? WHEN (floor(datediff(day,
  [HR_PERSONNEL].[D_DATE_OF_BIRTH], CURRENT_TIMESTAMP) / ?) BETWEEN ?
  AND ?) THEN ? ELSE ? END' (365.25, 15, 15, 365.25, 15, 19, 19, 100,
  365.25, 15, 15, 365.25, 15, 19, 19, 100)

looks like MSSQL/ODBC bug???