text:
Q: Get parameters out of text file I have a C# asp.net page that has to get username/password info from a text file.
Could someone please tell me how.
The text file looks as follows: (it is actually a lot larger, I just got a few lines)
DATASOURCEFILE=D:\folder\folder
var1= etc
var2= more
var3 = misc
var4 = stuff
USERID = user1
PASSWORD = pwd1

all I need is the UserID and password out of that file.
Thank you for your help,
Steve

A: Open the file, split on the newline, split again on the = for each item and then add it to a dictionary.
string contents = String.Empty;
using (FileStream fs = File.Open("path", FileMode.OpenRead))
using (StreamReader reader = new StreamReader(fs))
{
    contents = reader.ReadToEnd();
}

if (contents.Length > 0)
{
    string[] lines = contents.Split(new char[] { '\n' });
    Dictionary<string, string> mysettings = new Dictionary<string, string>();
    foreach (string line in lines)
    {
        string[] keyAndValue = line.Split(new char[] { '=' });
        mysettings.Add(keyAndValue[0].Trim(), keyAndValue[1].Trim());
    }

    string test = mysettings["USERID"]; // example of getting userid
}

A: This would work:
var dic = File.ReadAllLines("test.txt")
              .Select(l => l.Split(new[] { '=' }))
              .ToDictionary( s => s[0].Trim(), s => s[1].Trim());

dic is a dictionary, so you easily extract your values, i.e.:
string myUser = dic["USERID"];
string myPassword = dic["PASSWORD"];

A: You can use Regular expressions to extract each variable. You can read one line at a time, or the entire file into one string. If the latter, you just look for a newline in the expression.
Regards,
Morten

A: Dictionary is not needed.
Old-fashioned parsing can do more, with less executable code, the same amount of compiled data, and less processing:
public string MyPath1;
public string MyPath2;

...

public void ReadConfig(string sConfigFile)
{
  MyPath1 = MyPath2 = "";  // Clear the external values (in case the file does not set every parameter).

  using (StreamReader sr = new StreamReader(sConfigFile))  // Open the file for reading (and auto-close).
  {
    while (!sr.EndOfStream)
    {
      string sLine = sr.ReadLine().Trim();  // Read the next line. Trim leading and trailing whitespace.

      // Treat lines with NO "=" as comments (ignore; no syntax checking).
      // Treat lines with "=" as the first character as comments too.
      // Treat lines with "=" as the 2nd character or after as parameter lines.
      // Side-benefit: Values containing "=" are processed correctly.

      int i = sLine.IndexOf("=");  // Find the first "=" in the line.
      if (i <= 0) // IF the first "=" in the line is the first character (or not present),
        continue;  // the line is not a parameter line. Ignore it. (Iterate the while.)
      string sParameter = sLine.Remove(i).TrimEnd();  // All before the "=" is the parameter name. Trim whitespace.
      string sValue = sLine.Substring(i + 1).TrimStart();  // All after the "=" is the value. Trim whitespace.

      // Extra characters before a parameter name are usually intended to comment it out. Here, we keep them (with or without whitespace between). That makes an unrecognized parameter name, which is ignored (acts as a comment, as intended).
      // Extra characters after a value are usually intended as comments. Here, we trim them only if whitespace separates. (Parsing contiguous comments is too complex: need delimiter(s) and then a way to escape delimiters (when needed) within values.) Side-drawback: Values cannot contain " ".
      i = sValue.IndexOfAny(new char[] {' ', '\t'});  // Find the first " " or tab in the value.
      if (i > 1) // IF the first " " or tab is the second character or after,
        sValue = sValue.Remove(i);  // All before the " " or tab is the parameter. (Discard the rest.)

      // IF a desired parameter is specified, collect it:
      // (Could detect here if any parameter is set more than once.)
      if (sParameter == "MyPathOne")
        MyPath1 = sValue;
      else if (sParameter == "MyPathTwo")
        MyPath2 = sValue;
      // (Could detect here if an invalid parameter name is specified.)

      // (Could exit the loop here if every parameter has been set.)
    } // end while

  // (Could detect here if the config file set neither parameter or only one parameter.)
  } // end using
}


text:
Q: How can I save a few best Keras models? I need to save a few best models. I have defined ModelCheckpoint from Keras, which saved only one best model.
checkpoint = tf.keras.callbacks.ModelCheckpoint(
     filepath=checkpoint_path,
     monitor='val_loss',
     verbose=1,
     save_best_only=True,
     save_weights_only=True,
     mode='min'
)

Any ideas?

A: save_best_only=False
This way you will save the model after each epoch,and not only when the model is considered "the best".
Remember to define a path that changes for each epoch or the model will be overwritten.
AFTER THE COMMENT:
If your callback is saving only one model is probably because you have defined the path to be static, you need to use the keras formatting, so that the name on the file where the model is saved changes every epoch, otherwise it will be overwritten.
You need to define the path in something like this:
filepath= model_folder_path + "/epoch:{epoch:02d}-val_loss:{val_loss:.2f}.hdf5"

If you define the path to be static every time keras goes to save the new best model the model saved just before will be overwritten and you will remain with only one of them (the last one saved).
Go check the doc for more info on how to write the path:
https://keras.io/api/callbacks/model_checkpoint/
AFTER THE SECOND COMMENT:
Ok now what you want is to save only some of this best models and not everyone of them, I achieved this result using a callback like this:
class too_many_models(Callback):
  def __init__(self, mypath, max_num_of_models):
    self.path = mypath
    self.mnom = max_num_of_models

  def  on_epoch_end(self, epoch, logs=None):
    onlyfiles = [f for f in listdir(self.path) if isfile(join(self.path, f))]
    onlyfiles.sort()
    if len(onlyfiles) > self.mnom:
      os.remove(join(self.path, onlyfiles[0]))

model_folder = "supertest"
!mkdir "/content/gdrive/My Drive/"$model_folder

folderpath = "/content/gdrive/My Drive/" + model_folder
filepath = folderpath + "/epoch:{epoch:02d}-val_loss:{val_loss:.2f}.hdf5"

my_callbacks = [
    tf.keras.callbacks.ModelCheckpoint(filepath=filepath, save_weights_only=False, monitor='val_loss', mode='min', save_best_only=True),
    too_many_models(mypath=folderpath, max_num_of_models=5)
    ]

you want to use this callback like this:
model.fit(train, steps_per_epoch=len(train), validation_data=valid, callbacks=my_callbacks)

A few things to note:
the callback too_many_models is called after the callback that saves the model.
The folder needs to be empty before starting the training, you need a different folder for every training (but I usually do this, so I don't see it as a problem).
I sort the files, in this way I am sure the model I am removing (at index 0) is always the older one saved (with the lower number in epoch), this works only because i defined the names of the models in that way, the number of the epoch sort the files as I want them. (I hope this point is clear)
you can change the number of models saved with max_num_of_models, with 5 it will save the last best 5 models.
folderpath needs to be the path where you are saving the models. (pay attention on how I defined the different paths)
I just tested everything to be sure it works as intended.
I know it's a pretty rough solution, but it gets the job done :D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need to implement mobile push notifications for our cordova based mobile apps, based on shopify We need to implement push notifications for our cordova based mobile apps for our ecommerce store, which is powered by shopify. We need to send push notifications to users whenever they make a purchase, a product has been shipped etc. What is the best way to go about implementing user specific push notifications for mobile apps for our shopify store? I believe we would need to use shopify's webhooks for this right?
Couldn't find any relevant info on this topic anywhere so I had to ask this here. Any help would be great!

A: you can use the plugin OneSignal Cordova Push Notification Plugin
check here https://onesignal.com/

*

*you can use API for send the notification when customer make a purchase so you need to make some code with php in your store ..


text:
Q: How to automate a sql script in snowflake I have a SQL script that transforms data for various tables in snowflake. I need to run this SQL code daily and I want to automate it somehow. I thought I could automate the SQL with 'tasks' in snowflake but 'tasks' are unable to run more than one single SQL statement and my code contains a multitude of SQL statements. Does anyone have any ideas? Any help is appreciated

A: If you want to automate more than one sql statement, you have two options:

*

*Run a task for each of your statements and build up dependencies between them

*Wrap your whole script into a stored procedure and trigger this procedure with your task. The statement for triggering the procedure is something like CALL myProcedure(optional parameters);


text:
Q: How to add platform(linux/amd64) to KuberneterClient in Java? Using io.fabric8.kubernetes.client library to create pod, how to add the platform to build the pod/container?
Is it under the withEnv(envVars) or .addNewEnv().withName("platform").withValue("linux/amd64").endEnv()? Or is it not part of the environment itself as the platform comes more of an argument/ option to create a container/ pod.

*

*Env.: Mac M1 chip

*Docker v4.8, K8s 1.24.


text:
Q: Parameterization of the curve of intersection of a surface I need to parameterize the curve of intersection of the surface:
$x^2+y+z=2$ and $xy+z=1$
What I've done so far is said:
$z=2-x^{2}-y$ therefore $xy+(2-x^{2}-y)=1$ (using substitution). Then, we get $x^{2}-xy+y=1$.
This is where I'm stuck, this cannot be factored any further and so I can't finish the parameterization. Any help would be greatly appreciated! Thank you.

A: You cannot get one parametrization however you can get two:
The intersection of $x^2+y+z=2$ and $xy+z=1$ consists of the union of a line: $(1,t,1-t)$ and a parabola: $(s-1,s,-s^2+s+1)$ which intersect in the point $(1,2,-1)$. Maple:
> solve([x^2+y+z = 2, x*y+z = 1]);
                             /                        2        \
{x = 1, y = y, z = -y + 1}, { x = y - 1, y = y, z = -y  + y + 1 }
                             \                                 /

with(plots);
p1 := plot3d([1, y, -y+1], x = -10 .. 10, y = -10 .. 10);
p2 := plot3d([y-1, y, -y^2+y+1], x = -10 .. 10, y = -10 .. 10);
display(p1, p2); #manually rotated to get the image


text:
Q: $\lim\limits_{n\to\infty}\sum_{k=1}^n\frac{1}{k(k+1)…(k+m+1)}=\frac{1}{(m+1)\cdot(m+1)!}$ Can I proof this identity somehow without using the Riemann integral?
I have tried Stolz–Cesàro Theorem and sums of valuations' progressions.

A: Note that
$$
\frac{1}{k(k+1)\cdots(k+m+1)}=\frac{1}{(m+1)}
\left(\frac{1}{k(k+1)\cdots(k+m)}-\frac{1}{(k+1)(k+2)\cdots(k+m+1)}\right).
$$
Thus
$$
\sum_{k=1}^n \frac{1}{k(k+1)\cdots(k+m+1)}=\frac{1}{(m+1)}
\left(\frac{1}{(m+1)!}-\frac{1}{(n+1)(n+2)\cdots(n+m+1)}\right),
$$
and hence
$$
\lim_{n\to\infty}\sum_{k=1}^n \frac{1}{k(k+1)\cdots(k+m+1)}=\frac{1}{(m+1)\cdot (m+1)!}.
$$

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\lim_{n \to \infty}\sum_{k = 1}^{n}{1 \over k\pars{k + 1}\ldots\pars{k+m+1}}
     ={1 \over m\,m!}:\ {\Large ?}}$

