text:
Q: Make Alert Stateful I'm building this app where I need to use a DropdownButton in an Alert. My widget is Stateful and I'm calling SetState, but still when I click into the DropdownItem it doesn't change in the Button.
Code below:
// ignore_for_file: use_key_in_widget_constructors, avoid_print, unrelated_type_equality_checks

import 'dart:convert';
import 'package:http/http.dart' as http;

import 'package:apetit_project/models/app_user.dart';
import 'package:apetit_project/models/reservation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../models/meal.dart';
import '../utils/app_routes.dart';

class MealItem extends StatefulWidget {
  final Meal meal;

  MealItem(
    this.meal,
  );

  @override
  State<MealItem> createState() => _MealItemState();
}

class _MealItemState extends State<MealItem> {
  final List<Reservation> _items = [];
  String dropDownValue = '11:30';

  List<Reservation> get items => [..._items];

  final AppUser? appUser = const AppUser(
    id: 'PedroNovoTeste',
    email: 'email',
    company: 'GTFoods',
  );

  void addReservation(Reservation reservation) {
    //   var resBody = {};
    //  resBody["cnpj"] = "1234567";
    final future = http.post(
      Uri.parse(
          'http://172.16.30.120:8080/ords/apiteste/integrafoods/cadastra-empresa'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        "cnpj": reservation.user,
        "razao": reservation.company,
        "fantasia": reservation.opcao,
      }),
    );