\begin{align}
&\color{#00f}{\large\sum_{k = 1}^{\infty}{1 \over k\pars{k + 1}\ldots\pars{k+m+1}}}=
\sum_{k = 1}^{\infty}{\Gamma\pars{k} \over \Gamma\pars{k + m + 2}}
=
{1 \over \pars{m + 1}!}\sum_{k = 1}^{\infty}
{\Gamma\pars{k}\Gamma\pars{m + 2} \over \Gamma\pars{k + m + 2}}
\\[3mm]&=
{1 \over \pars{m + 1}!}\sum_{k = 1}^{\infty}{\rm B}\pars{k,m + 2}=
{1 \over \pars{m + 1}!}\sum_{k = 1}^{\infty}
\int_{0}^{1}t^{k - 1}\pars{1 - t}^{m + 1}\,\dd t
\\[3mm]&=
{1 \over \pars{m + 1}!}\int_{0}^{1}\pars{1 - t}^{m + 1}
\pars{\sum_{k = 1}^{\infty}t^{k - 1}}\,\dd t
=
{1 \over \pars{m + 1}!}\int_{0}^{1}\pars{1 - t}^{m + 1}\,{1 \over 1 - t}\,\dd t
\\[3mm]&=
{1 \over \pars{m + 1}!}\bracks{-\,{\pars{1 - t}^{m + 1} \over m + 1}}_{0}^{1}
=\color{#00f}{\large{1 \over \pars{m + 1}\pars{m + 1}!}}
\end{align}

$\ds{{\rm B}\pars{x,y} \equiv \int_{0}^{1}t^{x - 1}\pars{1 - t}^{y - 1}\,\dd t}$
is the Beta Function which satisfies
$\ds{{\rm B}\pars{x,y} = {\Gamma\pars{x}\Gamma\pars{y} \over\Gamma\pars{x + y}}}$. $\Gamma\pars{z}$ is the Gamma Function. Also, $\ds{\Gamma\pars{n + 1} = n!}$
with $\ds{n \in {\mathbb N}}$.

A: The denominator is $k (k+1)_{m+1}$ where the second term is the Pochhammer symbol.
The summation from $k=1$ to $k=n$ simplifies and write
$$\frac{\frac{1}{\Gamma (m+1)}-\frac{(m+1) \Gamma (n+1)}{\Gamma (m+n+2)}}{(m+1)^2}$$ Going to limit, this seems to give  $$\frac{1}{(m+1)^2 \Gamma (m+1)}$$ which seems to be wrong !
I would really appreciate if somebody could tell me where I started being wrong.


text:
Q: Python Selenium Click on all li as I click on a
* inside it there is an  and inside the  there is an  I had already tried to use:
driver.find_element(By.CLASS_NAME,"result-view").click();
driver.find_elements(By.CLASS_NAME,"result-view").click();

but no it worked and in the logs it appeared that only the image is clickable.
 Message: element click intercepted: Element
...
 is not clickable at point (130, 939). Other element would receive the click:

Note, I want to click all the buttons that are on the page but it didn't click even the first one


text:
Q: How do I add two URLs into given format? I have a excel sheet..That contains two urls sets..I need to add them into this format in another column
Col 1                       Col 2

Web site A.1               Web site B.1
Web site A.2               Web site B.2

New column should be like this..
web site B.1
web site B.2

How to do this?

A: Concatenate everything all together:
In cell C1 use the formula ="" & B1 & ""


text:
Q: How to search a file by cluster of lines and then delete those lines? I have a log file that is a list of repeating characteristics. For example:
## This is the pattern of lines
time
urgency
icon_path
summary
body
appname

## Below is what the log file would actually look like
12:30
critical

test notification
notification
notify-send
11:00
low

earlier notification
notification
notify-send
10:46
normal

hello
world
dunstify

I'm trying to find a way to search for a block/cluster of lines that match my search terms and then delete them in bash. As you can see in the above example, sometimes lines are empty, sometimes they are filled. The best "solution" I have found so far is to use sed '/12:30/,+5 d' or slightly better sed '/12:30/,/notify-send/d'. The problem with both of these is that the first one will delete all occurrences of the timestamp, thus deleting more than just one log entry; the problem with the other command is that if there are two or more entries with the same time and appname, all matching entries will get deleted.
What I've been trying to get working and have been failing spectacularly is to do something like: sed '/12:30\n^.*$\n^.*$\ntest notification\nnotification\nnotify-send/d' /tmp/notification_log. Note that the 2nd and 3rd lines can be anything (the urgency and icon_path lines respectively), which is why I used ^.*$ (to be frank, I'm not even sure if that is the proper regex).
EDIT:
Using the above failed command, I would expect the output to be:
11:00
low

earlier notification
notification
notify-send
10:46
normal

hello
world
dunstify

That command had the input of:
12:30
*anything*
*anything*
test notification
notification
notify-send

A: It's actually not so hard, provided all clusters are M lines long, M is fixed, clusters don't overlap and we don't need to search for the beginning of any cluster. In our case M is 6.
sed allows you to match against multiple lines, but since it normally processes one line at a time, you need to explicitly append additional lines to the pattern space. You do it with N:
sed 'N;N;N;N;N; /12:30\n.*\n.*\ntest notification\nnotification\nnotify-send/d'

The rest is your code without ^ and $ anchors. The anchors are often associated with "the beginning of the line" and "the end of the line" respectively; but in sed they are really "… of the string". When sed processes one line at a time there is no difference. In our case we should definitely remember the anchors are "… of the string". Putting them in the middle doesn't make sense. It's not they would never match anything. sed wouldn't interpret them as anchors in the first place, it would interpret them as literal ^ and $.
There's no need for "… of the line" anchors in the middle of a string. Any line but last ends just before some newline character; any line but first begins just after some newline character. So it's enough to match \n.
Maybe you tried to use anchors to make sure .* (which is greedy and can match newline characters) doesn't match more than one line. Even if ^ and $ acted as "… of the line" anchors, .* would still be greedy. Consider this: The pattern space in sed never contains a newline character after the last line*. In our case we know there are at most six lines in the pattern space; and we used \n exactly five times. This guarantees each fragment of the regular expression can only match certain line in a cluster.
Still anchors can help. The above command can delete a cluster ending with notify-send-whatever. $ is the right way to prevent this. There is no time other than 12:30 that matches 12:30; but it's different for 2:30, so in general ^ can also be useful. The improved command:
sed 'N;N;N;N;N; /^12:30\n.*\n.*\ntest notification\nnotification\nnotify-send$/d'

* This doesn't mean there can never be a newline character at the end of the pattern space. A newline character at the end indicates there's a line just after the character. It's the last line and it's empty. And there is no newline character after it, so "never a newline character after the last line" stands.


text:
Q: Не пойму в чем проблема. BooleanField не имеет атрибута? Всем привет. При запуске сервера выдает следующее

Вот файл forms.py

from django.forms import ModelForm, Form
from . import models
from . import forms
from .models import Author1
from .models import Article
from django.http import HttpResponse

class AuthorOneForm(ModelForm):
    class Meta:
        model = Author1
        fields = ['name', 'surname', 'city']

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['author', 'title', 'text']

class ContactForm(forms.Form):
    boolean_field = forms.BooleanField()
    float_field = forms.FloatField()
    name_sender = forms.CharField(max_length=100, label='Введите ваше имя')
    message = forms.CharField(widget=forms.Textarea, label = 'Сообщение')
    sender = forms.EmailField(label='Введите ваш эмейл')

Должно быть так ... (правда версии джанго на скрине 1,11 у меня 2,2)

В документации рекомендуют использовать NullBooleanField - но меня это не спасает...
P.S (только учусь опыта мало)


text:
Q: Can a Linux system have two IP's Simultaneously? Recently I installed apache2 on Raspbian and after end of installation I entered the following cmd and got two IP's.
$ hostname -I
192.168.1.17 192.168.1.24

Of this, I have been using the IP ending in 17 from beginning. But I have never seen the one with 24. Can I use them both to access my RPi or each one present only for a specific use. Like 24 only for apache ???

A: hostname -I doesn't work here (openSUSE 13.2) but there is no problem with one host using several IP addresses. That is obviously possible by having several network adapters but you can have several addresses per interface (aliases) and even several interfaces per hardware NIC.
The usual way to see the network configuration is ip addr show.

A: The command hostname -I gives back all IP-addresses that are currently configured on your system with exception to local-link addresses for IPv6 or on your loopback interfaces. So yes you could use 192.168.1.24 as well to access your site if Apache is configured correctly.

A: When you use :
root@debian:/home/mohsen# ip addr show up
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 18:03:73:60:b4:4e brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.14/24 brd 192.168.1.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 192.168.1.21/24 brd 192.168.1.255 scope global secondary eth0:1
       valid_lft forever preferred_lft forever
    inet6 fe80::1a03:73ff:fe60:b44e/64 scope link
       valid_lft forever preferred_lft forever

I set up alias IP for eth0 , you have to find IPs of ethernet of set on the given ethernet. Or you can use:
root@debian:/home/mohsen# ifconfig

    eth0      Link encap:Ethernet  HWaddr 18:03:73:60:b4:4e
              inet addr:192.168.1.14  Bcast:192.168.1.255  Mask:255.255.255.0
              inet6 addr: fe80::1a03:73ff:fe60:b44e/64 Scope:Link
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:101110 errors:0 dropped:0 overruns:0 frame:0
              TX packets:81804 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000
              RX bytes:89999660 (85.8 MiB)  TX bytes:10808197 (10.3 MiB)

    eth0:1    Link encap:Ethernet  HWaddr 18:03:73:60:b4:4e
              inet addr:192.168.1.21  Bcast:192.168.1.255  Mask:255.255.255.0
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

It's better to don't use alias IP and use original IP.


text:
Q: Scoped service creating two different instances for a request I'm fairly new to Asp.Net core 6 and am working on an GraphQL API that receives a bearer token in the request. The API then invokes another Web API and passes the same bearer token in the header. Below is what my code looks like-
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<HeaderHandler>();
builder.Services.AddScoped<TokenContainer>();
//builder.Services.AddScoped<IFooGateway, FooGateway>();

builder.Services.AddHttpClient<IFooGateway, FooGateway>((c) =>
{
    c.BaseAddress = new Uri(builder.Configuration["FooApiUrl"]);
})
.AddHttpMessageHandler<HeaderHandler>();

builder.Services.AddTransient<GraphApiService>();

var app = builder.Build();
app.UseMiddleware<HeaderMiddleware>();
app.MapGraphQL();
app.Run();

HeaderMiddleware.cs
public class HeaderMiddleware
    {
        //TokenContainer _tokenContainer;

        private readonly RequestDelegate _requestDelegate;
        public HeaderMiddleware()
        {
        }
        public HeaderMiddleware(RequestDelegate requestDelegate)
        {
            _requestDelegate = requestDelegate;
            //_tokenContainer = tokenContainer;
        }

        public async Task InvokeAsync(HttpContext context, TokenContainer tokenContainer)
        {
            var header = context.Request.Headers.Authorization;
            tokenContainer.SetToken(header);
            await _requestDelegate(context);
        }

TokenContainer.cs:
public class TokenContainer
{
    public string BearerToken { get; private set; }

    public void SetToken(string token) => BearerToken = token;
}

HeaderHandler.cs:
public class HeaderHandler : DelegatingHandler
    {
        TokenContainer _tokenContainer;
        public HeaderHandler()
        {

        }

        public HeaderHandler(TokenContainer tokenContainer)
        {
            _tokenContainer = tokenContainer;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // for every request sent via the http client, intercept & add the bearer token header.
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", _tokenContainer.BearerToken);
            // continue with request pipeline
            return await base.SendAsync(request, cancellationToken);
        }
    }

FooGateway.cs:
public class FooGateway : IFooGateway
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;
        private readonly string _context = String.Empty;

        public FooGateway(HttpClient httpClient, IConfiguration configuration)
        {
            _configuration = configuration;
            _context = configuration["FooContext"];
            _httpClient = httpClient;
        }
       public void DoSomething()
       {
        _httpClient.PostAsync("/blabla");
       }

    }

So, the idea was that the bearer token for every incoming request will be stored in a class called TokenContainer and the HttpHandler will add it to all the outgoing requests.
However, what is happening is that the token is stored in the TokenContainer but the HeaderHandler gets a different instance of TokenContainer in its constructor with its BearerToken property set to null.
Can someone please explain why the same instance of TokenContainer from the middleware is not being passed into the HeaderHandler?

A: The issue you are seeing is because the lifetime of the HttpMessageHandler is not the same as the lifetime of the request: usually, the same handler will be reused across many requests and be controlled separately on expiration timers and such.
You should not expect that a service injected into your message handler will be the same object that is injected outside it when it is registered as scoped.
https://andrewlock.net/understanding-scopes-with-ihttpclientfactory-message-handlers/#scope-duration-in-ihttpclientfactory
As the article suggests, to use the same scoped instance as you do outside the handler, you have to rely on IHttpContextAccessor to access the current HttpContext and fetch the service from there. So your handler implementation would look something like this:
public class HeaderHandler : DelegatingHandler
    {
        IHttpContextAccessor _httpContextAccessor;
        public HeaderHandler()
        {

        }

        public HeaderHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var tokenContainer = _httpContextAccessor
                .HttpContext
                .RequestServices
                .GetRequiredService<TokenContainer>();

            // for every request sent via the http client, intercept & add the bearer token header.
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenContainer.BearerToken);
            // continue with request pipeline
            return await base.SendAsync(request, cancellationToken);
        }
    }

This should make sure that the TokenContainer instance is the same across your current request and http calls.
Remember that to add this functionality you need to add the accessor like this:
services.AddHttpContextAccessor();


text:
Q: Data transformation - transform data from columns and interpolate missing values I have data about number of people living in Wrocław:
Pop <- data.frame(Year = c(850, 1000, 1200,  1300,  1350,  1318,  1327,  1329),
                    Pop  = c(800, 2250, 5000, 13500, 14000, 13600, 12000, 15950))

Is there a way to change it, that each year is separate row and the data is interpolated?
Pop_long <- data.frame(Year = 850:1329, Pop = 850, ....)

The interpolation would be linear. I have done if, but I bet there is a better way:
Pop <- Pop
  mutate(Year_lead = lead(Year),
         Pop_lead  = lead(Pop),
         Year_diff = Year_lead - Year,
         Pop_diff  = Pop_lead  - Pop,
         Pop_add   = Pop_diff / Year_diff) %>%
  select(Year, Pop, Pop_add)

Pop_long <- data.frame(Year = 850:1329) %>%
  merge(Pop, all.x = T)

for(i in 1:nrow(Pop_long)){
  if(is.na(Pop_long[i, "Pop"])) {
    Pop_long[i, "Pop"]     <- Pop_long[i - 1, "Pop_add"] + Pop_long[i - 1, "Pop"]
    Pop_long[i, "Pop_add"] <- Pop_long[i - 1, "Pop_add"]
  }
}

A: You could use complete from tidyr and na.approx from zoo.
library(tidyr)
library(dplyr)
library(zoo)
Pop_long <- Pop %>%
 complete(., Year = 850:1329) %>%
 # complete(., Year = min(Year):max(Year)) %>%
 mutate(Pop = na.approx(Pop))

Pop_long
# A tibble: 480 x 2
#    Year   Pop
#   <dbl> <dbl>
# 1  850.  800.
# 2  851.  810.
# 3  852.  819.
# 4  853.  829.
# 5  854.  839.
# 6  855.  848.
# 7  856.  858.
# 8  857.  868.
# 9  858.  877.
#10  859.  887.
# ... with 470 more rows

library(ggplot2)
ggplot(data = Pop_long, aes(Year, Pop)) +
  geom_line() +
  geom_point(data = Pop, col = "red")


text:
Q: How to get the value out of Knockout function I'm using Knockout and I'm trying to build function that will return a value, The problem is that I'm computing the value inside internal function, and I don't find a way to get the value out of this function.
Thats what I have so far
JS
var vm = {
    myResponse: ko.observable(),
    computedValue: ko.observable()
};

vm.myResponse.subscribe(function (newValue) {
    myfunction(computedValue);
});

var myfunction = function (observableToUpdate) {
    var responses = request.responses();
    return changeUp.getUserInfo().then(function (userInfo) {
        var currentResponse = ko.utils.arrayFirst(responses, function (r) {
            return r.userName === userInfo.userName;
        });
        var responseindex = responses.indexOf(currentResponse);
        observableToUpdate({
            responeIndex: responseindex
        });
    });
};

On my html I'm using following lines

    {{since()}}
    {{amount|number}}
    {{rate|number}}
    {{distance}}

        {{_t('Details')}}

Currently non of the  get the class responder. i want to add it only if the condition in isMyResponse is true;

A: The only way to use asynchonous callbacks to set an observable is to use subscriptions.  A knockout computed expects a synchronous return value.
You function finished execution before the "then" callbacks fire.
var someObservable = ko.observable();
var computedValue = ko.observable();

someObservable.subscribe( function( newValue ) {
    changeup.getUserInfo().then( function(userInfo) {
        ...
        computedValue(myRespondIndex);
    });
} );

Also, "then" callback return value only influences the call chain of the promise.  If you throw an exception the fail callback will fire and any chained "then" callback will not be invoked.  A returned value does not "cascade" through the callbacks.

A: For the UserID = 'undefined', I think that the result of the first then function is being passed to the second then function.  The result of the second then function will be undefined as nothing is returned. I think it should probably be something like this:-
this.isMyResponse = function(index) {
    var test ;
    var responses = this.request.responses();
    var useriD = changeup.getUserInfo().then(function (userInfo) {
        var currentResponse = ko.utils.arrayFirst(responses, function (r) {
            return r.username === userInfo.username;
        });
        var myRespondIndex = responses.indexOf(currentResponse);
        test = myRespondIndex;
        console.log("inside" + test);
        return myRespondIndex;
    }).then  (function (index) {
        console.log("outside" + test);
        return index;
    });
    console.log("outside" + test);
    return test;
}

EDIT
The following jsFiddle was my attempt to confirm what Robert Stanley was telling me. In the end I implemented the solution how he suggested.
http://jsfiddle.net/gonefishern/zdDh9/
As Robert Stanley pointed out to me, the following javascript will return a promise but the not values that I thought it was going to.
var isMyResponse = function(observableToUpdate) {
    var responses = this.request.responses();
    return  changeup.getUserInfo().then(function (userInfo) {
        var currentResponse = ko.utils.arrayFirst(responses, function (r) {
            return r.username === userInfo.username;
         });
         return {
             responeIndex: responses.indexOf(currentResponse),
             userInfo: userInfo
         };
    });
}


text:
Q: Add 1 month to fixed date in Smarty 2.x & show days left to that date in WHMCS I'm working with WHMCS 5.3.x which has Smarty 2.x IIRC.
So for instance {$service.regdate} renders:
2015-06-01

What I need to do is add one month to that date:
2015-07-01

...which I can then format with:
|date_format:"%m/%d/%Y"

...to display it how I want it.
I've tried quite a few things based on Google results like:
{"+1 month $service.regdate"|date_format:"%m/%d/%Y"}

{strtotime("+1 month",$service.regdate)|date_format:"%m/%d/%Y"}

...and a few other various iterations but the output generally renders only my initial date or nothing at all.
I'd also need to generate the number of days left from $smarty.now to $service.regdate + 1 month so I can show my customers how many days are left.
This I haven't found nearly as much information on.
I know you can do most if not all of this in PHP and then assign it to Smarty variables, but, I haven't found an example that works and, if you've ever worked with WHMCS support before, they don't really give you much to go on other than to "ask the forums", "talk to modulesgarden" or "open a feature request"
Thank you =)

A: Sylvain is 100% correct and using MySQL is the proper resolution:

        {php}
        $userid = $this->_tpl_vars['clientsdetails']['id'];
        $result = mysql_query("
            SELECT *,
            DATE_ADD(tblhosting.regdate,INTERVAL 1 MONTH) as trialexpires,
            DATEDIFF(DATE_ADD(tblhosting.regdate,INTERVAL 1 MONTH),CURDATE()) as trialdaysleft
            FROM tblhosting,tblproducts
            WHERE userid = $userid
            AND tblhosting.packageid= tblproducts.id
            AND tblhosting.domainstatus='Active'"
        );
        $services = array();
        while ($data = mysql_fetch_array($result)) {
            array_push($services, $data);
        }
        $this->_tpl_vars['services'] = $services;
        {/php}

Thank you =)


text:
Q: how to add color to sub item in listview? c# I tried to add text color to any sub item in the listview by the index that the method get from the array
for (int i = 0; i < sizes.Length; ++i)
            {
                if (sizes[i] == 1)
                {
                    Item.SubItems.Add("In Stock");
                }
                else if (sizes[i] == 0)
                {
                    Item.SubItems.Add("Out Of Stock");
                }
                else if (sizes[i] == 2)
                {
                    Item.SubItems.Add("Less Than 3");
                }
                else if (sizes[i] == 5)
                {
                    Item.SubItems.Add("Less Than 5");
                }
                else if (sizes[i] == 10)
                {
                    Item.SubItems.Add("Less Than 10");
                }
            }

            ProductListView.Items.Add(Item);
        }