    future.then((response) {
      _items.add(reservation);
    });
  }

  void _newReservation() {
    final newReservation = Reservation(
        user: appUser!.id,
        date: DateTime.now().add(const Duration(days: 2)),
        opcao: widget.meal.id,
        company: appUser!.company,
        resTime: dropDownValue);

    addReservation(newReservation);

    print(newReservation.user);
    print(newReservation.date);
    print(newReservation.opcao);
    print(newReservation.company);
    print(newReservation.isReserved);
    print(newReservation.resTime);
  }

  void _selectMeal(BuildContext context) {
    Navigator.of(context)
        .pushNamed(
      AppRoutes.MEAL_DETAIL,
      arguments: widget.meal,
    )
        .then((result) {
      if (result == null) {
        print('Sem resultado!');
      } else {
        print('O nome da refeição é $result.');
      }
    });
  }

  List<DropdownMenuItem<String>> get dropdownItems {
    List<DropdownMenuItem<String>> menuItems = [
      const DropdownMenuItem(value: "11:30", child: Text("11:30")),
      const DropdownMenuItem(value: "12:00", child: Text("12:00")),
      const DropdownMenuItem(value: "12:30", child: Text("12:30")),
      const DropdownMenuItem(value: "13:00", child: Text("13:00")),
      const DropdownMenuItem(value: "13:30", child: Text("13:30")),
    ];
    return menuItems;
  }

  @override
  Widget build(BuildContext context) {
    final reservation = Provider.of<Reservation>(context);
    final date = DateTime.now().add(const Duration(days: 2));
    String formattedDate = DateFormat('dd/MM/yyyy').format(date);

    return InkWell(
      onTap: (widget.meal.descricao == 'Reservar')
          ? () {
              showDialog(
                context: context,
                builder: (context) {
                  return Dialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30)),
                    child: DecoratedBox(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        gradient: LinearGradient(
                          colors: [
                            Colors.white.withOpacity(0.2),
                            Colors.grey.withOpacity(0.2),
                            Colors.black.withOpacity(0.2),
                          ],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SingleChildScrollView(
                            child: ListBody(
                              children: <Widget>[
                                ListTile(
                                  title: Padding(
                                    padding: const EdgeInsets.only(top: 15),
                                    child: Image.asset(
                                      'assets/images/logo.png',
                                      fit: BoxFit.contain,
                                      height: 80,
                                    ),
                                  ),
                                ),
                                Column(
                                  children: [
                                    Text(
                                      (reservation.isReserved == false)
                                          ? 'Confirmar reserva para o dia $formattedDate no restaurante administrativo da empresa GTFoods(Matriz) para o horário'
                                          : 'Você já possui uma reserva para o dia $formattedDate no restaurante administrativo da empresa GTFoods(Matriz), deseja cancelar sua reserva?',
                                      textAlign: TextAlign.center,
                                      style: const TextStyle(
                                          fontSize: 15,
                                          fontFamily: 'Raleway',
                                          fontWeight: FontWeight.bold),
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        DropdownButton<String>(
                                          value: dropDownValue,
                                          items: <String>[
                                            '11:30',
                                            '12:00',
                                            '12:30',
                                            '13:00',
                                            '13:30',
                                          ].map<DropdownMenuItem<String>>(
                                              (String value) {
                                            return DropdownMenuItem<String>(
                                              value: value,
                                              child: Text(value),
                                            );
                                          }).toList(),
                                          onChanged: (String? newValue) {
                                            setState(() {
                                              dropDownValue = newValue!;
                                            });
                                          },
                                        ),
                                        const Text('?')
                                      ],
                                    ),
                                  ],
                                ),
                                const SizedBox(
                                  height: 10,
                                ),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    if (reservation.isReserved == false)
                                      ElevatedButton(
                                        child: const Text('Sim'),
                                        onPressed: () {
                                          _newReservation();
                                          reservation.toggleReserved();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    if (reservation.isReserved == true)
                                      ElevatedButton(
                                        child: const Text('Sim'),
                                        onPressed: () {
                                          print(reservation.isReserved);
                                          reservation.toggleReserved();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ElevatedButton(
                                      child: const Text('Não'),
                                      onPressed: () => Navigator.pop(context),
                                    ),
                                  ],
                                ),
                                ListTile(
                                  title: Image.asset(
                                    'assets/images/logo_gttech.png',
                                    fit: BoxFit.contain,
                                    height: 40,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              );
            }
          : () => _selectMeal(context),
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 0,
        margin: const EdgeInsets.only(right: 0, left: 0),
        child: Column(
          children: [
            Stack(
              children: [
                ClipRRect(
                  // borderRadius: BorderRadius.only(
                  //   topLeft: Radius.circular(15),
                  //   topRight: Radius.circular(15),
                  //   bottomLeft: Radius.circular(15),
                  //   bottomRight: Radius.circular(15),
                  // ),
                  child: Image.asset(
                    widget.meal.imageUrl,
                    height: (widget.meal.descricao == 'Reservar') ? 50 : 73,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Container(
                  height: (widget.meal.descricao == 'Reservar') ? 0 : 73,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: FractionalOffset.centerRight,
                      end: FractionalOffset.centerLeft,
                      colors: [
                        Colors.grey.withOpacity(0.0),
                        Colors.black.withOpacity(0.9),
                      ],
                      stops: const [0.0, 1.0],
                    ),
                  ),
                ),
                Positioned(
                  bottom: (widget.meal.descricao == 'Reservar')
                      ? 7
                      : (widget.meal.descricao == 'Feijoada')
                          ? 15
                          : (widget.meal.descricao == 'X Salada')
                              ? 15
                              : 0,
                  left: (widget.meal.descricao == 'Reservar') ? 95 : 10,
                  child: Container(
                    width: (widget.meal.descricao.length > 22)
                        ? 300
                        : (widget.meal.descricao.length > 20)
                            ? 210
                            : (widget.meal.descricao == 'Reservar')
                                ? 210
                                : (widget.meal.descricao == 'Bife Americano')
                                    ? 150
                                    : (widget.meal.descricao ==
                                            'Feijão Tropeiro')
                                        ? 150
                                        : (widget.meal.descricao.length > 14)
                                            ? 200
                                            : 150,
                    padding: const EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 15,
                    ),
                    child: Text(
                      widget.meal.descricao,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 24,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Why might it not be changing state? I'm trying and I can't figure out where the problem is. I need that when I select an item it changes in the button but it's not working.

A: Wrap your Dialog with StatefulBuilder and use its setState.
StatefulBuilder(builder: (context, setState) {

    return Dialog();
  },)


text:
Q: can't run python script with crontab and startup application I have a simple python script that compares date of a file to the current date and prints something on screen.
I want to execute this script every time I log in.
I try to add the script to the startup application in Ubuntu that didn't work.
I tried to create a .sh file that have 'python3 code.py' in it and pass this sh file to crontab( through crontab -e command with @reboot /passtofile/script.sh) but I didn't get desired output.
what should I do?

A: Jobs run through cron, crontab, aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment  variable settings are automatically propagated to  your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).
One can set environment variables for all one's cron jobs in the crontab file
Read man 5 crontab.
Look at the results of  echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.
Since the command part of the crontab line is, by default,  interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script  (executable, mounted, starts with #!/bin/bash) which sets up the environment,  then calls the desired program.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Further narrow down regex character set so that one uppercase is mandatory I have a long string like aaaaa123 ** bbbbb444 ** ccccc66 ** ddDddD77 ** eeeee667 and want to grab a substring using a Regex.
What I've got so far:
/[A-Z,a-z,0-9,_-]{7,14}/
This should return any group of 7 to 14 characters consisting of uppercase, lowercase, digits - and _
So far so good.
However, I now want it to be more strict so that at least one uppercase character is mandatory. I.e. in my example only ddDddD77 should match. How do I do that?

A: If a lookahead and \w is supported and the word does not start or end with - you can assert for the length and match at least an uppercase:
\b(?=[\w-]{7,14}\b)[a-z0-9_-]*[A-Z][\w-]*

Regex demo
Another option:
(?<!\S)(?=[\w-]{7,14}(?!\S))[a-z0-9_-]*[A-Z][\w-]*

Regex demo
If the lookbehind is not supported, you could also opt for a capture group:
(?:\s|^)(?=[\w-]{7,14}(?:\s|$))([a-z0-9_-]*[A-Z][\w-]*)

Regex demo


text:
Q: WPF C# .NET Core Compiler-error when compiling for osx-x64 When I tried to compile my WPF C# .NET Core project for "osx-64" I got this error:
There was no runtime package available for "Microsoft.WindowsDesktop.App.WPF" for the specified runtime identifier "osx-x64".
What can I do? Does anyone have an idea?
Thanks in advance.

A: WPF in .NET Core is only available on Windows, see reference.

One of the biggest enhancements is support for Windows desktop applications (Windows only). By using the .NET Core 3.0 SDK component Windows Desktop, you can port your Windows Forms and Windows Presentation Foundation (WPF) applications. To be clear, the Windows Desktop component is only supported and included on Windows.


text:
Q: Create CGContext for CGLayer I want to pre-render some graphics into CGLayer for fast drawing in future.
I found that CGLayerCreateWithContext requires a CGContext parameter. It can be easily found in drawRect: method. But I need to create a CGLayer outside of drawRect:. Where should I get CGContext?
Should I simply create temporary CGBitmapContext and use it?
UPDATE:
I need to create CGLayer outside of drawRect: because I want to initialize CGLayer before it is rendered. It is possible to init once on first drawRect call but it's not beautiful solution for me.

A: There is no reason to do it outside of drawRect: and in fact there are some benefits to doing it inside.  For example, if you change the size of the view the layer will still get made with the correct size (assuming it is based on your view's graphics context and not just an arbitrary size).  This is a common practice, and I don't think there will be a benefit to creating it outside.  The bulk of the CPU cycles will be spent in CGContextDrawLayer anyway.

A: You can create it by this function, you can render your content in the render block
typedef void (^render_block_t)(CGContextRef);

- (CGLayerRef)rendLayer:(render_block_t) block {
    UIGraphicsBeginImageContext(CGSizeMake(100, 100));
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGLayerRef cgLayer = CGLayerCreateWithContext(context, CGSizeMake(100, 100), nil);
    block(CGLayerGetContext(cgLayer));
    UIGraphicsEndImageContext();
    return cgLayer;
}

I wrote it few days ago. I use it to draw some UIImages in mutable threads.
You can download the code on https://github.com/PengHao/GLImageView/
the file path is GLImageView/GLImageView/ImagesView.m


text:
Q: Apollo not returning relational object on create I have the following Mutation:
Mutation: {
  createMessage: async (_, args) => {
    const x = await prisma.message.create({
      data: {
        message: args.message,
        user: {
          connect: {
            id: Number(args.userId)
          }
        },
        session: {
          connect: {
            id: Number(args.sessionId)
          }
        }
      }
    })
    console.log(x)
    return x
  },
},

I create new message and connect it to a user and a session.
This is the typeDef:
type Message {
  id: ID,
  message: String
  user: User
}

type Mutation {
  createMessage(
    sessionId: ID!
    userId: ID!
    message: String!
  ): Message
}

But when I create a message the log on the server shows:

{ id: 23, message: 'This is a message!', userId: 100, sessionId: 6 }

Do I need to change something to include the User and Session relational objects in the create mutation?

A: It's quite easy:
Mutation: {
  createMessage: async (_, args) => {
    const x = await prisma.message.create({
      data: {
        message: args.message,
        user: {
          connect: {
            id: Number(args.userId)
          }
        },
        session: {
          connect: {
            id: Number(args.sessionId)
          }
        }
      },
      include: {
        user: true
      }
    })
    console.log(x)
    return x
  },
},

Just add the include.


text:
Q: How to add an accounts-password package? My platform is windows 7.I want to add the accounts-password package. But I got a "error:CERT_UNTRUSTED".
This is all output error message.

AppData\Local.meteor\leaderboard>..\meteor add accounts-password
Unable to update package catalog (are you offline?)
If you are using Meteor behind a proxy, set HTTP_PROXY and HTTPS_PROXY
  environment variables or see this page for more details:
  https://github.com/meteor/meteor/wiki/Using-Meteor-behind-a-proxy
=> Errors while adding packages:
While downloading npm-bcrypt@0.7.8_2...: error: CERT_UNTRUSTED
Your package catalog may be out of date. Please connect to the
  internet and try again.

Blockquote
I don't know how to fix this problem. Or is there a alternative manual way to add this accounts-password package. Have any suggestions? Many thanks.

A: You have a space in "pa ssword".
Run:
meteor add accounts-password

You'll be good to go.

A: It looks like you are behind the firewall which is conducting SSL Inspection (so it is replacing SSL certificate). If it is so - ask your system administrator to turn off SSL Inspection for your machine and try again.


text:
Q: Dynamic Pivot tables I'm trying to execute multiple pivot tables, dynamically, every time with the column values horizontally.
I tried to execute the following query, but it fails for some reason, even though when I print the query and execute it subsequently, everything works just fine.
DECLARE @sql VARCHAR(MAX) = (
SELECT ' SELECT '+ QUOTENAME(c.name)
    + '
      ,[1] AS a
      ,[2] AS b
      ,[3] AS c
FROM
    (SELECT [ID]
            ,CASE WHEN [c1] < 25 THEN 1
              ELSE CASE WHEN [c1] < 45 THEN 2
              ELSE 3 END END AS cat
            ,' + QUOTENAME(c.name) + '
    FROM [dbo].[table]) p
PIVOT
(
COUNT (ID)
FOR cat IN ([1], [2], [3] )
) AS pvt
ORDER BY [2] desc
'
FROM sys.columns c
    WHERE c.object_id = OBJECT_ID('dbo.SAMR_respons')
    AND c.name NOT IN ('ID')
    FOR XML PATH('')
)

PRINT(@sql)
EXEC(@sql);

Does anyone know what might go wrong?
The error I get is:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ';'.


text:
Q: Sequences with bounded iterated sums Consider double sequences $a_{n,m}\in\mathbb R$ where $n,m\in\mathbb Z,$ satisfying

*

*$a_{n,m}=a_{n-1,m}+a_{n,m-1}$ for all $n,m\in\mathbb Z,$ and

*$\sup_\limits{m\in\mathbb Z}|a_{n,m}|<\infty$ for all $n\in\mathbb Z.$

An example solution is $a_{n,m}=(-1)^m2^{-n}.$ A more general solution is
$$a_{n,m}=\int z^{-m}(1-z)^{-n} d\mu(z),\tag{x}$$
for a
finite signed measure $\mu$ supported on an arc of the unit circle $\{\exp(2\pi i\theta)\mid \theta\in[\epsilon,2\pi-\epsilon]\}$ with $\epsilon>0.$ I am curious if there is a characterization, but to make a specific question:

Is there a solution of (1.) and (2.) not of the form (x)?

My thoughts:

*

*Decreasing $n$ is taking the discrete backwards difference. Increasing $n$ is like choosing a discrete integral.

*Given a row $(a_{n,m})_{m\in\mathbb Z}$ such that $\sup_{m}|a_{n,m}|$ is finite, the previous row is always ok: $\sup_{m}|a_{n-1,m}|$ is automatically finite because $a_{n-1,m}=a_{n,m}-a_{n,m-1}$

*Any row $(a_{n,m})_{m\in\mathbb Z}$ determines $(a_{n,m})_{n,m\in\mathbb Z}$ uniquely if a solution exists. To prove this, by linearity it suffices to show there is a unique solution of conditions 1 and 2 satisfying $a_{0,m}=0$ for all $m.$ Condition 1 gives $a_{1,m}=a_{1,m-1}$ so $a_{1,m}=a_{1,0}$ for all $m.$ This then gives $a_{2,m}=a_{1,0}+a_{2,m-1},$ so $a_{2,m}=a_{1,0}m+a_{2,0}$ for all $m.$ Condition 2 with $n=2$ forces $a_{1,0}=0,$ so $a_{1,m}=0$ for all $m.$ By induction, we get $a_{n,m}=0$ for all $n\geq 0.$ And $a_{n-1,m}=a_{n,m}-a_{n,m-1}$ implies $a_{n,m}=0$ for all $n=-1$ and hence all negative $n$ by induction.

A: The answer is no: not every such double sequence is of the form you describe. I will prove the following things:

*

*Different (complex) measures give rise to different (complex) double sequences;

*The domain of definition is larger than the set of measures specified by OP;

*There exist double sequences meeting the requirements which are not of the form (x) for any complex measure $\mu$ on $\mathbb{T}$.

The main results of the second and third part are listed in blockquote. The textbooks I occasionally refer to are listed at the very end of this post.
Part 0: Prerequisites and notation

*

*Let $\mathbb{N} = \{0,1,2,\ldots\}$ denote the natural numbers with zero.

*Let us denote the space of real or complex double sequences satisfying (1.) and (2.) by $\mathcal S_{\mathbb{R}}$ and $\mathcal S_{\mathbb{C}}$, respectively.

*For $k\in\mathbb{Z}$, let $\lVert \:\cdot\: \rVert_k : \mathcal S_{\mathbb{C}} \to \mathbb{R}_{\geq 0}$ denote the seminorm given by
$$ \lVert \{a_{n,m}\}_{n,m\in\mathbb{Z}} \rVert_k \: := \: \sup_{m\in\mathbb{Z}} |a_{k,m}|. $$
It follows from OP's uniqueness argument that every individual $\lVert \:\cdot\: \rVert_k$ already defines a norm on $\mathcal S_{\mathbb{C}}$, but choosing just one would not give us the right topology on $\mathcal S_{\mathbb{C}}$. More on that later.

*Let $\mathbb{T}$ denote the complex unit circle.

*Let $C(\mathbb{T})$ denote the $C^*$-algebra of all continuous functions $\mathbb{T} \to \mathbb{C}$.

*Let $M(\mathbb{T})$ denote the complex vector space of all (complex) Borel measures on $\mathbb{T}$, which becomes a Banach space with the total variation norm $\lVert \mu\rVert := |\mu|(\mathbb{T})$. Since $\mathbb{T}$ is compact and metrisable, it follows from [Cohn, proposition 7.2.3] that every $\mu \in M(\mathbb{T})$ is automatically regular. Consequently, it follows from the Riesz representation theorem that $M(\mathbb{T})$ is isometrically isomorphic with the Banach space dual of $C(\mathbb{T})$, where the dual pairing is given by $\langle f,\mu\rangle = \int f \: d\mu$.

*Let $\mathcal D(A) \subseteq M(\mathbb{T})$ denote the subspace consisting of those measures for which the formula (x) is well defined, and let $A : \mathcal D(A) \to \mathcal S_{\mathbb{C}}$ denote the linear map given by (x).

Part 1: Injectivity of $A$
Before we determine the domain of definition of $A$, we show that $A$ is necessarily injective. For this we prove the following slightly stronger statement:
Proposition. The map $\phi^t : M(\mathbb{T}) \to \ell^\infty(\mathbb{Z})$ given by $\phi^t(\mu)_m = \int \lambda^m \: d\mu$ is injective.
First proof. Let $\mu,\nu \in M(\mathbb{T})$ be given with $\phi^t(\mu) = \phi^t(\nu)$. Now let $f_\mu,f_\nu \in C(\mathbb{T})^*$ denote the linear functionals associated with $\mu$ and $\nu$. By assumption, $f_\mu$ and $f_\nu$ agree on the functions $\lambda^m \in C(\mathbb{T})$ for all $m\in\mathbb{Z}$. By linearity, $f_\mu$ and $f_\nu$ agree on the linear subspace $V \subseteq C(\mathbb{T})$ spanned by all $\lambda^m$. But this subspace is self-adjoint (we have $\overline\lambda = \lambda^{-1}$ on the unit circle), contains the unit, and separates points, so it follows from the Stone–Weierstrass theorem that $V$ is dense in $C(\mathbb{T})$.  Now $f_\mu$ and $f_\nu$ coincide on a dense subspace, so they must be equal. Consequently, we have $\mu = \nu$, showing that $\phi^t$ is injective. $\quad\Box$
Second proof. Observe that $\phi^t$ is the transpose of the Gelfand representation $\phi : (\ell^1(\mathbb{Z}),*) \to C(\mathbb{T})$; hence the notation $\phi^t$. It is well known that $\phi$ is injective (this is the same as saying that $(\ell^1(\mathbb{Z}),*)$ is semisimple), and the image of $\phi$ is the space of those continuous functions $\mathbb{T} \to \mathbb{C}$ which have an absolutely convergent Fourier series. As such, the image of $\phi$ is dense in $C(\mathbb{T})$, but $\phi$ is not surjective. This gives an alternative proof of the above proposition: we have $\ker(\phi^t) = \text{ran}(\phi)^\perp = 0$; cf. [Conway, proposition VI.1.8 and the bipolar theorem, V.1.8]. Another immediate consequence is that the image of $\phi^t$ is weak-* dense in $\ell^\infty(\mathbb{Z})$, but not weak-* closed or even norm closed. (For the final claim, see [Conway, proposition VI.1.9 and theorem VI.1.10].) $\quad\Box$
It follows that $A$ is also injective.
Part 2: What belongs to $\mathcal D(A)$?
The definition of $\mathcal D(A)$ is at present a little vague. This is in part due to the following technical difficulty: most textbooks on measure theory define integrals over signed or complex measures only for bounded functions, and consequently only define $L^p$ spaces over positive measures. However, there doesn't seem to be a serious problem; we may simply define $\mathscr{L}^1(\mu)$ for a complex measure $\mu$ by
$$ \mathscr{L}^1(\mu) \: := \: \left\{f : \mathbb{T} \to \mathbb{C} \:\: \text{Borel measurable} \:\: \left| \:\:\: f\cdot \frac{d\nu}{d|\nu|} \in \mathscr{L}^1(|\mu|)\right.\right\}, $$
and the integral of a function $f \in \mathscr{L}^1(\mu)$ is given by
$$ \int f\: d\mu \: := \: \int f\cdot\frac{d\nu}{d|\nu|}\: d|\nu|. $$
If $f$ is bounded, then this coincides with the definition of integration as given in [Cohn, section 4.1]; this is proven at the end of [Cohn, section 4.2]. Furthermore, it is shown that $\left|\frac{d\nu}{d|\nu|}\right|$ is $|\nu|$-almost everywhere equal to $1$, so we find
$$ f \in \mathscr L^1(\mu) \quad \Longleftrightarrow \quad f \in \mathscr L^1(|\mu|). $$
Now it is clear that the domain of definition of the operator $A$ is
$$ \mathcal D(A) \: = \: \left\{\mu \in M(\mathbb{T}) \:\: \left| \:\: \frac{1}{(1 - z)^n} \in \mathscr L^1(\mu) \:\: \text{for all $n\in\mathbb{N}$}\right.\right\}. $$

Main result. It is not so hard to see that $\mathcal D(A)$ is larger than the set conjectured by OP:

*

*There are complex measures $\mu\in M(\mathbb{T})$ for which $A(\mu)$ nonetheless defines a real double sequence. A concrete example is the measure given by
  $$ \mu(\{i\}) = \tfrac{1}{2i},\qquad \mu(\{-i\}) = -\tfrac{1}{2i},\qquad \mu(\mathbb{T} \setminus \{i,-i\}) = 0. $$
  The double sequence it defines is given by $a_{n,m} = \text{Im}(i^{-m}(1 - i)^{-n})$. It seems that a complex measure $\mu \in M(\mathbb{T})$ gives rise to a real-valued double sequence if and only if $\mu(\overline X) = \overline{\mu(X)}$ holds for every Borel measurable set $X \subseteq \mathbb{T}$, whereas the real measures are given by the property $\overline{\mu(X)} = \mu(X)$.

*There are more serious counterexamples than the above. Let $\lambda \in M(\mathbb{T})$ denote the Lebesgue measure, and let us say that a positive function $f \in C(\mathbb{T})$ is of rapid decrease near $1$ if $f(z) > 0$ holds for all $z\in\mathbb{T} \setminus \{1\}$, and we have
  $$ \lim_{z \to 1} \frac{f(z)}{(1 - z)^n} \: = \: 0\tag*{(for all $n\in\mathbb{N}$).} $$
  A concrete example of such a function is $f(z) = e^{-\frac{1}{|1 - z|}}$. If $f$ is any such a function, then the measure $\nu(X) := \int_X f \: d\lambda$ belongs to $\mathcal D(A)$, for we have $\frac{f(z)}{(1 - z)^n} \in C(\mathbb{T})$ for all $n\in\mathbb{N}$. However, the resulting measure $\nu$ always has $1$ in its support¹, so it is not of the form described by OP.

  ¹: See [Cohn, section 7.4] for the definition of the support of a regular Borel measure on a locally compact Hausdorff space.

Put in another way: in order for OP's equation (x) to be well defined, it is not necessary that $(1 - z)^{-1}$ is $\mu$-a.e. bounded. It suffices that $(1 - z)^{-n}$ is $\mu$-integrable for all $n \in\mathbb{N}$.
Part 3: $A$ is not surjective
It turns out that, even with the domain of definition stretched as far as possible, the map $A$ is not surjective, so there exist double sequences which are not of the form (x) for any measure $\mu$ on $\mathbb{T}$. We sketch the argument involved. (A full proof was given in a previous version of this answer, but edited out for being way too long.)
Recall from the second proof in part 1 that the natural map $\phi^t : M(\mathbb{T}) \to \ell^\infty(\mathbb{Z})$ fails to be an open mapping. It turns out that a similar statement is true for the map $A : \mathcal D(A) \to \mathcal S_{\mathbb{C}}$. To that end, note that the following (infinite) diagram commutes:
$$\begin{array}{ccccccccc}
 \cdots & \stackrel{D}{\longleftarrow} & M(\mathbb{T}) & \stackrel{D}{\longleftarrow} & M(\mathbb{T}) & \stackrel{D}{\longleftarrow} & M(\mathbb{T}) & \stackrel{D}{\longleftarrow} & \cdots \\[1ex]
 & & \bigg\downarrow{\phi^t} & & \bigg\downarrow{\phi^t} & & \bigg\downarrow{\phi^t} & & \\
 \cdots & \stackrel{\Delta}{\longleftarrow} & \ell^\infty(\mathbb{Z}) & \stackrel{\Delta}{\longleftarrow} & \ell^\infty(\mathbb{Z}) & \stackrel{\Delta}{\longleftarrow} & \ell^\infty(\mathbb{Z}) & \stackrel{\Delta}{\longleftarrow} & \cdots
\end{array}\tag*{$(*)$}$$
Here $\Delta : \ell^\infty(\mathbb{Z}) \to \ell^\infty(\mathbb{Z})$ denotes the discrete backwards difference, and likewise $D : M(\mathbb{T}) \to M(\mathbb{T})$ denotes the corresponding "downward" map that takes a measure $\mu$ and multiplies is by the function $(1 - z)$, or to put it more formally, that turns $\mu$ into the measure $\mu'$ given by
$$ \mu'(X) \: := \: \int_X (1 - z)\cdot \frac{d\mu}{d|\mu|} \: d|\mu|. $$
(Note: in $(*)$, one should not take the maps in the other direction, for they are not continuous!)
The spaces $\mathcal D(A)$ and $\mathcal S_{\mathbb{C}}$ can be considered as the inverse (or projective) limits of the $\mathbb{Z}$-indexed systems defined by the rows of $(*)$, and the corresponding inverse limit topologies turn them into Fréchet spaces. Furthermore, one can show that not only $\phi^t : M(\mathbb{T}) \to \ell^\infty(\mathbb{Z})$ but also $A : \mathcal D(A) \to \mathcal S_{\mathbb{C}}$ fails to be an open mapping. Therefore in particular it cannot be surjective (by the open mapping theorem).
References

*

*[Cohn]: Donald L. Cohn, Measure Theory, second edition (2013), Birkäuser Advanced Texts, Birkhäuser, Basel.

*[Conway]: John B. Conway, A Course in Functional Analysis, second edition, third printing (2007), Springer Graduate Texts in Mathematics 96, Springer-Verlag, New York.

A: I think that there are solutions which are not of the form (x). I only use the following lemma (see Sequence with bounded sums for an explicit construction).

Lemma : Let us consider the operator $T : \mathbf{a} \in \mathbb{R}^{\mathbb{N}} \mapsto \big(\sum \limits_{k=0}^n a_k\big)_{n \ge 0}$. There exists $\mathbf{a} \in \mathbb{R}^{\mathbb{N}}$ such that for all $p \in \mathbb{N}$, $T^p \big(\mathbf{a}\big)$ is bounded, and $\sup_m |\big(T^p \mathbf{a}\big)_m| \ge p^p$.

If you have such a sequence, which we call $(b_n)$, you can define a double sequence $(a_{n,m})$ including $(b_n)$. It is easy to see that it is enough to define only $(a_{0,m})_{m \in \mathbb{Z}}$, and $(a_{n,0})_{n \ge 1}$.
Let $(a_{n,m})_{(n,m) \in \mathbb{Z}^2}$ be the only sequence satisfying $(1)$ and such that :

*

*for $m > 0$, $a_{0,m} = b_m$

*for $n \ge 0$, $a_{n,0} = b_0$

*for $m < 0$, $a_{0,m} = 0$.
As you pointed out in the comments, as $(a_{0,m})_{m \in \mathbb{Z}}$ is bounded, for all $n < 0$, $(a_{n,m})_{m \in \mathbb{Z}}$ is bounded (proof by induction).
Then, it is easy to prove by induction that for $p \ge 0$, $(a_{p,m})_{m \in \mathbb{N}} = T^p \big( (b_m)_{m \in \mathbb{N}} \big)$, so $(a_{p,m})_{m \in \mathbb{N}}$ is bounded, by definition of $(b_m)$.
Finally, by induction on $m$, it is easy to prove that for all $m < 0$, $\forall n \ge 0,\ a_{n,m} = 0$ (the lower-right quarter contains only zeroes). Thus we conclude that for all $n \ge 0$, $(a_{n,m})_{m \in \mathbb{Z}}$ is bounded. Hence
$ $
$$(a_{n,m})_{(n,m) \in \mathbb{Z}^2} \mbox{ satisfies } (1) \mbox{ and } (2).$$
To conclude, note that as mathworker21 pointed out, if $(a_{n,m})$ were of the form (x), we'd have $\sup_n \big( \sup_m |a_{n,m}| \big)^{1/n} < \infty$. However, by definition of $(b_n)$, $\big( \sup_m |a_{n,m}| \big)^{1/n} \ge n$.
Hence $(a_{n,m})$ is not of the form (x).
$ $
Remark : I can change a bit the lemma to conclude that the space of double sequences of the form (x) has a complement of uncountable dimension in the space of double sequences satisfying $(1)$ and $(2)$.

A: As a by-product of my other answer, I found a neat topological argument why there must be more than conjectured by OP.
Prerequisites and notation.

*

*Let $\mathbb{N} = \{0,1,2,\ldots\}$ denote the natural numbers with zero.

*Once again let $\mathcal S_{\mathbb{R}}$ denote the space of all double sequences satisfying (1.) and (2.), and let $\tau_{\mathcal S}$ be the locally convex topology given by the family of seminorms
$$ \left\lVert \{a_{n,m}\}_{n,m\in\mathbb{Z}} \right\rVert_k \: := \: \sup_{m\in\mathbb{Z}} |a_{k,m}|\tag*{($k\in\mathbb{Z}$).} $$
As I pointed out in my other answer, this topology $\tau_{\mathcal S}$ is compatible with a complete invariant metric, for instance
$$ d\big(\{a_{n,m}\},\{b_{n,m}\}\big) \: := \: \sum_{k\in\mathbb{Z}} \frac{1}{2^{|k|}} \cdot \frac{\lVert \{a_{n,m}\} - \{b_{n,m}\}\rVert_k}{1 + \lVert \{a_{n,m}\} - \{b_{n,m}\}\rVert_k}. $$
As such, $(\mathcal S_{\mathbb{R}},\tau_{\mathcal S})$ is a Fréchet space.

*Like in mathworker21's answer, for $\varepsilon \in (0,\pi)$ we let $\mathbb{T}_\varepsilon\subseteq \mathbb{T}$ denote the arc
$$ \mathbb{T}_\varepsilon \: := \: \{e^{\theta i} \: : \: \theta \in [\varepsilon,2\pi-\varepsilon]\}. $$

*Like in my other answer, let $M(\mathbb{T})$ denote the space of all complex Borel measures on $\mathbb{T}$.

*Let $X \subseteq M(\mathbb{T})$ denote the set of all measures $\mu \in M(\mathbb{T})$ supported on a subset of some $\mathbb{T}_\varepsilon$ and such that the double sequence defined by OP's formula (x) is real-valued.

*Let $A : X \to \mathcal S_{\mathbb{R}}$ denote the map defined by OP's formula (x). (Warning: this is not exactly the same as the map $A$ from my other answer. The domain is smaller, and therefore the range is also smaller.)

Solution.
By definition, $\tau_S$ is the smallest topology making all of the seminorms $\lVert \:\cdot\: \rVert_k$ continuous. Hence, for any sequence $\{C_k\}_{k=0}^\infty$ of positive real numbers, the set
$$ \mathcal V\left(\{C_k\}_{k=0}^\infty\right) \: := \: \big\{\{a_{n,m}\}_{n,m\in\mathbb{Z}} \in \mathcal S_{\mathbb{R}} \: : \: \lVert \{a_{n,m}\}_{n,m\in\mathbb{Z}} \rVert_k \leq C_k \ \ \text{for all $k\in\mathbb{N}$} \big\} $$
is closed, being the intersection over all $k\in\mathbb{N}$ of the inverse image of the closed interval $[-C_k,C_k]$ under the continuous map $\lVert\:\cdot\:\rVert_k$. We shall be interested in the sequence $\{W_n\}_{n=1}^\infty$ of closed sets given by
$$ W_n \: := \: \mathcal V\left(\left\{n\cdot \left|\frac{1}{1 - e^{i/n}}\right|^k\right\}_{k=0}^\infty\right). $$

Claim 1. We have
$$ \text{ran}(A) \: \subseteq \: \bigcup_{n=1}^\infty W_n. $$
Proof. Let $\mu \in X$ be given. Suppose that $\mu$ is supported on $\mathbb{T}_\varepsilon$, then by Hölder's inequality we have
$$ \hspace{-18mm}\lVert A(\mu)\rVert_k \: \leq \: \left\lVert \left(\frac{1}{1 - z}\right)^k \right\rVert_{\mathscr{L}^1(|\mu|)} \: \leq \: \lVert 1\rVert_{\mathscr{L}^1(|\mu|)} \cdot \left\lVert \left(\frac{1}{1 - z}\right)^k\right\rVert_{\mathscr{L}^\infty(|\mu|)} \: \leq \: \lVert \mu\rVert \cdot \left|\frac{1}{1 - e^{i\varepsilon}}\right|^k\tag*{($k\in\mathbb{N}$).} $$
Thus, if we take $n := \left\lceil \max(\lVert \mu\rVert,\frac{1}{\varepsilon}) \right\rceil$, then we certainly have $A(\mu) \in W_n$.$\quad\Box$

Claim 2. Every $W_n$ has empty interior.
Proof. The interior of a convex, balanced set is again convex and balanced. Hence, if $W_n$ should have non-empty interior, then in particular $0$ will be an interior point. This is however not the case: pick some $\varepsilon \in (0,\frac{1}{n})$ and let $\mu_\varepsilon \in X \subseteq M(\mathbb{T})$ be the measure defined by
$$ \mu_\varepsilon\left(\{e^{i\varepsilon}\}\right) = \tfrac{1}{2}, \qquad \mu_\varepsilon\left(\{e^{-i\varepsilon}\}\right) = \tfrac{1}{2},\qquad \mu_\varepsilon\left(\mathbb{T} \setminus \{e^{i\varepsilon},e^{-i\varepsilon}\}\right) = 0. $$
The sequence $\{\frac{1}{k} A(\mu_\varepsilon)\}_{k=1}^\infty$ converges to zero in $\mathcal S_{\mathbb{R}}$, but no element of this sequence lies in $W_n$.$\quad\Box$

Conclusion. Now the result follows from the Baire category theorem: each $W_n$ is closed and has empty interior, so their union also has empty interior. It follows that $\text{ran}(A)$ has empty interior as well, so in particular it is not the whole space $\mathcal S_{\mathbb{R}}$.

(Observe the important role played by completeness in both my solutions. This comes to show some of the power of the theory of complete metric spaces.)

A: I wanted to post an answer just containing what is needed to answer the OP's question. This answer is due to Josse van Dobben de Bruyn and not me.
Yes, there is a solution not of the form (x). Define the measure $\mu$ on $\mathbb{T} := \{z \in \mathbb{C} : |z| = 1\}$ by $d\mu = e^{-\frac{1}{|z-1|}}dz$, and let $a_{n,m} = \int_{\mathbb{T}} z^{-m}(1-z)^{-n}d\mu(z)$. Since $\mu$ decays rapidly enough near $1$, $a_{n,m}$ is defined for each $n,m$; in fact, the rapid decay implies $\sup_m |a_{n,m}| \le \int_{\mathbb{T}} |1-z|^{-n}d\mu(z) < \infty$ for each $n$, verifying (2). Also, of course (1) is satisfied. It remains to show $(a_{n,m})_{n,m}$ is not of the form (x). If it were, then we'd have $\int_{\mathbb{T}} z^{-m}d\nu(z) = \int_{\mathbb{T}} z^{-m}d\mu(z)$ for each $m \in \mathbb{Z}$, for some finite, signed $\nu$ supported away from $1$. This means $\nu$ and $\mu$ have the same fourier coefficients and are thus equal, but $\mu$ is supported at/near $1$.
This question seems very trivial in hindsight...


text:
Q: Transfer SoilGrid default projection to a Geographic lat/lon? How do I transfer the SoilGrid default projection to a Geographic lat/lon?
Also, is the SoilGrid data only for 2017 and 2019?

A: SoilGrids WMS services support Geographic lat long projection such as EPSG:4326, you just need to request that CRS in your client (for preview).
SoilGrids WCS raster download services, support EPSG:4326, so you can just request the data in that projection.

A: In addition to nmtoken's answer, there is also this information in the FAQ:

The VRT-mosaics can themselves be easily reprojected using the gdalwarp tool. Considering the size of each mosaic, it is best to require a VRT also as output. For example:
gdalwarp -t_srs EPSG:3035 -of VRT ./sand_60-100cm_Q0.5.vrt ./sand_60-100cm_Q0.5_3035.vrt


text:
Q: El registro de transacciones de la base de datos está lleno tengo un problema cuando intento borrar algunos datos en mi base de datos, cuando hago un delete sql server me manda el siguiente mensaje:
El registro de transacciones de la base de datos 'Finprue' está lleno. Para saber por qué no se puede volver a utilizar el espacio del registro, vea la columna log_reuse_wait_desc de sys.databases
ahora, encontré un código que decía ayudaba a reducir el log de la base de datos y todo funcionaria bien, pero ya lo probé y me dice que el log no existe, aquí les dejo dicho código y salida:
use Finprue
GO
DBCC SHRINKFILE (N'Finprue_Log' , 0, TRUNCATEONLY)
GO
USE [Finprue]
go
ALTER DATABASE Finprue
SET RECOVERY SIMPLE;
GO
DBCC SHRINKFILE (Finprue_Log, 80);
GO
ALTER DATABASE basededatos
SET RECOVERY FULL;

Mens. 8985, Nivel 16, Estado 1, Línea 2
No se encontró el archivo 'Finprue_Log' para la base de datos 'Finprue' en sys.database_files. No existe el archivo o se quitó.
Alguien sabrá alguna forma alterna para solucionar este problema?
Les agradezco sus comentarios, buen día.

A: Ya lo resolví, al parecer no tenía suficiente espacio en el DD de mi servidor, al liberar unos 15gb pude hacer operaciones con la base de datos, queda como precedente como una posible solución por si alguien tiene un problema similar!

A: Cambia a "simple" el modo de recuperación de la Base de datos, luego ejecuta
use Finprue
GO
DBCC SHRINKFILE (N'Finprue_Log' , 0, TRUNCATEONLY)
GO

Y finalmente vuelve a poner la base de datos en modo de recuperación "Full"


text:
Q: How to use get_theme_mod in gutenberg editor wordpress? In my old WordPress themes (before Gutenberg) I used get_theme_mod to get custom values for certain things in the theme.
get_theme_mod( 'news_custom_headline' );

Now I would like to use the gutenberg editor, however still want to access data from the customizer. How can I do something like this:
save({ attributes }) {
   return
Value from backend: get_theme_mod( 'news_custom_headline' )
;
}

A: You don't do that like this. I got it working with a server side rendered block:
In my index.js:
registerBlockType('test/custom-php-render-block', {
    title: "Custom Block Server Side Rendering",
    category: 'widgets',
    edit: () => { return
This is just a placeholder!
},
    save: () => { return null }
});

In functions.php:
function register_my_custom_block() {
    wp_register_script( 'custom-block-php-script', get_template_directory_uri() . '/build/index.js', array('wp-blocks', 'wp-editor'));
    wp_enqueue_script('custom-block-php-script');

    register_block_type('test/custom-php-render-block', [
        'editor_script' => 'custom-block-php-script',
        'render_callback' => 'custom_block_php-render'
    ]);
}

add_action( 'init', 'register_my_custom_block');

function custom_block_php-render($attr, $content) {
    return '
From customizer: ' . get_theme_mod('your-setting') . '
';
}

You can read more about this here: https://awhitepixel.com/blog/wordpress-gutenberg-create-custom-block-part-9-dynamic-blocks-php-render/


text:
Q: Extracting maximum numbers from file names I'm new to bash and wondered if you guys could help - I have a list of files named things like
amp1_X_1
amp1_X_2
...
amp43_X_3
and have to extract the maximum values of the numbers which appear either side of X.
I've been looking at various links to help solve my problem, but when I try and tweak the examples to suit my purpose I get various errors, like "command not found" or %% operators remaining unevaluated.
How do I Select Highest Number From Series of <string>_# File Names in Bash Script
extract numbers from file names
For example, I tried something like
max=-1
for file in amp*_X_1
do
  pattern=_X_*
  num=${file}%%${pattern}
  num=${num}##amp
  echo "num is $num"
  [[ $num -gt $max ]] && max=$num
done
echo "max is: $max"

(credit largely to ghostdog74 in the first link) which would in any case only work for one set of numbers, but it returns with the %% unevaluated. Have I missed something stupid/is there a better way to do this?
Thanks!

A: there are some errors in your script:
1)for file in amp*_X_1
if you want use the files in a specific folder you have to use commands like ls or find
i.e.
for file in $(ls -1 <your file>)
for file in ($find . -name "<your file>")

etc..
2) num=${file}%%${pattern}
use num=${file%%$pattern}
below you can find your script edited:
max=-1
for file in $(find . -name "amp*")
do
  echo "file[$file]"
  pattern=_X_*
  num=${file%%$pattern}
  num=$(echo $num|sed "s/^\.\///g" | sed "s/amp//g")
  echo "num is $num"
  [[ $num -gt $max ]] && max=$num
done
echo "max is: $max"

output:
sh-4.3$ bash -f main.sh
file[./amp1_X_1]
num is 1
file[./amp3_X_2]
num is 3
file[./amp3_X_1]
num is 3
file[./amp43_X_1]
num is 43
max is: 43

now this script is looking for the maximum between the numbers on the left side of X.
From your question isn't clear what's your expected result..
1) find maximum between all numbers on both X side?
2) find maximum between all numbers on left X side?
3) find maximum between all numbers on right X side?
if 1 is the case you have to add another variable, get the value, and check it.
something like
   max=-1
for file in $(find . -name "amp*")
do
  echo "file[$file]"
  pattern=_X_*

  num=${file%%$pattern}
  num=$(echo $num|sed "s/^\.\///g" | sed "s/amp//g")
  echo "num is $num"

  pattern2=*_X_
  num2=${file##$pattern2}
  echo "num2 is $num2"

  [[ $num -gt $max ]] && max1=$num
  [[ $num2 -gt $max ]] && max2=$num2
  if [[ $max1 -gt $max2 ]]; then
        echo "max is: $max1"
  else
        echo "max is: $max2"
  fi

done
#echo "max is: $max"


text:
Q: Permalink misbehaving in Custom Post Types I have a post type named careers which is,
function do_careers() {
 register_post_type('Careers', array(
    'labels' => array(
        'name' => 'Careers',
        'singular_name' => 'Career',
        'add_new_item' => 'Add New Career',
        'edit_item' => 'Edit Career',
    ),
    'description' => 'Careers',
    'public' => true,
    'menu_position' => 20,
    'supports' => array('title')
 ));
}

add_action('init', 'do_careers');

And for the purpose of having /blog/ in permalink of posts I have the custom permalink structure like,
/blog/%postname%/
When I have /blog/ part in the custom permalink I see the career permalink like this https://www.abcd.net/blog/careers/blah-blah-blah/.
When I only have the /%postname%/ in custom permalink I can see that my blog post permalink shows like https://www.abcd.net/blah-blah-blah/. Part/blog/ is not here, but career link is perfect like https://www.abcd.net/careers/blah-blah-blah/.
I want then permalink in the following pattern for all posts(including custom post types).
https://www.abcd.net/post_type/post_name

A: The rewrite argument of register_post_type() will help you with this. The rewrite argument is an array of different arguments, the one you'll need is with_front, which desides whether the permalink base is prepended to your post type. It defaults to true, setting it to false will not include the permalink structure in the permalink. It would look something like this:
function do_careers() {
 register_post_type('Careers', array(
    'labels' => array(
        'name' => 'Careers',
        'singular_name' => 'Career',
        'add_new_item' => 'Add New Career',
        'edit_item' => 'Edit Career',
    ),
    'description' => 'Careers',
    'public' => true,
    'menu_position' => 20,
    'supports' => array('title'),
    'rewrite' => array(
        'with_front' => false,
    ),
 ));
}

add_action('init', 'do_careers');

You can also add a slug argument to the rewrite array to make the post type slug different from the post type name, if you wish to do so.


text:
Q: When two things are so related it is situationally useful to think of them as one thing My line of work is abstract - I could name some items, but it would not help.
So, I have two nouns.  They have a parent-child relationship. But lately I realize that it is sometimes unhelpful to treat these items as though they are separate. That is, the child's allowable behaviors are tightly controlled by the parent's.
'associated' and 'coupled' are too weak
'parasitic' has a negative connotation
'master/slave' ehhh no.
'major/minor' maybe but doesn't really imply behavior, and this is all about behavior.
And I need a word that describes the child item, and a word for the parent too.  I could call the child node 'dependent' but then the parent node would be called ???

A: An example of this relationship occurs in the Observer Design Pattern.
https://en.m.wikipedia.org/wiki/Observer_pattern
The names for the parent and child here would be subject and observer.
A different example, which puts more emphasis on the parent's ability to control as opposed to the child's ability to interpret, can be found in Control Theory.
https://en.m.wikipedia.org/wiki/Control_theory
Here the parent would be the controller. The child could be descibed generically as a dependent.
These are examples from the world of machines. The human world offers many more examples, such as master/servant, parent/child, captain/mate, etc. However, if the intent is to not anthropomorphize the description, electrical and computer engineering offers some possibilities.
In the first example, you have an observing relationship. In the second case, you have a controlling relationship.


text:
Q: WebStorm debugging with Chrome - best Workflow with useful console and setting breakpoints in WebStorm The main thing I want to achieve is setting breakpoints directly in WebStorm instead of having to find them in Chrome again (I currently do this with warnings as the fastest way...), without losing any features available in Chrome.
I'm currently trying to switch from debugging JavaScript in Chrome to debugging in WebStorm directly. I got it setup using Remote Debugging together with the Chrome-plugin and it works quite good.
But the console style and options in WebStorm are far away from what I have in Chrome. console.warn has just the same colors as console.log output and I can't filter the output for errors or warnings. Are there any plugins or options to improve this behavior or do I need to stick to the Chrome console?
And if I fall back to using Chromes console, when starting the developer tools JetBrains debug plugin gets disabled, making the breakpoints set in WebStorm useless - is there a better workflow for getting best out of both worlds?
Update : I am using the "debugger;" command in the code for now, it at least is way better than what I used before. Source : Set a javascript breakpoint in code - in chrome?
I am still open for better suggestions where I don't have to change the code for debugging purposes.
/edit : Here is a screenshot of my console color setup and outputs (with the corresponding commands above them) :

A: There currently seems to be no better solution than using the "debugger;" command in javascript for setting breakpoints (see comments to the question). That way we can use the great browser-debugger while setting breakpoints in the code.


text:
Q: How does sqs message deletion flow works in celery-sqs I was looking for how celery and sqs deletion works?
When does celery delete message from sqs?
Does it delete when message is picked from sqs or after completion of tasks?
What happens if there is some error in task or it raises error?
Will the message (task) will be there if the tasks is taking too long like and 20 mins.

A: When does celery delete message from sqs?
Message will be deleted after completing the task.
What happens if there is some error in task or it raises error?
Message is still with broker, and deleted after max_retries reaches.
Will the message (task) will be there if the tasks is taking too long like and 20 mins?
This depends on visibility timeout. Message goes to "Not Visible" state, till your visibility timeout, after that it is available to worker.
(if visibility timeout is less than retry time, worker will consume same message many times).

Best Practice is (visibility timeout) > (max_retries * retry_time)

A: The selected answer is (unfortunately) incorrect for SQS, as this open issue indicates.
There was an attempt at fixing the issue, as evidenced by this merged PR.
However, there are bugs with the above implementation.
Long story short, messages will be deleted from an SQS queue 100% of the time, regardless of any exception that occurs within the task.
edit: this may have been resolved, per this PR
I'll update this answer after I've confirmed via personal testing that this functions correctly


text:
Q: How can I escape an apostrophe to match data from a MySQL database in Node.js/Discord.js? I know how escaping works in general, but in this case, I cannot get it to give me the desired results.
I have a table with a list of cards in it. At the top of the command, I have the query push each card name into an array as a "master list." Later on in the code, I have the users provide card names they would like to add to their deck. In order to check that they are using cards that exist, exactly as spelled, it takes each card name the user provides and tries to find it in the master list array.
However, when the user provides a card name with an apostrophe in it (i.e. Drago's Fury), it refuses to find the card name in the list.
I have tried replacing all occurrences of ' with \' and '' and several combinations of the two, multiple \'s and multiple ' 's in various amounts. Nothing seems to let me match it. Drago's Fury in the table does contain the 's in the name as expected, because I was able to put it into the table by escaping it with \'.
Here's the code I have:
con.query(`SELECT * FROM cardsmaster`, (error, rows, fields) => {
    let cardsList = []
    for (var i in rows) {
        cardsList.push(rows[i].name)
    }
});

Here is how Drago's Fury is listed in the MySQL table:

This is what I'm using right now to try and escape it and make it find Drago's Fury when it is provided inside Discord from a user:
cardsToAdd = cardsToAdd.content.replace(/'/gi, "\'");

This is how cardsToAdd displays Drago's Fury when it's logged after the replacement:

But then I receive this error:

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Fury, Fierce Boost, Fierce Boost, Fiery Rage, Fire Boost, Fire Boost, Magma Bo' at line 1

So, I tried:
cardsToAdd = cardsToAdd.content.replace(/'/gi, "\\'");

I was thinking that the first \ would escape the second \ and the apostrophe, but that isn't exactly what I want. The incoming value is the same, except that it has double quotes instead of single, so I'm not certain if that is causing the problem or not...
This is the section that tries to take what the user gives and finds it in the master list:
let usercardnamearray = cardsToAdd.split(", ")

let matchedcards = []
let unmatchedcards = []

for (let i = 0; i < usercardnamearray.length; i++) {

    console.log(usercardnamearray[i])

    let found = cardsList.indexOf(`${usercardnamearray[i]}`)
    console.log(found)

    if (found >= 0) {
        matchedcards.push(usercardnamearray[i])
    } else if (found == -1){
        unmatchedcards.push(usercardnamearray[i])
    }
}

How can I consistently match the provided name in the master list?

A: As explained in the comments, by using placeholders (?), the input is automatically escaped for you; the node-mysql driver uses mysql.escape() for them on its own. This will prevent injection and your current error, without you having to do anything else yourself. Your apostrophe won't trigger the same error since it's being read literally rather than as part of the statement.
Example usage:
const name = "Drago's Fury";

con.query("SELECT * FROM cardmaster WHERE name = ?", [name], (err, rows) => {
  if (err) return console.error(err);

  console.log(rows);
})


text:
Q: I am trying to correct this error code in T-SQL that states that I have an invalid column This was my original question:
"What would be the correct syntax and join (if any) of a subquery that would return all of the employees first and last name from the employee's table, and return their department name from the department table, but only those employees who more than the average salary for their department? Thanks for your answers"
After using Mitch Wheat's example (and taking his well deserved admondishment), I added a column to my DEPARTMENT table in my database and implemented this code:
ALTER TABLE DEPARTMENTS
ADD Salary money
GO
select First_Name, Last_Name, department_Name
from Employees e join
   (select Department_Name,AVG(Salary) AS averageSalary
     from DEPARTMENTS d
     join Employees e ON e.Department_Id=d.Department_Id
     group by  Department_Name) ds
on ds.averageSalary=e.Employee_Id
where e.salary>ds.AverageSalary

However, I still got this error:
Msg 207, Level 16, State 1, Line 8
Invalid column name 'salary'.

Why does SALARY continues to be an invalid column name?

A: You've perhaps got some case sensitive collation enabled, which would affect the case sensitivity of column names. Note your added column is 'Salary', but your query references 'salary'.
Correct the case and you should be fine.
See this related question for more on this.
(Note also LittleBobbyTables (great nick, btw!) comment about your query - there's an odd join clause there!)

A: Are you sure you have a salary column in Employee table? (e.salary)
The Salary column you added is on Department table (d.Salary) to store the average salary of the department I suppose.
Also as Paul Dixon stated, case of column names can be important too.


text:
Q: Terminate existing pool when all work is done Alright, brand new to gpars so please forgive me if this has an obvious answer.
Here is my scenario.  We currently have a piece of our code wrapped in a Thread.start {} block.  It does this so it can send messages to an message queue in the background and not block the user request.  An issue we have recently ran into with this is for large blocks of work, it is possible for the users to perform another action which would cause this block to execute again.  As it is threaded, it is possible for the second batch of messages to get sent before the first causing corrupted data.
I would like to change this process to work as a queue flow with gpars.  I've seen examples of creating pools such as
def pool = GParsPool.createPool()

or
def pool = new ForkJoinPool()

and then using the pool as
GParsPool.withExistingPool(pool) {
    ...
}

This seems like it would account for the case that if the user performs an action again, I could reuse the created pool and the actions would not be performed out of order, provided I have a pool size of one.
My question is, is this the best way to do this with gpars?  And furthermore, how do I know when the pool is finished all of its work?  Does it terminate when all the work is finished?  If so, is there a method that can be used to check if the pool has finished/terminated to know I need a new one?
Any help would be appreciated.

A: No, explicitly created pools do not terminate by themselves. You have to call shutdown() on them explicitly.
Using withPool() {} command, however, will guarantee that the pool is destroyed once the code block is finished.

A: Here is the current solution we have to our issue.  It should be noted that we followed this route due to our requirements

*

*Work is grouped by some context

*Work within a given context is ordered

*Work within a given context is synchronous

*Additional work for a context should execute after the preceding work

*Work should not block the user request

*Contexts are asynchronous between each other

*Once work for a context is finished, the context should clean up after itself

Given the above, we've implemented the following:
class AsyncService {
    def queueContexts

    def AsyncService() {
        queueContexts = new QueueContexts()
    }

    def queue(contextString, closure) {
        queueContexts.retrieveContextWithWork(contextString, true).send(closure)
    }

    class QueueContexts {
        def contextMap = [:]

        def synchronized retrieveContextWithWork(contextString, incrementWork) {
            def context = contextMap[contextString]

            if (context) {
                if (!context.hasWork(incrementWork)) {
                    contextMap.remove(contextString)
                    context.terminate()
                }
            } else {
                def queueContexts = this
                contextMap[contextString] = new QueueContext({->
                    queueContexts.retrieveContextWithWork(contextString, false)
                })
            }

            contextMap[contextString]
        }

        class QueueContext {
            def workCount
            def actor

            def QueueContext(finishClosure) {
                workCount = 1
                actor = Actors.actor {
                    loop {
                        react { closure ->
                            try {
                                closure()
                            } catch (Throwable th) {
                                log.error("Uncaught exception in async queue context", th)
                            }

                            finishClosure()
                        }
                    }
                }
            }

            def send(closure) {
                actor.send(closure)
            }

            def terminate(){
                actor.terminate()
            }

            def hasWork(incrementWork) {
                workCount += (incrementWork ? 1 : -1)
                workCount > 0
            }
        }
    }
}


text:
Q: Get into orbit from the Redbull jump position to a satellite position by using a cord/rope? Its difficult to put this into the title.
I was watching the Redbull Jump and noticed that the height of this is at 39 kilometres (24 mi) the atmosphere pressure is at I believe about 0.4% of that at sea-level. I was imagining, what if a large satellite dragged a cable (bungie cord, rope) below it into the atmosphere and the person grabbed onto the cord that is below the satellite, from the position of the Redbull jump altitude. The satellite may or may not be geo-stationary.
Since the atmosphere pressure is low, even if the cable was moving through the atmosphere, its air friction would be relatively low and therefore its movement through the atmosphere wouldn't be much of a concern. Maybe there would be a lower chance of the cable breaking, also less cable length and therefore less weight could be used.
Would this be a better way to get an object into space when compared with a full cable from the satellite to earth as in the traditional space elevator idea http://en.wikipedia.org/wiki/Space_elevator.
Can you compare and contrast the two options against each other?
Photo of Red Bull Jump
http://i.imgur.com/thjAO.jpg

A: The practical lowest orbit is around 300km and a velocity of 8km/s - around 26 times the speed of sound at the altitude of the balloon jump.
So imagine the mass of a 300km long rope and even with a thin atmosphere there is quite a lot of friction on something moving at Mach 26

A: Your biggest issue is simply that without a tether and a counterweight, your cable is effectively just sitting in a very precarious equilibrium (at best).  Moving any weight up the cable causes the cable to be pulled downwards, and unless you counter this somehow, your cable will eventually fall to the ground.  In fact, the friction of the atmosphere itself (however small it may be) will eventually drag it down, unless you provide some kind of constant thrust to counter it.
The space elevator design works around this problem using a counterweight - the weight itself is placed in a position so that it would "fly away" if it wasn't tethered to the ground.  This means that the cable is effectively being pulled away from the ground, and it is this force  which allows you to traverse it without it falling back down to the ground.  It's basically harnessing the earth's rotation (and the strength of the cable) to keep the cable in position.
Aside from this, you'd typically want your space elevator to be a lot longer than just a few hundred kilometers to get the best practical uses (e.g. you'd have to be around 50,000km to have escape velocity without any additional thrust).  So basically, the first 39km isn't really the problem.


text:
Q: Tracking keywords in a live stream of tweets I installed and tried out tweepy, I am using the following function right now:
from API Reference

API.public_timeline()
Returns the 20 most recent statuses from
non-protected users who have set a custom user icon. The public
timeline is cached for 60 seconds so requesting it more often than
that is a waste of resources.

However, I want to do extract all tweets that match a certain regular expression from the complete live stream. I could put public_timeline() inside a while True loop but that would probably run into problems with rate limiting. Either way, I don't really think it can cover all current tweets.
How could that be done? If not all tweets, then I want to extract as many tweets that match a certain keyword.

A: The streaming API is what you want. I use a library called tweetstream. Here's my basic listening function:
def retrieve_tweets(numtweets=10, *args):
"""
This function optionally takes one or more arguments as keywords to filter tweets.
It iterates through tweets from the stream that meet the given criteria and sends them
to the database population function on a per-instance basis, so as to avoid disaster
if the stream is disconnected.

Both SampleStream and FilterStream methods access Twitter's stream of status elements.
For status element documentation, (including proper arguments for tweet['arg'] as seen
below) see https://dev.twitter.com/docs/api/1/get/statuses/show/%3Aid.
"""
filters = []
for key in args:
    filters.append(str(key))
if len(filters) == 0:
    stream = tweetstream.SampleStream(username, password)
else:
    stream = tweetstream.FilterStream(username, password, track=filters)
try:
    count = 0
    while count < numtweets:
        for tweet in stream:
            # a check is needed on text as some "tweets" are actually just API operations
            # the language selection doesn't really work but it's better than nothing(?)
            if tweet.get('text') and tweet['user']['lang'] == 'en':
                if tweet['retweet_count'] == 0:
                    # bundle up the features I want and send them to the db population function
                    bundle = (tweet['id'], tweet['user']['screen_name'], tweet['retweet_count'], tweet['text'])
                    db_initpop(bundle)
                    break
                else:
                    # a RT has a different structure.  This bundles the original tweet.  Getting  the
                    # retweets comes later, after the stream is de-accessed.
                    bundle = (tweet['retweeted_status']['id'], tweet['retweeted_status']['user']['screen_name'], \
                              tweet['retweet_count'], tweet['retweeted_status']['text'])
                    db_initpop(bundle)
                    break
        count += 1
except tweetstream.ConnectionError, e:
    print 'Disconnected from Twitter at '+time.strftime("%d %b %Y %H:%M:%S", time.localtime()) \
    +'.  Reason: ', e.reason

I haven't looked in a while, but I'm pretty sure that this library is just accessing the sample stream (as opposed to the firehose). HTH.
Edit to add: you say you want the "complete live stream", aka the firehose. That's fiscally and technically expensive and only very large companies are allowed to have it. Look at the docs and you'll see that the sample is basically representative.

A: Take a look at the streaming API.  You can even subscribe to a list of words that you define, and only tweets that match those words are returned.
The streaming API rate limiting works differently: you get 1 connection per IP, and a maximum number of events per second.  If more events occur than that, then you only get the maximum anyways, with a notification regarding how many events you missed because of rate limiting.
My understanding is that the streaming API is most suitable for servers that will redistribute the content to your users as needed, instead of being accessed directly by your users - the standing connections are expensive and Twitter starts blacklisting IPs after too many failed connections and re-connections, and possibly your API key afterwards.


text:
Q: Get values from multiple mat-sliders dynamically created within ngFor I am dynamically creating multiple mat-sliders in Angular as follows:
<ng-container *ngFor="let parameter of parameterValues; let i = index;">
  <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" id="{{ 'myslider' + i }}"></mat-slider>
</ng-container>

When any of the slider positions are changed, I want to fire an event which subsequently calls another function which receives an array 'sliderValues' which contains each of the dynamically created mat-slider values. I'm attempting this with:
  onInputChange(event: MatSliderChange) {
   for (let i = 0; i < this.results.parameterNames.length; i++) {
    const theid = "myslider" + i;
    var ele = document.getElementById(theid)
    console.log((ele as HTMLInputElement).id + " is the id");
    console.log((ele as HTMLInputElement).value + " is the value");
    this.sliderValues.push((ele as HTMLInputElement).value);
   }
   //some function called here which accepts 'this.sliderValues' as a parameter
  }

This isn't currently working; I cannot access the values of the sliders. In the console I see 'id' reported correctly but 'value' is 'undefined'. Any help appreciated, I'm open to doing it in a completely different way if needs be.

A: I found a cleaner way of doing this. The value can be obtained from:
event.value

and the ID from:
event.source._elementRef.nativeElement.id

Both 'value' and 'source' are accessible from the MatSliderChange 'event' object


text:
Q: Get child element inside a known parent, with a known *part* of child's ID Let's say (just for test) I have this code:

Now let's say I have the "p1" div inside the variable: var node.
All I know is - there is a title inside my node var, which is an element with an id starts with "title".
How can I:
1) Recursivly search for this child inside my current parent.
2) Search only by its ID substr ("title" part).
3) Finish the function when I found it.
Please show me a live example if you can :)
Thank you!

A: You can use querySelector and the css 'starts-with' attribute selector for this:
var p1 = document.querySelector('.p1'),
    titleChild = p1.querySelector('[id^="title"]');

A: This is how you could do it recursively, if for some reason you didn't want to use queryselector.
function getChildByPrefix(parent, prefix) {
    var i, child;
    if (parent.id.substr(0, prefix.length) == prefix) {
        return parent;
    }
    for (i = 0; i < parent.children.length; i++) {
        child = getChildByPrefix(parent.children[i], prefix);
        if (child) {
            return child;
        }
    }
}

jsfiddle


text:
Q: Invalid parameter Facebook video ad creative in Facebook Marketing API I am getting the same error while creating Ad Creative via Facebook Marketing API. I followed their guide but doesn't work. Facebook video ad creative reference
    $config = Config::get('facebook');
    $data['account_id'] = 'act_'.$config['ad_account_id'];
    $data['page_id'] = $config['page_id'];

    // Init facebook
    $api = Api::init($config['app_id'], $config['app_secret'], $config['access_token']);

    // Create product catalog
    $product_catalog = new ProductCatalog(null,  $config['business_id']);
    $product_catalog->setData(array(
        ProductCatalogFields::NAME => "Catalog",
    ));
    $product_catalog->create();

    $product_catalog_id = $product_catalog->id;

    // Setup Feed
    $product_feed = new ProductFeed(null, $product_catalog_id);
    $product_feed->setData(array(
        ProductFeedFields::NAME => 'Campaign Feed',
        ProductFeedFields::SCHEDULE => array(
            ProductFeedScheduleFields::INTERVAL => 'DAILY',
            ProductFeedScheduleFields::URL => 'http://example.com/facebook/dpa_product_catalog_sample_feed.csv',
            ProductFeedScheduleFields::HOUR => 22,
        ),
    ));
    $product_feed = $product_feed->create();

    // Create  Product Set
    $product_set = new ProductSet(null,  $product_catalog_id);
    $product_set->setData(array(
        ProductFeedFields::NAME => 'All Product',
    ));
    $product_set->create();

    $data['product_set_id'] = $product_set->id;

    $video = new Advideo(null, $data['account_id']);
    $video->{AdVideoFields::SOURCE} = public_path().'/facebook/video-demo.mp4';
    $video->create();

    $video_data = new AdCreativeVideoData();
    $video_data->setData(array(
      AdCreativeVideoDataFields::IMAGE_URL => 'http://example.com/facebook/resize-image.jpg',
      AdCreativeVideoDataFields::VIDEO_ID => $video->id,
      AdCreativeVideoDataFields::CALL_TO_ACTION => array(
        'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
        'value' => array(
          'page' => $data['page_id'],
        ),
      ),
    ));

    $object_story_spec = new AdCreativeObjectStorySpec();
    $object_story_spec->setData(array(
      AdCreativeObjectStorySpecFields::PAGE_ID => $data['page_id'],
      AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
    ));

Above these code working and return response but when I call ad creative, the API return "Invalid parameter"
    $creative = new AdCreative(null, $data['account_id']);
    $creative->setData(array(
      AdCreativeFields::NAME => 'Video Ad Template Creative Sample',
      AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
      AdCreativeFields::PRODUCT_SET_ID => $data['product_set_id'],
    ));

    $creative->create();

A: Might be your issue is in creating AdCreativeVideoData.
search for line
AdCreativeVideoDataFields::IMAGE_URL => public_path().'/facebook/resize-image.jpg',

Here IMAGE_URL  requires url path like http://example.com/myimage.jpg. You are giving directory path that might cause problem.
If your image is not directly accessible from URL then you should create IMAGE_HASH. For this see below.
try {
        $image = new AdImage(null, $data['account_id']);
        $image->{AdImageFields::FILENAME} = public_path().'/facebook/resize-image.jpg';

        $image->create();
        // Image_hash = $image->hash
    } catch (Exception $e) {
        echo 'Error message: ' . $e->getMessage() . "\n" . "
";
        echo 'Error Code: ' . $e->getCode() . "
";
    }

And replace IMAGE_URL to IMAGE_HASH in your AdCreativeVideoData like this
$video_data = new AdCreativeVideoData();
    $video_data->setData(array(
      AdCreativeVideoDataFields::IMAGE_HASH => $image->hash,
      AdCreativeVideoDataFields::VIDEO_ID => $video->id,
      AdCreativeVideoDataFields::CALL_TO_ACTION => array(
        'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
        'value' => array(
          'page' => $data['page_id'],
        ),
      ),
    ));


text:
Q: How to pass this mysql addition to jpql? Good afternoon, I have this query which I have in MYSQL and it gives me a data of a sum but I want to transfer that query to JPQL language.
 SELECT SUM(`TOTAL_HORA_HOMBRE`) FROM `tiempos` WHERE `ID_ORDENTRABAJO` = 4696;

Thanks.

A: JPQL syntax is very close to standard SQL.
But MySQL uses the back-ticks to delimit table names and other identifiers. This is nonstandard.
Take out the back-ticks and I believe this query will work fine.
SELECT SUM(TOTAL_HORA_HOMBRE) FROM tiempos WHERE ID_ORDENTRABAJO = 4696;

See http://docs.oracle.com/javaee/7/tutorial/persistence-querylanguage.htm#BNBTG for full documentation on JPQL.

A: This is a native SQL query. To use JPQL you have to have a java class annotated with the @Entity annotation and @Table annotation and pointing to the tiempos table.
If your entity would look like:
    @Entity
    @Table(name = "tiempos")
    public class Tiempos {

    @Column(name = "TOTAL_HORA_HOMBRE")
    Double totalHolaHombre;

    @ManyToOne
    @JoinColumn(name = "ID_ORDENTRABAJO")
    Ordentrabajo ordentrabajo;
    }

Then the JPQL query could look like:
SELECT SUM(t.totalHolaHombre) FROM Tiempos t WHERE t.ordentrabajo = :paramOrdentrabajo;


text:
Q: PHP header and $_SESSION I'm currently building a CMS and I'm having an issue with PHP sessions:

*

*Anywhere on my website user can start CMS by adding query string to URL -> ?mod=admin

*?mod=admin will redirect to login.php

*After authentication I would like to redirect user to page he came from with CMS functionalities enabled

For that I store current page url in a session before user go to login.php
url.class.php script
function curPageURL() {
 session_start();
 $pageURL = 'http';
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["PHP_SELF"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"];
 }
 $_SESSION['url'] = $pageURL;
}

Login.php script:
if validation successful I start a session and TRY to redirect user to page he came from:
if($num_rows == 1){
  session_start();
  $_SESSION['username'];
  header('Location: ' . $_SESSION['url']);
}

I get a "session had already started" error.
But if I redirect to a specific page (homepage for instance) then all is working fine.
for instance -> header('Location: index.php');

A: If thats the error you are getting then you need to check to see if you've already started the session somewhere else. In which case you need to put:
if(!isset($_SESSION)){
    session_start();
}

In place of where you put your normal session_start().

A: Can you not just redirect to the previous page using $_SERVER['HTTP_REFERER']?
What actually happens when you try to run your script in it's current state?

A: In url.class.php, has you already started the session? Your problem could be that you haven't started the session, and hence no session data can be stored.
In your url.class.php try checking that the session variables hold the values that you want.

A:
Anywhere on my website user can start CMS

I assume you mean that the website is implemented via a CMS and that the user can gain access to elevated privileges / additional functionality at any stage by appending to the query string.

store current page url in a session

Erk.
This is not the right place to store this information - it should be passed via the URL (or via POST - but that's not going to work across redirection):
session_start();
if (!is_auth_for_cms() && $_GET['mod']=='admin') {
     // simplified a bit...
     $comeback='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
     // rewriting the get trigger avoids short circuit looping problems
     $comeback=urlencode(str_replace('mod=admin', 'mod=auth', $comeback));
     header("Location: " 'http://' . $_SERVER['HTTP_HOST'] . "/login.php?backto=$comeback";
}

Leaving aside the typos in your code, what is the question?
if($num_rows == 1){
  session_start();
  $_SESSION['username'];
  header('Location: ' . $_SESSION['url']);
}

What do you think the third line does?


text:
Q: does live usb 3 work faster than a live usb 2 I have bought a new notebook which has one usb2 and 2 usb3  . I wanna ask if I buy a usb 3 flash disk and make it a live usb  ,would this live usb (usb 3.0) work 10 times faster than live usb (usb 2) ?
thanks

A: Short answer: No.
My recommendation:
Get a small (2,5" USB3) external harddisk instead of a USB flash. This will make your system feel 10 times as fast, even if the transfer speed isn't. Or, if you have the cash, get a cheap 64GB external SSD.
The reason is that with normal USB flash media the access times are really slow, with harddisks this is much better, and with SSD disks they are another 10x faster. The raw data rate of the bus (USB2 vs. USB3) also differs, but doesn't matter so much unless you do a lot of raw data transfer (i.e. copying very few very large files).
I have tried all of the above. Summary:

*

*USB3 stick on USB3 port: Works, is usable, boots in ~60 seconds (new install).

*USB3 stick on USB2 port: Works, is usable, boots in ~65 seconds (new install).

*USB3 disk on USB3 port: Works, is a lot faster, boots in ~40 seconds (new install).

*USB3 disk on USB2 port: Works, also a lot faster, boots in ~50 seconds (new install).

When using the harddisk the actual port (USB2 vs USB3) doesn't matter so much in daily usage. I connect it to the USB3 port unless I have to transfer a lot of data to a second USB3 disk, in which case this disk will get the USB3 port.
Here are the raw data rates of the respective combinations:

*

*USB3 stick on USB3 port: ~30 MB/s read, ~10MB/s write

*USB3 stick on USB2 port: ~20 MB/s read, ~10MB/s write

*USB3 disk on USB3 port: ~75..90 MB/s according to hdparm

*USB3 disk on USB2 port: ~25..35 MB/s according to hdparm

But, as I said, these are not the primary concern for a system disk. The access times are much more important.

A: would depend on the flash drives read speed, just cause something says it uses a new interface does not mean it has anything to gain (eg sata3 HDDs)
also i think it would require the linux kernel you are booting to support usb3 for it to get the extra speed, so don't expect ubuntu 10.04 to boot faster with it
if you require a special driver for your usb3 controller don't expect it to boot faster
i have not tried booting with a usb3 drive, so consider this general info


text:
Q: Is it possible to do echo something if an ACF field DOESNT exist? I have a radio button ACF fields in WordPress, with two buttons 'svarvning' and the other 'frasning', but my acf field also has a "custom" button as well

I want to echo the value of 'custom field' if neither of the 'svarvning' or 'frasning' are true.
Is this possible?
I've got it to work if its TRUE
<?php
    if (get_field('kurstyp') !== 'svarvning' . 'frasning') {
       echo "It's not equal!"
    } else {
       die;
    }
?>

Thank you!!

A: I think you just need to fix the condition check, as it stands, it is concatenating your options into one that doesn't exist.
<?php
    if (get_field('kurstyp') !== 'svarvning' && get_field('kurstyp') !== 'frasning') {
       echo "It's not equal!"
    } else {
       die;
    }
?>

If you have a large amount of values to compare, you can also check if value is in a list of possibilities, something like this:
    $array=array('frasning', 'svarvning', 'etc');

    if (in_array(get_field('kurstyp'),$array))
    {
      echo 'Value found';
    } else {
      echo 'Not found';
    }

A: Try with this condition.
if( get_field('kurstyp') == 'svarvning' || get_field('kurstyp') == 'frasning' ){
    // Choice Value
} else {
    // Button value
}


text:
Q: Swift: print array values sort by added My code :
internal static var myList = [Int: String]()

let data = "1:Tea#12:Food#2:Milk#7:Juice#4:Coffee"
let array = data.components(separatedBy: "#")
for value in array {
    let val = value.components(separatedBy: ":")
    myList[Int(val[0])!] = "\(val[1])"
}

Now print array :
var j = 0
for sort in myList {
    print("\(sort.value) (+\(sort.key))")
}

Output :
Tea
Milk
Coffee
Juice
Food

But i want print by added to array :
Tea
Food
Milk
Juice
Coffee

My array print values by key, but i want print by added to array

A: Use a struct
struct Item {
    let added : Int
    let index : Int
    let name : String
}

and map the array of the string components to instances of that struct
var myList = [Item]()

let data = "1:Tea#12:Food#2:Milk#7:Juice#4:Coffee"
for (index, element) in data.components(separatedBy: "#").enumerated() {
    let val = element.components(separatedBy: ":")
    myList.append(Item(added: index, index: Int(val[0])!, name: val[1]))
}
print(myList)


text:
Q: Python pexpect - redirect child stdout to a tkinter text widget I'm developing a python script that calls and executes a csh script. For this I'm using the pexpect.spawnu that calls the script and sends an option every time that csh script asks for it.
My problem is that I need to redirect the stdout of csh script to a tkinter text widget in real time but at this moment the information is written to the text widget only when child is closed.
I've already tried to redirect all child.logfile to the stdout and the stdout to the text widget but even so the information is written only when child is closed.
child = pexpect.spawnu('script_name'+ param1 + ' '+ param2, timeout=None)

child.logfile = sys.stdout

for line in child:

    self.text1.insert(tk.INSERT, line) # this will be inserted only when child is closed

    if 'option' in line:
       child.sendline(opt1)

child.close()

I'm trying to put the child.logfile to insert the stdout directly in the text widget but I still cannot.
Thanks.
[EDIT]
See the solution in the comment.

A: It seems the text widget was being updated only when class finishes the execution.
After the insert I only need to update the text widget to view the information in real time like:
child = pexpect.spawnu('script_name'+ param1 + ' '+ param2, timeout=None)

child.logfile = sys.stdout

for line in child:

    self.text1.insert(tk.INSERT, line)
    self.text1.update() # update the information in the text widget

    if 'option' in line:
       child.sendline(opt1)

child.close()

It's solved, thanks!


text:
Q: How can I limit the display to distinct records? As shown in the picture below, there are redundant records.  How can the redundancy be removed?
Here's my code:
<?php
$YearNow=Date('Y');
include('../connection/connect.php');
$result = $db->prepare("SELECT * FROM studentvotes,student where student.idno = studentvotes.idno");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
    ?>

        <?php echo $row['idno']; ?>
        <?php echo $row['candid']; ?>

    <?php
}
?>

A: just add groupby to your query like
$result = $db->prepare("SELECT * FROM
                        studentvotes,student
                        where student.idno = studentvotes.idno
                        GROUP BY student.idno
                      ");

for more details please read @pupil Answer.
i hope this is working for you.

A: You need to use GROUP BY.
Change your SQL To:
SELECT * FROM studentvotes,student where student.idno = studentvotes.idno
GROUP BY student.idno

With GROUP BY, you specify a column (even multiple columns) to group with.
The results are grouped by those columns it means those columns (combinations if multiple) will come only once in the result set.
For example, your table has multiple entries of iDno.
When we fire SELECT query, it will return all rows having multiple instances of iDno.
If we apply GROUP BY, it will return results grouped by iDno.

A: You can use GROUP BY for not displaying redundant records.
$result = $db->prepare("SELECT *
             FROM   studentvotes,
             student
             WHERE  student.idno = studentvotes.idno
             GROUP  BY student.idno
");


text:
Q: C# How can I separate a tab from tabcontrol like Firefox or Google Chrome? I add a tab to my tabcontrol with a buttonclick and I can close these tabs with the middle mouse button. Now I want add that I can separate the tabs like Chrome or Firefox. For that I must click down the mouse and move them out to separate which handler is that or how can i realize that?
Update
I use Visual Studio 2015 with Winforms

A: I think what you should do is create a new control on click, one that has all the children of the tab you want to separate (and then dispose the old tabwindow control). Then when you have  this separate control, you can implement dragging, and handle a drop on the tab control you want it to add to. The dropping handler would contain code that transforms the new control back to a tabwindow, and adds it to the tabcontrol.


text:
Q: A Tic-Tac-Toe win function Hello everyone I am building a C program for tic-tac-toe and
I have problem in finding its best move

*

*I first put my two 'X' and then put my opponents 'O' at its best
position (i.e. Not giving me a chance to win).

*Then put my 'X' in blank places and check for my winning chance. If not vacate it and continue.

But I am finding difficulty in checking my winning chance.
When I put my last X the check method increments the chance variable by 1.
But when I change my X position to count another chance the function the   pre-counted (i.e. the chance produced by the X which were put at the starting)
This is my code example:
char a[3][3];
int check(void)
{
   char op='X';
   int e,w,p=0;
   int      i=0,j;
   for(w=0;w<3;w++)
   {
      for(e=0;e<3;e++)
      {
         if(a[w][e]=='_')
         {
            a[w][e]=op;
            pri();
            i=0;
            for(j=0;j<3;j++)
            {
               if(a[i][j]==op && a[i+1][j]==op && a[i+2][j]==op)
               {
                  chance++;   a[w][e]='_';
               }
            }
            j=0;
            for(i=0;i<3;i++)
            {
               if(a[i][j]==op && a[i][j+1]==op && a[i][j+2]==op)
               {
                  chance++;   a[w][e]='_'; r
               }
            }
            if(a[0][0]==op && a[1][1]==op && a[2][2]==op)
            {
               chance++;   a[w][e]='_';
            }
            else if(a[0][2]==op && a[1][1]==op && a[2][0]==op)
            {
               chance++;   a[w][e]='_';
            }
           a[w][e]='_';
        }
      }
   }
}

A: It looks like chance is a global variable, so it keeps its value even after the function returns. You could reset its value by adding chance = 0 to the beginning of the function.


text:
Q: query inside main query order issue I'm trying to access the following shortcode in a simple page, with [featured/]
function mytheme_featured() {
$my_query2 = new WP_Query('category_name=featured&showposts=1');
while ($my_query2->have_posts()) : $my_query2->the_post();
return '
'.the_title().'

'.the_excerpt().'
';
endwhile;
}
add_shortcode( 'featured', 'mytheme_featured' );

However, the content of that post is displayed at the top of the page, instead of the location given to the shortocde, which is below the first paragraph, inside the box with the red border. Any thoughs on why this happens?

A: the_title(), the_excerpt() and the_permalink() prints the output at once but the shortcode function is supposed to just return the output. You can use get_the_title(), get_permalink() and get_the_excerpt() instead.


text:
Q: Padding at top of NSView in an NSScrollView I have an NSView as the document of an NSScrollView. I would like to have a few pixels of padding at the top and bottom of the visible part of the view, regardless of where the scroller is positioned (not just at the top and bottom of the document as described here). For an example of an app that does this, look at Terminal.app. Regardless of the background color of the text, the top two visible rows of pixels are always the default background color.
I know I could simply draw everything two pixels lower and draw a rectangle at the top and bottom of the document-visible rect, but that will require changing a lot of complex code that I didn't write. Simpler ideas are welcomed!

A: The answer to the question you linked is actually a good solution for this problem too. In fact if your view is anything but an NSTextView, I'd say it's easier to implement.
Specifically: make your actual document view a subview of some other view, leaving room around the edges and make that view the scroll view's document view. If your content view (the one you wish to pad) changes sizes, have your "padding view" observe it for frame changes and resize to maintain the padding.
2015 Update
Content inset has been added to NSScrollView as of 10.10, making my older answer obsolete.


text:
Q: How can two services discover each other without static addresses? Supposed I have two services that need to share and / or exchange data. Both instances are separate from each other, and they shall not know anything about where the other part is located.
Now in order for them to be able to share and / or exchange data, they need to connect to each other.
How do they find each other without the need to configure the IP addresses explicitly? In other words: How could they detect each other automatically?
Basically, I have two ideas:

*

*Pull: You need to have a central service where they register. Then you can ask that service for the address of a service, and that service then returns those data. While this works, it has the drawback that it only shifts the problem to the next level: What if I have multiple instances of that service, and I don't want them to know each other in advance?

*Push: Each service broadcasts its own address, so that other services get it to know. Each service repeats this from time to time. Drawback: This does hardly work in the internet.
Any idea of how I could solve this in an intelligent way?
PS: If you want to say so, I'm looking for a way to handle dynamic IPs without the need for a central DNS server.

A: "broadcast packets are not forwarded everywhere on a network, but only to devices within a broadcast domain."
If your devices are on different broadcast domains then broadcasting is not going to work.
You are probably going to have to implement your own central service, unless you can use one of the free dynamic dns servers, for example: Free

A: The usual way is to have some fault-tolerant server where services register and can then look for other services - Curator framework implements that over zookeeper.
If you want autodiscovery then you should probably implement some sort of gossip protocol so that the servers would know which other servers are out there in a reliable way. You should keep in mind that getting gossip protocols right is tricky (e.g. some of past Amazon cloud failures where due to problems in their implementation)


text:
Q: Keyboard notification is not working on iPads with iOS 10+ when focusing the Texfield in WKWebView I am working on a WKWebview iOS app. The keyboard notification is not calling methods to add the observer on iPads with iOS 10+. Not even in the simulator, when  focusing on the text field in the WKWebView.
Below is the code I wrote in ViewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

This is being called on the iPhone but not on the iPad. I tried these lines on the different functions too, like ViewWillAppear and ViewDidAppear.


text:
Q: Clipboard issue on Ubuntu Arzt I've had problems with Arful...
One of them (the most important right now) is  a clipboard issue. Artful's clipboard doesn't work properly 'cause using libreoffice it didn't copy an image to the clipboard from another document. I don't remember wich was the document's extension, but it happended.
I installed clipman in XFCE (my preferred desktop environment) to make a drawing in BricsCAD and it gave me that copyclip issue also.
When I write an existing drawing, it works. But if I make a drawing copying another one, it breaks.
I want to know if there's a low-level clipboard manager to test BricsCAD issue. I really need BricsCAD, and it could be a problem of Artful.
I've already requested technical support to Bricsys Co., but they didn't solve me that trouble...
I'm running kernel 4.15.1, XFCE, compiz and the last stable mesa from Padoka Stable (17.3.2)