if the size in stock the subitem color change to green
and if the size is out of stock the subitem color will change to red
thanks

A: The Add method returns the subItem,
So you can change the subItem color like this:
var subItem = Item.SubItems.Add("In Stock");
subItem.ForeColor = Color.Green;
// subItem.BackColor = Color.Red;


text:
Q: Implementing a Set in typescript, specifically IterableIterator<[T, T]> I'm playing with a Set implementation in typescript. I want it to adopt the interface of set, but with some differences, I seem to have a problem with: entries() however:
I have implemented next() on my object, which returns either:
{
 value: elementAt(index),
 done: false;
}

or
{
value: undefined,
done: true
}

but this does not work for
entries() : IterableIterator<[T, T]>
and I can't seem to find any references for how to do this. Can someone help out here? My first thought was that the value of value has to be different but so far nothing i have tried has worked.

A: From the documentation of Set.prototype.entries():

The entries() method returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. For Set objects there is no key like in Map objects. However, to keep the API similar to the Map object, each entry has the same value for its key and value here, so that an array [value, value] is returned.

That means for your object to satisfy the Set interface, it needs to return a different iterator for its entries() method than it does for its values() and keys() methods. Specifically you need to make the value of the iterator result be a pair, so next() returns something like
{
 value: [elementAt(index), elementAt(index)]
 done: false;
}

Hope that helps; good luck!

A: Here's how I implemented (extended) the Set interface in an abstract class. In my case, I wanted users to define their own (extended) implementations of the abstract methods.
I delegated most things to the _values set, and so I didn't have to mess with a lot.
VS Code completed most of this (it helps you with methods to implement). I Googled a bit to find a foreach implementation.
At the bottom is an example of how to instantiate the new class with the methods.
/** Wrap a Set to support multiple values,
    e.g., foos are objects in a set, but each foo has an "opposite" */
export abstract class SetWithOpposite<T> implements Set<T> {

    abstract setOpposite(value: T) : this
    abstract clearOpposite(value: T) : this

    add(value: T): this {
        if (!this._values.has(value)) {
            this._values.add(value)
            this.setOpposite(value)
        }
        return this
    }

    constructor(iterable?: T[]) {
        this.clear();

        if (iterable === undefined) {
            return;
        }

        if (!Array.isArray(iterable)) {
            throw new Error("Non-array iterables not supported.");
        }

        for (const value of iterable) {
            this.add(value);
        }
    }

    clear(): void {
        this._values.clear()
    }

    delete(value: T): boolean {
        if (this._values.has(value)) this.clearOpposite(value)
        return this._values.delete(value)
    }

    forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void {
        for (const element of this._values.keys()) {
            callbackfn.call(thisArg, element, element, this);
        }
    }

    has(value: T): boolean {
        return this._values.has(value)
    }

    get size(): number {
        return this._values.size;
    }

    entries(): IterableIterator<[T, T]> {
        return this._values.entries()
    }

    keys(): IterableIterator<T> {
        return this._values.keys()
    }

    values(): IterableIterator<T> {
        return this._values.values()
    }

    [Symbol.iterator](): IterableIterator<T> {
        return this.values()
    }

    [Symbol.toStringTag]: string;

    _values = new Set<T>()

}

Client defining and using a concrete implementation of SetWithOpposite:
import { SetWithOpposite } from "./setWithOpposite";

const incomingAccesses = new class extends SetWithOpposite<String> {
    setOpposite(value: String): this {
        console.log(`setOpposite: ${value}`)
        return this
    }
    clearOpposite(value: String): this {
        console.log(`clearOpposite: ${value}`)
        return this
    }
}

let entity = new String('Fred')

incomingAccesses.add(entity)

entity = new String('Nancy')

incomingAccesses.add(entity)

incomingAccesses.forEach(element => {
    console.log(`foreach element: ${element}`)
});

incomingAccesses.delete(entity)

for (const entry of incomingAccesses) {
    console.log(entry)
}


text:
Q: A sequence $x_n(t)\in C^1[0,1]$ with $x(0)=0$ such that $x_n(t)\to x(t)$ in $C[0,1]$ and $x'_n(t)\to y(t)$ in $L^2[0,1]$ but $x'(t)\neq y(t)$ Terminology/Definition: The set
$$
\Gamma(A):=\{(x,Ax):x\in\text{Dom}A\}\subseteq X\times Y
$$
is called the graph of $A$. We define the norm in $X\times Y$ by $||(x,y)||:=||x||_X+||y||_Y$. We say that $A$ is a closed graph operator if $\Gamma(A)$ is a closed set in $X\times Y$. This means that whenever $x_n\in\text{Dom}A$, $x_n$ converges to $x$ and $Ax_n$ converges to $y$, then $x\in\text{Dom}A$ and $y=Ax$.

Currently I'm self studying functional analysis, namely closed graph operators. In the text, the other gives the following example:

Example: The operator $Ax=dx/dt$ in $L^2[0,1]$ with $\text{Dom}A=\{x\in C[0,1]: x'\in C[0,1],x(0)=0\}$ is not a closed graph operator.

I'm trying to figure out why it's not a closed graph operator. I believe it boils down to finding a sequence of functions $x_n(t)\in C^1[0,1]$ with $x(0)=0$ such that $x_n(t)\to x(t)$ in $C[0,1]$ and $x'_n(t)\to y(t)$ in $L^2[0,1]$ but $x'(t)\neq y(t)$. However, I've tried many examples and can't find such a function.

A: Let $y_n$ be continuous with $0\leq y_n(t) \leq 1$, $y_n(t)=0$ for $t \leq \frac 1 2$ and $y_n(t)=1$ for $t \geq \frac 1  2+\frac 1 n$. Let $x_n(t)=\int_0^{t} y_n(s)ds$. Then $(x_n,Ax_n)$ is a sequence in the graph of $A$ converging in $L^{2}$ to $(x(t),y(t))$ where $x(t)=\int_0^{t} \chi_{(\frac 1 2 ,1)}(s)ds$. Also, $x_n'=y_n
\to \chi_{(\frac 1 2 ,1)}$ in $L^{2}$. Note that $x_n \to x$ uniformly. Since $x(t)$ is not even differentiable at $\frac  1 2$ (and hence does not belong to the domain of $A$) it follows that that graph of $A$ is not closed.


text:
Q: Duplicating turtle list elements by n for every loop iteration I have a list of turtle elements that I want to double by the end of each loop, but it returns nothing
level = 1

number_of_enemies = 5
enemies = []
for i in range(number_of_enemies):`
    enemies.append(turtle.Turtle())

 while True:
    for level < 4
         [for enemy in l for enemies in repeat(enemy, level)]
         for enemy in enemies:
              (do_stuff)
    level += 1

A: Generate a number of enemies double the then length of enemies list through enemies = [generate_turtle_object_somehow for i in range(2*l)]. Also, list comprehension returns a result list, so it needs to be assigned appropriately.
Code:
level = 1
turtle = "turtle"
number_of_enemies = 5
enemies = []
for i in range(number_of_enemies):
    enemies.append(turtle+str(i+1))
#print enemies

while level < 4:
    print "level", level
    l = len(enemies)
    enemies = [turtle+str(i+1) for i in range(2*l)]
    print enemies
    print len(enemies)
    for enemy in enemies:
        pass
    level += 1


text:
Q: Split string with replace by multiple tags function My string has HTML code. I need to split it to array by br and strong tags. Example of string:
string = "There was once upon a time a king but where he reigned and what he was called, I do not know.
Then it was foretold to the king that his daughter would find her health by eating an apple.
So he ordered it to be proclaimed throughout the whole of his kingdom...";
Is it possible to identify splitting tag and:

*

*If tag is br then add "\n" to the end of that part.

*If tag is strong then add "[b]" to the beginning of that part.

So this is what I want to achieve:
"[b]There was once upon a time a king",
 "but where he reigned and what he was called, I do not know. \n",
 "Then it was foretold to the king that his daughter would find her health by ",
 "[b]eating an apple. \n",
 "So he ordered it to be proclaimed throughout the whole of his kingdom..."

I have tried
 var array = string.replace(/(]*>(.*?)<\/strong>)|(
)/g,function(string,p1,p2) {
    if(p1) return '[b]$1';
    if(p2) return ' \n';
});

but that did not help me.

string = "There was once upon a time a king but where he reigned and what he was called, I do not know.
Then it was foretold to the king that his daughter would find her health by eating an apple.
So he ordered it to be proclaimed throughout the whole of his kingdom...";
var array = string.replace(/(]*>(.*?)<\/strong>)|(
)/g,function(string,p1,p2) {
        if(p1) return '[b]$1';
        if(p2) return ' \n';
    });

console.log(array);

A: I just would use javascripts split join and replace all tags either with nothing for e.g  which you dont need or with the correct thing for the given tag.

let text = "There was once upon a time a king but where he reigned and what he was called, I do not know.
Then it was foretold to the king that his daughter would find her health by eating an apple.
So he ordered it to be proclaimed throughout the whole of his kingdom...";

const replaceTags = (text, tag, replacement) => {
  return text.split(tag).join(replacement);
}

const tags = [
  {tag: "", rep: "\n[b]" },
  {tag: "", rep: "" },
  {tag: "
", rep: " \n" },
  {tag: "
", rep:  " \n" },
  {tag: "
", rep: " \n" },

];

tags.forEach(tag => {
  text = replaceTags(text, tag.tag, tag.rep);
});

if(text.startsWith("\n")) text = text.substring(1, text.length);

const texts = text.split("\n")

console.log(texts);


text:
Q: Insert array / nested table into table I really apologise if answer already was given, but I could only find answers for php.
My problem is that I got nested table array "test_nested_table" that got values ('a','b','c'). I also got table "test_table" in the DB that got three columns col1, col2, col3.
All I want to do is something like
insert into test_table values (test_nested_table);

I understand I can do that:
insert into test_table values (test_nested_table(1), test_nested_table(2), test_nested_table(3));

However, my actual real life table might be very big and I would be very surprised if I really need to type all 100 elements to insert.

A: I have come up with the following solution:
declare
    type test_array is varray(3) of varchar2(10);
    ta test_array := test_array ('a','b','c');
    sql_txt varchar2(1000) := 'insert into test_table_1 values (''';
begin
    for n in 1 .. ta.count loop
    sql_txt := sql_txt || ta(n)||''',''';
    end loop;
    sql_txt := rtrim(sql_txt,',''')||''')';
    execute immediate sql_txt;
end;
/

So, if you have an array or any other collection type, you can use dynamic approach to insert a lot of values without writing them all in the insert statement; however, I believe there still should be a more usual way to do that.


text:
Q: Avoiding dispose of underlying stream I'm attempting to mock some file operations. In the "real" object I have:
StreamWriter createFile( string name )
{
  return new StreamWriter( Path.Combine( _outFolder, name ), false, Encoding.UTF8 ) );
}

In the mock object I'd like to have:
StreamWriter createFile( string name )
{
  var ms = new MemoryStream();
  _files.Add( Path.Combine( _outFolder, name ), ms );
  return new StreamWriter( ms, Encoding.UTF8 ) );
}

where _files is a dictionary to store created files for later inspection.
However, when the consumer closes the StreamWriter, it also disposes the MeamoryStream... :-(
Any thoughts on how to pursue this?

A: If you subclass the MemoryStream, this will work but you have to call ManualDispose method to close the underlying stream.
I´m not sure but I think this object will be garbage-collected when it goes out of scope.
public sealed class ManualMemoryStream : MemoryStream
{
    protected override void Dispose(bool disposing)
    {
    }
    public void ManualDispose()
    {
        base.Dispose(true);
    }
}

Edit:
This is an alternative if you want the MemoryStream to be flushed and ready to be read from top.
public sealed class ManualMemoryStream : MemoryStream
{
    protected override void Dispose(bool disposing)
    {
        Flush();
        Seek(0, SeekOrigin.Begin);
    }
    public void ManualDispose()
    {
        base.Dispose(true);
    }
}

A: The nature of the StreamWriter is to dispose the underlying stream when it is itself disposed.  However, by creating (and returning) a sub-class of StreamWriter (I'm going to call it LeakyStreamWriter), you should be able to prevent this default behaviour.
public class LeakyStreamWriter : StreamWriter
{
    public override void Close()
    {
        BaseStream.Close(); //close, but do not dispose
    }

    protected override void Dispose(bool disposing)
    {
        //do nothing here
    }
}

Note that I am making the assumption that the StreamWriter has no other components to dispose other than the underlying stream, you may want to check the dissassembly of the StreamWriter to check what is actually done in those two methods.
Anyway, the result of using the above subclass is that the underlying stream will be closed, but not disposed, when the streamwriter is closed.


text:
Q: How to restrict image upload size to less than 2mb? I have an html select option for uploading images.

  Attach Image

  <input type="file" ng-model="image" accept="image/*">

How can I restrict the user from uploading images which are larger than 2MB?

A: This example should give you an idea of how to do it:
HTML
<form  class="upload-form">
    <input class="upload-file" data-max-size="2048" type="file" >
    <input type=submit>
</form>

JS
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more than ' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct - '+fileSize+' bytes');
            }
        }else{
            alert('Please select the file to upload');
            return false;
        }

    });
});


text:
Q: How to have ingest time - processing time as a field in elastic transform I have a pivot transform in elastic that groups data and then performs some arbitrary aggregations on it. The transform frequency is 10 minutes, which means it runs every 10 minutes.
Processing of the data takes longer based on the load on the machine and I want to see how long it took to process the data after it runs. For example if the transform starts running at minute X maybe it takes 2 minutes to run so X+2 is the time i see aggregated data. What i want to see in the transform is this X+2 or X+n to be general as a field.
I couldn't get transform to have a field that doesn't use aggregations because of this I never got the chance to get to timestamp part of the problem.

A: You should be able to find the stats of the latest transform with the following query:
GET _transform/<transform_id>/_stats


text:
Q: creating an engine object for Google maps engine in java I'm following this, but I'm having problems with creating the engine object (as described by the Java section of the code). I have 3 import lines that cant be resolved and I cant find where to get the files. i am still a novice coder so this is appreciated.

A: See here for the java library and how you can import it
Direct download link for a .zip file
For maven add to pom.xml:
<project>
  <dependencies>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-mapsengine</artifactId>
      <version>v1-rev64-1.20.0</version>
    </dependency>
  </dependencies>
</project>

for gradle:
repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.apis:google-api-services-mapsengine:v1-rev64-1.20.0'
}

By the way, Google Maps Engine API will stop working after jan 29th, 2016, so don't waste too much time getting used to it ;-)


text:
Q: Where managed cluster ends and our responsibilities begins in Azure Kubernetes service? I am wondering where responsibilities of Azure ends and our responsibilities begins?
For example we want to set up pods priority for our pods. But pods started by Azure (kube-dns, kube-proxy, heapter, ...) have priority 0 and we would like them to have highest priority of them all. I know that i can change priority of these services using patch even when i don't have manifest for them but i am not sure if i should do it because Azure started these pods. And i am not sure if it is my responsibility or Azures to support these system pods that are part of managed cluster.

A: For Azure Kubernetes Service, it's Kubernetes implementation on Azure. Azure manages something for Kubernetes, such as the node is the Azure VM. But the core is still the Kubernetes.

Azure Kubernetes Service (AKS) makes it simple to deploy a managed
  Kubernetes cluster in Azure. AKS reduces the complexity and
  operational overhead of managing Kubernetes by offloading much of that
  responsibility to Azure.

For more details, see Azure Kubernetes Service (AKS).
About the Pod Priority, it's the Feature of Kubernetes, also according to the version.

Pods can have priority. Priority indicates the importance of a Pod
  relative to other Pods. If a Pod cannot be scheduled, the scheduler
  tries to preempt (evict) lower priority Pods to make scheduling of the
  pending Pod possible.

Describe as the document, the Pod Priority is the order to schedule the pod, not start up the pod. And you can follow the steps How to use priority and preemption if you want to use the Pod Priority.

A: Thank you for posting this question. I'm on the engineering team of AKS. I'm not going to try to answer the question of exactly where the line is drawn between what Azure supports and what you are expected to maintain. That really is a difficult thing to answer and I don't feel comfortable giving an insufficient answer. For the most part, you are right, the pods we install, we try to maintain. We have monitors in place for when these pods are misbehaving and we try to automatically mitigate issues as they arise. We do rely on upstream kubernetes addon-manager for these pods and with few exceptions, these pods are listed with an addon mode of Reconcile, which means our changes will overwrite yours.
Anyways, with all that said, I have submitted a pull request that adds pod priority classes for the service and addon pods for 1.11 (and above) clusters. Thank you for the suggestion.


text:
Q: Too much backtracking: why is there a "redo" here? I'm doing a very simple exercise in Prolog and there's something I don't understand in the trace. The program is a "greater than" (>) on integers represented as successors:
greater_than(succ(_), 0).
greater_than(succ(A), succ(B)) :-
  greater_than(A, B).

My problem: I don't understand why the request greater_than(succ(succ(succ(0))),succ(0)) generates a redo in the following trace:
[trace] ?- greater_than(succ(succ(succ(0))),succ(0)).
Call: (6) greater_than(succ(succ(succ(0))), succ(0)) ? creep
Call: (7) greater_than(succ(succ(0)), 0) ? creep
Exit: (7) greater_than(succ(succ(0)), 0) ? creep
Exit: (6) greater_than(succ(succ(succ(0))), succ(0)) ? creep
true ;
Redo: (7) greater_than(succ(succ(0)), 0) ? creep
Fail: (7) greater_than(succ(succ(0)), 0) ? creep
Fail: (6) greater_than(succ(succ(succ(0))), succ(0)) ? creep
false.

Why is there a redo here? How can I avoid it (without a cut, of course)?
BTW, before you ask : no, it's not some kind of homework...

A: OK, so it's a compiler optimization that a given compiler/version combination might or might not have.
Later versions of SWI do not have this problem. It is probably related to clause indexing. This behaviour would be seen on implementations without indexing, or such that index on the first argument only.
But apparently, "SWI-Prolog provides `just-in-time' indexing over multiple arguments". SWI 5.6.56 manual states that "at most 4 arguments can be indexed". So it probably indexes more than one.

A: There reason there is a redo is that prolog cannot deduce (without examining it) if, by following the next clause, there would be an alternative solution. True, in this case it is just one head unification check (not that this is always trivial) but it could be something that could take a lot of time (or even never terminate).
Now, this is exactly where you should use cut: you know that the extra choice points wont produce a solution (so you are not changing the semantics - a green cut). Alternatively (but it's mostly syntactic sugar covering a cut) you can use if-then-else:
greater_than(succ(A), B):-
    B = succ(BI) ->
    greater_than(A,BI)
    ; B = 0.

not that this still does extra computations which would be avoided with cut.
PS: I doubt that anyone would think it's homework XD


text:
Q: How to get rid of the navigation bar for one screen and show for the remaining I want to hide the navigation bar for the first view controller and show for the rest. In order to achieve this I wrote the following code :
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

self.navigationController?.navigationBarHidden = true
}
override func viewWillDisappear(animated: Bool)
{
super.viewWillDisappear(animated)
self.navigationController?.navigationBarHidden = false
}

After writing this code it works fine, i.e this view controller does not show the navigation bar and the rest show as desired. But after writing this code another problem arise which is as follows:
problem link.
According to the solution given on the above link I need to remove the code:
 override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
}

Which brings me back to problem 1
Can anybody help to get rid of both issues?

A: Use this instead of navigationBarHidden:
self.navigationController?.setNavigationBarHidden(true, animated: animated)

A: In your SecondViewController add this code:
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.navigationBarHidden = false
}

A: On the View you want to hide navigation bar. put this code.
override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)
        self.navigationController?.navigationBarHidden = true;

        print("Navgition bar hidden")

    }

On the next View, from where you want to show the navigation bar. put below code.
override func viewWillAppear(animated: Bool) {

            super.viewWillAppear(animated)
            self.navigationController?.navigationBarHidden = true;

            print("Navgition bar show")

        }


text:
Q: Run Apache Ignite in Docker container as non-root user "Lock is being held to root directory" error when running Ignite container as non-root user.
Created new user and gave user permission for $IGNITE_HOME (/opt/ignite) recursively.
Exception in thread "main" class org.apache.ignite.IgniteException: Failed to start processor: GridProcessorAdapter []
at org.apache.ignite.internal.util.IgniteUtils.convertException(IgniteUtils.java:990)

... 5 more
Caused by: class org.apache.ignite.IgniteCheckedException: **Unable to start under DB storage path [/opt/ignite/persistence]. Lock is being held to root directory**

Should not get "lock" error

A: *

*Make sure /opt/ignite is writable by the user which runs Ignite.

*Enable INFO logging and search for "Unable to acquire lock to file" messages, which have more precise reason.

*Make sure you're not starting more than one node on the same FS!

*Maybe there are some lock files remaining, owned by root. Delete them.


text:
Q: Colour entire row when date in shell matches today's date function colorEntireRowGreenWhenDateOfEventMatchesCurrentDate() {

  var data = SpreadsheetApp.getActiveSheet();
  var dateColumn = data.getRange("C2:C15").getValues();
  var todaysDate = new Date();
  Logger.log(data)

  for (i=0; i=dateColumn.length; i++) {
    if (dateColumn[i] = todaysDate) {
      data.setTabColor("#3c643c");
    }
  }
}

Simply easy request. I want to colour an entire row green when the date entry in column C matches the today's date.

A: There is multiple problem on your code.
First, you made a mistake on your date comparaison
 if (dateColumn[i] = todaysDate) {

instead of
 if (dateColumn[i] == todaysDate) {

Also, the best way to compare date is to compare the time by using getTime() method. See also this SO question : Compare two dates with JavaScript
You try to use the Sheet.setTabColor(String) method which modify the tab color of the sheet, when you try to get the Range.setBackground(String) method or the Range.setBackgroundRGB(red, green, blue) method.
Here is a solution:
function colorEntireRowGreenWhenDateOfEventMatchesCurrentDate() {

  var data = SpreadsheetApp.getActiveSheet();
  var range = data.getRange("C2:C15");
  var values = range.getValues();
  var today = new Date();
  var todaysDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  Logger.log(data);
  range.setBackground(null);

  for (var i in values) {
    var d = values[i][0];
    if (d.getTime() === todaysDate.getTime()) {
      var row = parseInt(i) + 1;
      data.getRange(range.getCell(row, 1).getRow(),1,1,data.getMaxColumns()).setBackground('#3c643c');
    }
  }
}

A: According to the documentation, this explains how to set background color for cells. You can either use setBackground or setBackgroundRGB

A: This can be done much more simply with conditional formatting. Use custom formula in A2.
=$C2:$C=today()

Set range A2:F (change F to your last data column.


text:
Q: Client Server multiple connections in C I am trying to reason about how a simple server implemented in C with sockets can handle concurrent clients. Let's say a simple server waits for a client to connect and then read a message sent from the client. read() is a blocking function so the server will block until a client writes to it. If we assume two clients are concurrently writing to the server. The server will wake up to one of them but what will happen to the other one? is the server still "listening" while handling the request from the first client? I know that the bind function takes an int as the second argument that specifies the backlog (5 by default). does that mean that only 5 clients can connect concurrently to a server? If thats true, how are servers that handle multiple concurrent connections are implemented?

A: The select(2) and poll(2) system calls were invented to deal with this exact situation (with non-blocking sockets).
Then there is a multi-process approach with fork(2), and then, of course, the server could be implemented with threads.
The best solution for your case depends on your specific requirements.

A: You should threads. Usually servers have a main thread which listens for connection. If a connection is made the main thread created another thread and passes that connection to the newly created thread. This way the connections are responded while main thread is still able to listen for new connections.
Edit:
Here is the listen():
listen(int socket_fd, int backlog)
For a given listening socket kernal maintains two queue.

*

*An incomplete connection queue for which SYN has been come but three-way handshaking (TCP) is not done completely. (SYN_RCV state)
A complete connection queue

*Three-way handshaking done. (ESTABLISHED state) backlog argument historically specify sum of both queues. But there is no formal definition of what backlog means.

A: using this function in the server:
int listen(int sockfd, int backlog);

The 'backlog' indicates how many outstanding clients can be trying to connect at one time.
When this function returns:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

then immediately , passing the 'sockfd' parameter to the
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

to have the thread handle the communication with the client.
Note: creating a thread is expensive and slow, so a 'pool' of threads should be initially created and activate one for each client connection  and when the client disconnects, return the thread to the pool


text:
Q: Procedure with Dynamic Query I have similar problem: Stored Procedure with Dynamic Query but I can't do that. I have 100 similar tables, and I want to make dynamic procedure, but it doesn't work.
create or alter procedure Tab
(
    @z nvarchar(50) = ISNULL,
    @s varchar(30) = ISNULL,
    @l nvarchar(30) = ISNULL)
as
begin
    Declare @SQLQuery NVARCHAR(50)

    exec ('select * from'  + @l)  as p
           join z as z on p.C = z.C
           where @z in (home, away)
             and p.s = @s
             and z = @z
 end

Ok so I have 100 tables country c in mssql server and I don't want to write 100 stored procedures to each other, but instead write one for all of that.
This is the code for the procedure for one table
create or alter procedure Tabela
    (@zwyc  nvarchar(50) = ISNULL ,
     @season nvarchar(50) = ISNULL ,
     @lig nvarchar(50) = ISNULL)
as
begin
    Declare @SQL NVARCHAR(max)
    set @SQL = 'select * from '+@lig+' as p
    join zwyc z on p.Country=z.Country
    where '+@zwyc+' in  (home, away)
    and p.season = '+@season+' and z.zwyc = '+@zwyc
    exec (@sql)
go

and now I want to create a dynamic query in a stored procedure to connect to all countries POR , GER , SWE , ENG ...
sample view table POL (@lig)
IDPOL   Country League  Season  data    Time    Home    Away
1   Poland  Ekstraklasa 2012/2013   2012-08-17  17:00:00.0000000    Pogon Szczecin  Zaglebie
2   Poland  Ekstraklasa 2012/2013   2012-08-17  19:30:00.0000000    Piast Gliwice   Gornik Z.
3   Poland  Ekstraklasa 2012/2013   2012-08-18  12:30:00.0000000    Jagiellonia Podbeskidzie
4   Poland  Ekstraklasa 2012/2013   2012-08-18  14:45:00.0000000    Widzew Lodz Slask Wroclaw
5   Poland  Ekstraklasa 2012/2013   2012-08-18  17:00:00.0000000    Lech Poznan Ruch
6   Poland  Ekstraklasa 2012/2013   2012-08-19  13:30:00.0000000    Wisla   GKS Belchatow
7   Poland  Ekstraklasa 2012/2013   2012-08-19  16:00:00.0000000    Legia   Korona Kielce
8   Poland  Ekstraklasa 2012/2013   2012-08-20  17:30:00.0000000    Lechia Gdansk   Polonia Warszawa
9   Poland  Ekstraklasa 2012/2013   2012-08-24  17:00:00.0000000    Zaglebie    Piast Gliwice
10  Poland  Ekstraklasa 2012/2013   2012-08-24  19:30:00.0000000    Jagiellonia Gornik Z.

SQL Server returns this error:

Msg 102, Level 15, State 1, Procedure Tabela, Line 12 [Batch Start Line 1]
  Incorrect syntax near ')'

I change table name
Here is the joined query for one country
select top 10
    IDPOL, p.country, p.league, p.Season, data, time ,home, away
from
    POL p
join
    zwyciezcy z on p.Country = z.Country
where
    p.Season = '2012/2013'
    and z.Zwyciezca = 'Slask Wroclaw'
    and (home = 'Slask Wroclaw' or away = 'Slask Wroclaw')

and here is the result
IDPOL   country league  Season  data    time    home    away
-----------------------------------------------------------------------
4   Poland  Ekstraklasa 2012/2013   2012-08-18  14:45:00.0000000    Widzew Lodz Slask Wroclaw
14  Poland  Ekstraklasa 2012/2013   2012-08-26  13:30:00.0000000    Slask Wroclaw   Korona Kielce
23  Poland  Ekstraklasa 2012/2013   2012-09-02  16:00:00.0000000    Slask Wroclaw   Ruch
25  Poland  Ekstraklasa 2012/2013   2012-09-14  17:00:00.0000000    Podbeskidzie    Slask Wroclaw
38  Poland  Ekstraklasa 2012/2013   2012-09-23  13:30:00.0000000    Slask Wroclaw   GKS Belchatow
46  Poland  Ekstraklasa 2012/2013   2012-09-30  13:30:00.0000000    Gornik Z.   Slask Wroclaw
55  Poland  Ekstraklasa 2012/2013   2012-10-07  16:00:00.0000000    Slask Wroclaw   Polonia Warszawa
62  Poland  Ekstraklasa 2012/2013   2012-10-21  13:30:00.0000000    Lechia Gdansk   Slask Wroclaw
70  Poland  Ekstraklasa 2012/2013   2012-10-28  13:30:00.0000000    Slask Wroclaw   Zaglebie
80  Poland  Ekstraklasa 2012/2013   2012-11-05  17:30:00.0000000    Pogon Szczecin  Slask Wroclaw

A: Is this SQL Server, or MySQL, or Oracle, or MS Access, or .... what?  Please change the TAG associated with the question. Answers will need to change accordingly.
Rather than starting a new Answer, please Edit the first question, and at the end of what was there add a separator of >>>> and then paste your corrections or revisions, keeping all that was above it.
Then, be aware that
Declare @SQL NVARCHAR(50)

needs to be (500) (or more) because what we come up with may be a long SQL.
What I got from 2nd SQL was
select *
from LLL as p
join z as z on p.C = z.C
wher

which was truncated after 50 chars.
Also, it may be continued on several lines, so let it wrap for readability.  What does it look like without params?
Also, the arguments should not be single letters  (@z, @s, @l, as well as s, z, p, ...) but should be descriptive.
Finally, we need to start with what the output is going to look like.
The SQL procedure seems only to have a select with a join.  Is this to be run 100 times? 100 results?
Or are we trying to JOIN 100 tables into ONE result?
Finally let us see some Inputs.  So please show us those table names by running and pasting the 1st 5 or 10 rows from
USE StackOver-or-your-db-name;

SELECT name, max_column_id_used
FROM sys.Tables  (maybe, WHERE name like 'xxx*')

And the structure of one input DDL.
And the first few rows of data in a table, say POR
When you say it doesn't work, tell us the line in the SQL and the Message received.
---------- Feb 24  1am
Good progress.  Lets not create proc 1st, but rather get the sql to work.
Please change arg  @zwyc to have a different name than the table name to avoid confusion; maybe @cname.
Please print a few rows of table zwyc that is being joined.
Here is what I am testing with.  I added lots of pairs of quotes to surround the varchar args. And right before EXEC, I added a
 Print @sql

to  look at the SQL that will execute.  Then change my sql arg values to what works for you,
and paste back into your area above so I know what you tried... noting any further problems...
 Declare
         @zwyc  nvarchar(50) = 'Poland' ,
         @season nvarchar(50) = '2012/2013' ,
         @ateam nvarchar(50) = 'Wisla',
         @lig nvarchar(50) = '[StackOver].[dbo].[DynamicQueryPOL]'

        Declare @SQL NVARCHAR(max)
        set @SQL = 'select * from ' + @lig + ' as p
        join zwyc z on p.Country=z.Country
        where ( p.home =  ''' + @ateam + '''   OR  p.away  = ''' + @ateam + ''' )
        and p.season = ''' + @season + ''' and z.zwyc = ''' + @zwyc + ''''
        print @sql
        --exec (@sql)

---------- Feb 24  13:30 PDT
Are the results good?  With the revised pairs of single quotes around the args it seems to work.
Are all 3 args always provided? Or might some of them be null/not supplied?
I notice that
p.country in the listing is always 'Poland'
Why do we join?  Do we get only 1 row back?  Seems like we get 12 or so rows...
join zwyciezcy z  on p.Country=z.Country

And those 12 rows are then filtered by Team name to only one.
where ::: z.Zwyciezca='Slask Wroclaw'

But we use no other columns from table zwyciezcy z.  So why is the join performed?
Please print a few rows of table zwyciezcy  that is being joined.

A: Issue in Your Query:
In you dynamic query you're not handling z.Zwyciezca = 'Slask Wroclaw' correctly. The way you're handling it is: z.Zwyciezca = Slask Wroclaw without '
select *
from
    POL p
join
    zwyciezcy z on p.Country = z.Country
where
    p.Season = '2012/2013'
    and z.Zwyciezca = 'Slask Wroclaw'
    and (home = 'Slask Wroclaw' or away = 'Slask Wroclaw')

Example Dynamic Query for above should be like:
Declare @SQL NVARCHAR(max)
    set @SQL = 'select * from '+@lig+' as p
    join SomeTable z on p.columnname= z.columnname
    where p.columnName in  (''home'', ''away'')
    and p.anothercolumn= '''+@season + ''''

    print @SQL
    exec (@sql)


text:
Q: How To Find Out What A User "Liked" Facebook API I'm currently calling the facebook me/home edge to get the users home feed. In the results I might get an entry like the JSON posted below.
My question is, when I get an entry like that where the user's friend ".. likes a link." How do I find out what link they liked? I'm trying to get the title and URL, but can't seem to figure out how. I've try just about every option using facebook's graph explorer.
Ideally, I would like that information to be returned when I made the /me/home request. I tried adding "attachments" to the fields parameter, but that didn't work.
  {
      actions=({
        link="https://www.facebook.com/10154950234790111/posts/323892414481111";name=Comment;
      });
      comments={

      };
      "created_time"="2015-01-02T23:18:16+0000";from={
        id=10154950234790453;name="Brian Joe";
      };
      id="10154950234790453_3238924144862222";
      likes={

      };
      privacy={
        value="";
      };
      story="Brian Joe likes a link.";
"story_tags"={
        0=({
          id=10154950234790111;
          length=14;
          name="Brian Joe";
          offset=0;
          type=user;
        });
      };
      type=status;
      "updated_time"="2015-01-02T23:18:16+0000";
    }

A: This is a long standing bug in Facebook, probably older than two years.
https://developers.facebook.com/bugs/648986871793611/
https://developers.facebook.com/bugs/522743067756848/
I and many others have given up trying to repro this for Facebook Support.
You can give it a go if you want by reporting it to https://developers.facebook.com/bugs
Ideally Facebook should be inserting the object target in the story_tags like this
 {
      "story": "phwd likes Moët & Chandon.",
      "story_tags": {
        "0": [
          {
            "id": "13608786",
            "name": "phwd",
            "offset": 0,
            "length": 17,
            "type": "user"
          }
        ],
        "24": [
          {
            "id": "38995979792",
            "name": "Moët & Chandon",
            "offset": 24,
            "length": 14,
            "type": "page"
          }
        ]
      },
      "id": "13608786_10101895322580287",
      "created_time": "2015-01-03T17:35:51+0000"
    },

Where this object
"24": [
              {
                "id": "38995979792",
                "name": "Moët & Chandon",
                "offset": 24,
                "length": 14,
                "type": "page"
              }
            ]

Would instead be something like
"24": [
              {
                "id": "event_id",
                "name": "Name of event",
                "offset": 24,
                "length": 14,
                "type": "event"
              }
            ]

So it ends up really being a feature request.


text:
Q: Find and If Statements in Excel VBA I am trying to write a script where a search is run through an Excel database which is in a Sheet called "Database". The search results are then to be presented in a sheet called "Results".
The search can be made according to certain criteria inputted by the user, namely the fields "Country", "Category" and "Subcategory". These are defined as user-dependent variables as follows:
country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
Subcategory = Sheets("Results").Range("D7").Value

I want the "Country" field to be filled mandatorily, in order for a search to run. If this condition is verified, then the search will run according to the remaining criteria provided by the user. I have written the following in order for this to happen:
finalrow = Sheets("Database").Range("A200000").End(xlUp).Row
For i = 2 To finalrow

    'If the country field is left empty
    If country = "" Then
        Sheets("Results").Range("B10:J200000").Clear
        MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided."
        Sheets("Results").Range("D5").ClearContents
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents
        Exit Sub

    'If the country field is filled in and there results from the search made
    ElseIf Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _
        (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then

            'Copy the headers of the table
            With Sheets("Database")
            .Range("A1:I1").Copy
            End With
            Sheets("Results").Range("B10:J10").PasteSpecial

            'Copy the rows of the table that match the search query
            With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
            End With
            Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

    'Hides search form
    Me.Hide

    End If

Like this, the script and search are running fine.
I now want to take into consideration the event in which the user fills the "Country" field but the value entered does not match anything in the database, i.e., the database contains no information on the country searched.
I was advised to do this by inserting a .Find statement before the already written If statement in order for the script to check, first, if the country is in the database and only after continue with the search. Being a beginner in coding, I searched online and this is what I ended up writing:
With Worksheets("Database")
    Set c = Range("A:A").Find(What:=country, After:=.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False)
    If Not c Is Nothing Then
    MsgBox "Unfortunately, the database does not have any information regarding the country you specified. Please search for information on another country."
        Exit Sub
    End If
End With

This is not working. The script still presents the results whenever I input a country in the database. However, whenever I leave the "Country" field blank, it stopped returning MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided." and whenever I input an inexistent country it just presents the "Results" sheet bearing no results.
How can I fix the issue? Thank you very much for your help.


text:
Q: How to skip SWIG directives in clang-format We use SWIG to generate Python wrappers for some C++ code. SWIG directives start with %, and look like this in headers:
#ifdef SWIG
%apply int* INT_RET_VAL{int * is_donor};
#ENDIF
ErrLevel mmct_hbond_is_donor(MM_Index ct, int atom_idx, int* is_donor);
#ifdef SWIG
%clear int * is_donor;
#ENDIF

When clang-format processes them, the %apply turns to % apply, which is not a SWIG statement anymore! There are lots of these in our code base currently. Is there a good way to convince clang-format to skip the %apply and %clear statements? Or maybe everything in an #ifdef SWIG?

A: You can use // clang-format off.
int formatted_code;
// clang-format off
    void    unformatted_code  ;
// clang-format on
void formatted_code_again;

https://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code


text:
Q: Access global javascript variables using react I have a JavaScript file and want to use it in an React Component.
The Script looks following:
function XMLtoJSON() {
    ....
}
var xml2json = new XMLtoJSON();

And an d.ts File with
interface XMLtoJSON {
    ...
}
declare var xml2json: XMLtoJSON;

I tried to use import './xml2json.js' and the js-code is included in the generated js file, but the part that creates the variable xml2json is not executed.
I recive following error in the browser console 'xml2json' is undefined
If it should be important, I use typescript and .tsx-files.
The Project was created with create-react-app MyProject --scripts-version=react-scripts-ts

A: Not too familiar with typescript for react but your exporting file should look something like this:
function XMLtoJSON() {
    ....
}
var xml2json = new XMLtoJSON();
export xml2json;

and the importing file should have this somewhere in the file:
import { xml2json } from './xml2json';


text:
Q: Setting custom MariaDB max_allowed_packet value in Debian 11? [This is more of an OS config file question, but I have had no response on Unix.SE, so I am hoping that the 'join' of DB admins and sysadmins here may result in better luck…]
Our Moodle server, running Debian 11 (bullseye), now seems to produce an "Error writing to database" message in the web browser when course admins try to manually backup some (larger) courses.
The error message links to error/moodle/dmlwriteexception, which says that we may need to increase the DB server's max_allowed_packet setting.
The page refers to MySQL, but we are running MariaDB (v10.5.15), although I expect the issue will be similar(?).
Indeed, the MariaDB config still seems to be inside /etc/mysql/, but I am not sure which config file I may need to change (or whether I can add an additional "local" 'override' file in one of the *conf.d folders) with the amended setting.
None of
-rw-r--r-- 1 root root 1126 Feb 18  2022 mariadb.cnf
lrwxrwxrwx 1 root root   24 Jun 22  2020 my.cnf -> /etc/alternatives/my.cnf
-rw-r--r-- 1 root root  839 Aug  3  2016 my.cnf.fallback

contain a default max_allowed_packet value.
All of these files 'include' !includedir /etc/mysql/conf.d/, and my.cnf and mariadb.conf both also 'include' !includedir /etc/mysql/mariadb.conf.d/ as well.
In the *conf.d folders, max_allowed_packet is referred to in the following:
conf.d/mysqldump.cnf:max_allowed_packet = 16M
mariadb.conf.d/50-server.cnf:#max_allowed_packet     = 1G

In MariaDB itself, when we query show variables like 'max_allowed_packet';, it returns 16777216 (= 16M), which seems to correspond to the issue we seem to be having with larger files (100 MB+).
I note that the value in mariadb.conf.d/50-server.cnf is commented out. If we were to add an additional conf file in that folder (I prefer not to directly edit the OS-installed config files, if possible) with a larger value, uncommented/enabled, would that be the right place/way for us to increase this setting?

A: Do not alter default settings without serious justifications - they effects both all applications and the server itself.
Your web application, which fails due to this setting, connects to MySQL via some access library. This connection have a lot of settings (host, user, password, default database and so on)... including such setting like "Additional commands" - the commands which are executed each time when the connection established. Add a command SET SESSION max_allowed_packet = {needed_value}; to this setting in the application settings. And this problem should be solved.
If this new setting value will decrease the performance in another application's functions then do not alter connection settings in the app settings but adjust its properties for definite connection object in those code place where the function in question is performed.
The most particular option is to adjust the connection setting during this manual backup. Admin who backups the data should do this "by hands", he must execute the above SQL statement immediately before the backing up.

Update.
In MariaDB this session setting is not dynamic.
So in MariaDB the admin may use the next method:

*

*Open connection #1.

*Set needed setting value globally by SET GLOBAL max_allowed_packet = {needed_value};.

*Open connection #2.

*Perform the backup using connection #2.

*Restore previous setting value.


text:
Q: How To Monitor A MySQL Database I have a small application that connects to a MySQL database.  It is very straight forward - basically the database contains alert entries (so as alerts happen, a new record gets written to this database table).  The application has a Datagridview that is bound to this table to populate visually all of the alerts.
However, what I want to achieve is to somehow 'watch' this MySQL table and auto populate the datagridview when new entries are made into this table (or changes).  I also want to be able to notify the user that the datagridview has been updated.
I have populated my datagridview with the MySQL table, but was after some help in setting this up to be an automatic watcher of the table.  I can set everything up in a background worker, but not sure how to find out when data has changed.
Thanks

A: I'm not familiar with MySQL, but you will probably end up having to poll the database to do this. You'll probably end up with some timer based code that will go check the database at a particular interval.
However, you can do your best to minimize the amount of work done on each check. A bad way to do this would be to retrieve the whole table each time and run a whole bunch of checks and comparisons in the program.
Instead, you could use triggers (and here's the syntax to create one) to know when a row was updated or inserted. How you use the triggers is up to you.
One alternative would be to have a timestamp column on the table that automatically updates whenever there's an insert or update. Similarly you could have a separate table with just the primary key and the same timestamp column (if you don't want to clutter up your main table with extra columns).
Either way, you would keep track of the timestamp you last checked at, and find everything that was inserted or updated after that point in time.

A: Perhaps add Insert, Update, Delete triggers to the table to log row in a new table with two columns..

*

*uid of row changed

*type of change insert/update/delete

Then you access this table and it tells you the specifically which rows were inserted, updated, deleted


text:
Q: Controlling iOS Zoom settings I have a problem in my app where by when users have the iPhone Zoom settings toggled to ON:
Settings > General > Accesibility > Zoom > on
Some of the content within in the app becomes enlarged.
So my question is where can I find the settings to the Zoom options so I can resolve this issue?

A: I can tell you have been working on a large iPhone (or even iPad) when in the Storyboard. However, when this is displayed on a smaller screen, everything will look bigger.
Consider using constraints and previewing the application in Xcode.


text:
Q: How to combine multiple signals into a composite slot in PyQt? The problem described in the top diagram: the reader reads an image a and two objects P1 and P2 have to process this image data. The processing in P2 involves both the original image a and the output of P1: b. Both P1 and P2 extend QWidget and the methods are slots: P1.process(a) and P2.process(a, b).

In an ideal world, I would want to have a way to connect two signals, a from Reader and b from P1 connect to the two parameters of the slot (I am thinking of something similar to LabView). But it looks like Qt signals and slot connections do not allow that.
As an workaround I created a dummy class as an intermediary where input to slot_a just stores the input value in dummy._a attribute and input to slot_b sends out a signal with two args, (dummy._a, b) and this is received by P2.slot_ab(a, b) which finished the processing in P2.
But apparently there is no easy way to ensure that Dummy.slot_a will be called before Dummy.slot_b, so the value of a may not get initialized, or be stale.
What will be a good and simple way to pass a and the corresponding value of b to P2 and trigger its processing?
I am using pyqt5 for this.


text:
Q: static Pay Pal link with business email and without default currency and amount My client wants create pdf file with payment link for donation.
I inserted this file link.
myclient@gmail.com.
The link works OK, but paypal opens with default amount 1 (but possibility to enter price) and default currency USD.
The client wants open paypal link with possibility to select any currency from currencies list and enter any amount.
I found in google only possibility create form with currencies and amount on Web page and send this
info to paypal, but I have no Web Page, I have static Pdf file.
Is it possible create static PayPal link, that opens paypal with possibility to select currency and to enter amount (without price) ? Thank you.

A: No, the link should specify the currency and will default to USD if unspecified. Create several links if you need options for different currencies.
For donations you can use cmd=_donations

*

*https://www.paypal.com/webscr?cmd=_donations&business=placeholderclient@email.com&currency_code=USD

*https://www.paypal.com/webscr?cmd=_donations&business=placeholderclient@email.com&currency_code=EUR


text:
Q: Searching in an Array I have this array:
$fruits = array(
    [0] => array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'),
    [1] => array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),
    [2] => array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere')
    )

How can I find out if the array $fruits already contains apple in it?
I have tried: in_array("apple", $fruits) and that didn't work out.
I also tried various syntax and messed a bit with array_key_exists(), but nothing worked out. Any ideas?

A: PHP is notoriously unwieldy in such cases. The best all-around solution is a simple foreach:
$found = false;
foreach ($fruits as $fruit) {
    if ($fruit['name'] == 'apple') {
        $found = true;
        break;
    }
}

if ($found) ....

You can write this in a number of sexier ways, but all of them will require additional memory allocation and/or will be slower; a good number of them will also be more difficult to understand if you are not very experienced.

A: foreach($fruits as $fruit)
{
    /*In first loop $fruit = array('name'=>'banana', 'color'=>'yellow' ,
      'shape'=>'cylinder')
    */
    if(in_array("apple",$fruit))
    {
       /*Using in_array() function we don't have to worry about array keys.
         The function checks whether the value exists in given array.
         Returns TRUE if value is found in the array, FALSE otherwise.
         if(in_array("apple",$fruit)) checks for TRUE
       */

       //Do something
    }
}

in_array(): http://php.net/manual/en/function.in-array.php

foreach(): http://php.net/manual/en/control-structures.foreach.php

A: $hasApple = false;
foreach ($fruits as $subArray) {
    if ($subArray['name'] == "apple")
        $hasApple = true;
}

This is the normal solution, simple. You can also try with array_map($fruits, function () use (&$hasApple) { /* ... */ }). (but this may be slower...)
As of PHP 5.5 there is an one-liner possible:
$hasApple = in_array("apple", array_column($fruits, "name"));

A: <?php

$fruits = array(
    array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'),
    array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),
    array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere')
);

$result = false;

foreach($fruits as $subarray) {
    if( in_array('apple', $subarray) ) {
        $result = true;
        break;
    }
}

echo "result is ", ($result ? "TRUE" : "FALSE");

?>

A: Try this:
 <?PHP

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

$b = array(array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'), array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere'));
echo in_array_r("apple", $b) ? 'found' : 'not found';

?>

Codepad Demo>>

A: $hasapple = 0;
foreach($fruits as $keynum)
{
    foreach($keynum as $fruitinfokey => $value)
        {
        if($value == "apple")
            {
            echo "fruits contains " . $value;
            $hasapple = 1;
            }
}
}

if($hasapple == 0)
    {
    echo "The array $fruits does not contain apple";
    }

Put a foreach loop inside of another foreach loop to search through expanded keys.

A:     function arraySearch($value, $array) {
       foreach ($array as $key => $val) {
           if ($val['name'] === $value) {
               return true;
           }
       }
       return null;
    }

if(arraySearch('apple',$fruits)){
   echo "yes found";
}else{
   echo "not found";
}


text:
Q: How to track clicks of ads in email using google analytics? I have this problem and really don't know how to solve this.
I'm having this newsletter using phplist system and I have to include some ads in emails. Now that's all fine but my client wants to track the number of clicks on those ads using google analytics.
Is there any way to do that? Thanks in advance for any hints.

A:
Is there any way to do that?

Definitely not inside the E-Mail: No sane E-Mail client supports Javascript.
You would have to link the ads to a URL on your server, register the hit there using GA's _trackPageview() (or maybe _trackEvent()), and redirect to the target ad.

A: Use the campaign Option from GA if you can include it in your Newsletter System, see http://www.google.com/support/analytics/bin/topic.py?hl=en&topic=10996

A: I'd say that you can't really do it right away because you can't include JS in an email.
However you could maybe set up some kind of proxy between the ads and their links. When the user clicks a link it first redirects to a page with google analytics on it (probably on your servers) and then redirect to the actual link.
Also I think some services provide an integrated stats system.


text:
Q: Store QList in QVariant I have a class defined as this:
cdataentry.h:
#ifndef CDATAENTRY_H
#define CDATAENTRY_H

#include <QObject>
#include <QString>
#include <QVariant>
#include <QtOpcUa>
#include <QMetaType>

#include <cnodetype.h>
#include <cdatastatus.h>

/**
 * @brief   A class providing data and methods to describe a single OPCUA ua
 *          node in the user input table.
 */
class CDataEntry : public QObject
{
    Q_OBJECT

public:

    CDataEntry(const QString& np, QObject* parent = nullptr);
    ~CDataEntry();

    QString nodePath() const;

private:

    /**
     * @brief   Obsolute path to the node on the MDE server
     */
    const QString m_nodePath;

};

Q_DECLARE_METATYPE(CDataEntry); // to be able to store it in QVariant.

#endif // CDATAENTRY_H

I am trying to store a QList<CDataEntry> object in a QVariant. For that end, I have provided the Q_DECLARE_METATYPE(CDataEntry);
The problem is that the code doesnt compile, what I get is:
error: no matching function for call to 'QVariant::QVariant(QList<CDataEntry>&)'

What am I missing here?

A: You need to add default constructor, copy constructor and copy/assignment  operator to your QObject subclass.
Like this:
CDataEntry& operator=(const CDataEntry&){}
CDataEntry(QObject* parent = nullptr):QObject(parent){}
CDataEntry(const CDataEntry&){}
//...
CDataEntry(const QString& np, QObject* parent = nullptr)

after that you can use it in QVariant like that:
    CDataEntry test;
    QList<CDataEntry> list;
    list.append(test);

    QVariant var = QVariant::fromValue<QList<CDataEntry>>( list );
    auto t = var.value<QList<CDataEntry>>();
    qDebug() << t.first().nodePath();


text:
Q: Magento addError redirects to login screen I'm creating a Magento module, and I've created a setup resource model that checks if a folder is writable. If yes; it creates a folder, otherwise it displays an error message. The problem is, that when using addError, it redirects to the admin login screen and displays the message there. It doesn't log out though. When reloading the page it ends up where you were before the setup was ran.
class Blabla_Bleh_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup {
    function createImportFolder() {
        $baseDir = Mage::getBaseDir();
        $importDir = $baseDir.DS.'var'.DS.'import';
        $dir = $importDir.DS.'blabladir';
        $io = new Varien_Io_File();
        $errorMessage = Mage::helper('blabla_bleh')->__('Errormessage...');

        if($io->isWriteable($importDir)) {
            $io->checkAndCreateFolder($dir);
        } else {
            Mage::getSingleton('adminhtml/session')->addError($errorMessage);
        }
    }
}

Any ideas?

A: Try the following statement after redirect,
 return;

A: I think you are using wrong class of session.Try core session for this :
Mage::getSingleton('core/session')->addError($errorMessage);

A: Use following code to redirect
Mage::getSingleton('core/session')->addError('Error message to be here');
$this->_redirect('*/*/controllerActionmethod');

Hope this help


text:
Q: Download image from url with google spreadsheet script I'm using google spreadsheet app to parse information from a webstore. So far I've managed to get all the needed information except the images of products. I have the link to the image stored in a variable like this:
var test = 'http://.....image.jpg'

what I need to do is to download the image to my PC into any folder without any confirmation, since all of this will be done in a loop to download all the images from a webpage.