text:
Q: freeradius mac authentication error (mac address not found?) So I set up a freeradius 3.0 server on Debian 9 following the official documentation here and here. I have an authorized_mac file with the addresses of my devices and in the file /etc/freeradius/3.0/mods-enabled/files I indicated which file my mac addresses are in:
files authorized_macs {
    # The default key attribute to use for matches.  The content
    # of this attribute is used to match the "name" of the
    # entry.
    key = "%{Calling-Station-ID}"

    usersfile = ${confdir}/authorized_macs

    #  If you want to use the old Cistron 'users' file
    #  with FreeRADIUS, you should change the next line
    #  to 'compat = cistron'.  You can the copy your 'users'
    #  file from Cistron.
    #compat = no
}

My WiFi access point sends the MAC addresses to the radius server in the format 1A:2B:3C:4D:5E:6F but to be sure that the problem is not coming from there, my authorized_macs file looks like this:
1A:2B:3C:4D:5E:6F
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

1a:2b:3c:4d:5e:6f
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

1A2B3C4D5E6F
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

1a2b3c4d5e6f
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

1A-2B-3C-4D-5E-6F
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

1a-2b-3c-4d-5e-6f
    Reply-Message = "Device with MAC Address %{Calling-Station-Id} authorized for network access"

So when I start the freeradius server in debug mode (freeradius -X) and try to connect to the SSID with my device, an error occurs:
[...] -- line 777
(0) pap: WARNING: No "known good" password found for the user.  Not setting Auth-Type
(0) pap: WARNING: Authentication will fail unless a "known good" password is available
(0)     [pap] = noop
(0)   } # authorize = ok
(0) ERROR: No Auth-Type found: rejecting the user via Post-Auth-Type = Reject
(0) Failed to authenticate the user
(0) Using Post-Auth-Type Reject
[...] -- line 783

Full logs available here. For information, 10.42.0.7 is my freeradius server and 10.42.0.22 is my WiFi access point. The SSID is named "testtt".
TL;DR: The configuration is correct according to the official documentation. The WiFi access point and the freeradius are well connected to each other but the radius server seems not to know the addresses even though they have been given...

EDIT
Here is the end of the file /etc/freeradius/3.0/sites-enabled/default :
server {
        authorize {
                preprocess

                # If cleaning up the Calling-Station-Id...
                rewrite_calling_station_id

                # Now check against the authorized_macs file
                authorized_macs

                if (!ok) {
                        # No match was found, so reject
                        reject
                }
                else {
                        # The MAC address was found, so update Auth-Type
                        # to accept this auth.
                        update control {
                                Auth-Type := Accept
                        }
                }
        }
}

A: Problem solved.
The piece of code I showed in my EDIT should not be added at the end of the file. In fact, the "authorize" section already exists and only this should be added after it (line 281):
rewrite_calling_station_id
       # Now check against the authorized_macs file
       authorized_macs
       if (!ok) {
               # No match was found, so reject
               reject
       }
       else {
               # The MAC address was found, so update Auth-Type
               # to accept this auth.
               update control {
                       Auth-Type := Accept
               }
       }


text:
Q: grouping and plotting data by time in python I have a csv file and I am trying to plot the average of some values per month. My csv file is structured as shown below, so I believe that I should group my data daily, then monthly in order to calculate the mean value.
timestamp,heure,lat,lon,impact,type
2007-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2007-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-01-02 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-01-03 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2007-01-03 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

I am using this code:
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

df= pd.read_csv("ave.txt", sep=',', names =["timestamp","heure","lat","lon","impact","type"])
daily = df.set_index('timestamp').groupby(pd.TimeGrouper(key='timestamp', freq='D', axis=1), axis=1)['impact'].count()
monthly = daily.groupby(pd.TimeGrouper(freq='M')).mean()
ax = monthly.plot(kind='bar')
plt.show()

But, I keep getting errors like this:

KeyError: 'The grouper name timestamp is not found'

any ideas ??

A: You're getting this error because you've set the timestamp column to index. Try removing key='timestamp' from TimeGrouper() or the set_index method and it should group as you expect:
daily = df.set_index('timestamp').groupby(pd.TimeGrouper(freq='D', axis=1), axis=1)['impact'].count()

or
daily = df.groupby(pd.TimeGrouper(key='timestamp', freq='D', axis=1), axis=1)['impact'].count()

A: I believe you need DataFrame.resample.
Also is necessary convert timestamp to DataTimeindex by parameter parse_dates and index_col in read_csv.
names =["timestamp","heure","lat","lon","impact","type"]
data = pd.read_csv('fou.txt',names=names, parse_dates=['timestamp'],index_col=['timestamp'])
print (data.head())

#your code
daily = data.groupby(pd.TimeGrouper(freq='D'))['impact'].count()
monthly = daily.groupby(pd.TimeGrouper(freq='M')).mean()
ax = monthly.plot(kind='bar')
plt.show()

#more simpliest
daily = data.resample('D')['impact'].count()
monthly = daily.resample('M').mean()
ax = monthly.plot(kind='bar')
plt.show()

Also check if really need count, not size.
What is the difference between size and count in pandas?
daily = data.resample('D')['impact'].size()
monthly = daily.resample('M').mean()
ax = monthly.plot(kind='bar')
plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: python compare two csv files with csv module: not iterating through every row I'm trying to compare two csv files and then print the product_id field on one line from each csv file. This is the code in question. Something to note is that in the two csv files, the fields are not in the same order.
import csv
import sys

f1 = sys.argv[1]
f2 = sys.argv[2]
num_matches = 0

with open(f1, 'rb') as f:
    csv_readerf = csv.reader(f)
    csv_readerf.next()
    with open(f2, 'rb') as n:
        csv_readern = csv.reader(n)
        csv_readern.next()
        for row in csv_readerf:
            a_name  = row[0].replace(" ", "").lower()   #not used, can be ommitted
            a_id    = row[1]
            a_post  = row[2]
            a_rev   = row[3]
            a_loc   = row[4]                            #not used, can be ommitted
            a_desc  = row[5].replace(" ", "").lower()   #remove all whitespaces for uniformity
            a_ovr   = row[6]
            a_cmf   = row[7]
            a_sty   = row[8]
            a_siz   = row[9]
            a_arc   = row[10]
            a_wid   = row[11]
            a_url   = row[12]
            for rowP in csv_readern:
                p_name  = rowP[10].replace(" ", "").lower()
                p_id    = rowP[6]

                temp    = rowP[11].split(" ")[0:3]      #disregard time stamp
                p_post  = (" ").join(temp)

                p_rev   = rowP[7]
                if p_rev is "":
                    p_rev = "Anonymous"
                p_desc  = rowP[1].replace(" ", "").replace("\n", "").replace("\r\n", "").lower()
                p_ovr   = rowP[4]
                p_cmf   = rowP[3]
                p_sty   = rowP[0]
                p_siz   = rowP[8]
                p_arc   = rowP[9]
                if p_arc:
                    p_arc = p_arc[0 : p_arc.index(" ")]     #for arch we only want the first word
                p_wid   = rowP[5]
                p_url   = rowP[2]

                print a_id, p_id

The problem I am having is that in the output, which I dumped into a .txt file, not all the product_id's from f1 are printed. I know this for sure, because f1 is a test file I created, and I purposely placed several products of different id's in there.
Another things to note is that I tried looping through each csv in separate scripts, and each worked correctly, printing out each product_id as expected. Why is it that when I embed the for loops, iterating through the first file seems to be cut short? What could be the problem? The test files that I made are small, so they should be able to fit in memory perfectly fine.

A: The error is, like BrenBam mentioned your loop construction
for row in csv_readerf:
   ....
   for rowP in csv_readern:
       # will only work in the first iteration of the outer loop
       # since the csv reader hits eof
       ...

so you simply compare only the first line of csv_readerf with all lines of csv_readern
you would prevent that if you open the csv file of the inner loop inside the outer loop:
for row in csv_readerf:
    ...
    with open(f2, 'rb') as n:
       csv_readern = csv.reader(n)
       csv_readern.next()       ....

        for rowP in csv_readern:
           # will iterate over csv_readern, but only in the first iteration of the outer loop

or if you read the inner file into an array first and loop over that
This a very common beginners error, which often occurs with deep nesting, using functions may help


text:
Q: If $a+1/a$ is an integer, then so is $a^t+1/a^t$ for $t\in\mathbb N$ I need to show if $a$ is in $\mathbb{R}$ but not equal to $0$, and $a+\dfrac{1}{a}$ is integer, $a^t+\dfrac{1}{a^t}$ is also an integer for all $t\in\mathbb N$.
Can you provide me some hints please?

A: Hint: If $\displaystyle a+\frac1a$ is an integer then $\displaystyle \left(a+\frac1a\right)^2,\left(a+\frac1a\right)^3, \ldots $ are integers.
Multiply the powers out and you should be able to see why  $a^t+\dfrac1{a^t}$ is going to be an integer for positive integer $t$, using a combination of symmetry and induction.

A: Use induction on $$a^{t+1} + \frac1{a^{t+1}} = \left(a^t+\frac1{a^t}\right)\left(a+\frac1a\right) - \left(a^{t-1}+\frac1{a^{t-1}}\right)$$

A: Let $T_n = r^n + \dfrac{1}{r^n}$, $T_0 = 2$, and $T_1 = \alpha$
\begin{align}
   r + \dfrac 1r &= \alpha \\
   r &= \alpha - \dfrac 1r \\
   \dfrac 1r &= \alpha - r\\
\hline
   r^{n+2} &= \alpha r^{n+1} - r^n \\
  \dfrac{1}{r^{n+2}} &=  \dfrac{\alpha}{r^{n+1}} - \dfrac{1}{r^n} \\
   r^{n+2} + \dfrac{1}{r^{n+2}}
      &= \alpha\left( r^{n+1} + \dfrac{1}{r^{n+1}} \right)
         - \left( r^n + \dfrac{1}{r^n} \right) \\
   T_{n+2} &= \alpha T_{n+1} - T_n \\
\hline
\end{align}
Clearly, if $\alpha$ is an integer, then $T_n$ is an integer for all non negative integers $n$.


text:
Q: play.libs.WS not recognized in Play framework I am using play.libs.WS in my application, but whenever I compile I get error that play.libs.WS is not resolved. Can someone please help me out in this?

A: Solved the issue. I had to include play_2.10.jar and play-datacommons_2.10.jar in my classpath. Thanks everyone for devoting your time.

A: You don't have to add jars manually one by one.
From docs:

To use WS, first add javaWs to your build.sbt file:

libraryDependencies ++= Seq(
  javaWs
)

And that's all.

A: try the following imports in your controller
import play.api.libs.ws.WS
and
import play.api.libs.ws._


text:
Q: Error of "Missing ;" that I cannot resolve function goToRecordInClasses() {
  var spreadsheet = SpreadsheetApp.getActive();
  var activeSheet = spreadsheet.getActiveSheet().getName();
  if (activeSheet == "Students"){
    var sheet = spreadsheet.getSheetByName("Students");
    var sourceSheet = spreadsheet.getSheetByName('Classes');
    var sheetRow = sheet.getActiveCell().getRow();
    var recordRefNumber = sheet.getRange("B"+sheetRow).getValue();
    If (recordRefNumber > 0){ //This is the line that is highlighted with the error message.
      var searchRange = sourceSheet.getRange("A1:A" + sourceSheet.getLastRow());
      var values = searchRange.getValues();
      var recordRowIndex = [];
      for (var y = 0; y < values.length; y++) {
        if(values[y][0] == recordRefNumber){
          recordRowIndex.push(y + 1);
        };
      };
      sourceSheet.showRows(1,sourceSheet.getMaxRows());
      var range = sourceSheet.getRange("A"+recordRowIndex+":M"+recordRowIndex);
      range.activate();
    }
    else{
      var ui = SpreadsheetApp.getUi();
      ui.alert("The selected record has no reference number.").OK;
    };
  }
  else{
    var ui = SpreadsheetApp.getUi();
    ui.alert("First select a cell in STUDENTS sheet").OK;
  };
};

In the above code I face the following error message:

Missing ; before statement. (line 75, file "macros")

I have also enclosed the photo of the code with error message.
I have added a note to the code line that triggers error.

A: The If has a capital 'I', I think you want to use lowercase.

A: Should be lowercase if on line 75


text:
Q: I am getting this error i dont know why "'Switch' (imported as 'Switch') was not found in 'react-router-dom'" Even though I used Routes instead of switch still its showing the same error ,I installed react dom using the command npm install -S react-router-dom. The code is below
import './App.css';
import Header from './Header';
import Home from './Home';
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom';

function App() {
return (
>     <Router>
>     <div className='app'>
>       <Switch>
>         <Route path='/'>
>           <Header/>
>           <Home/>
>         </Route>
>       </Switch>

>     </div>
>     </Router>

export default App;

The Error that is showing is
'Switch' (imported as 'Switch') was not found in 'react-router-dom'
And
'Route' (imported as 'Route') was not found in 'react-router-dom'

A: I assume that you are using react router v5 as switch is is not in v6. In that case the import for switch is following:
import { Switch } from "react-router";

You are importing it from react-router-dom while it should be from react-router


text:
Q: Prove that the interval contains at least one eigenvalue Let $A = (a_{ij})_{1 \leq i,j \leq n}$ be a symmetric matrix whose entries are real numbers.For each $i \in \{1,2,\cdots,n\}$, show that the set $$E_i := \left\{z : |z - a_{ii}| \leq \left( \sum_{j \neq i} a_{ij}^2 \right)^\frac{1}{2} \right\}$$ contains at least one eigenvalue of A.

A: Let $A=X\operatorname{diag}(\lambda_1,\ldots,\lambda_n)X^T$ be an orthogonal diagonalisation, $\mathbf x_1,\ldots,\mathbf x_n$ be the columns of $X$, so that the $j$-th coordinate of $\mathbf x_k$ is $x_{jk}$, the $(j,k)$-th coordinate of $X$. Let $D$ and $F$ be respectively the diagonal and off-diagonal parts of $A$, so that $A=D+F$. Then $(\lambda_kI-D)\mathbf x_k=F\mathbf x_k$ for each $k$. Taking the squared moduli of the $i$-th coordinates on both sides, we get
$$
(\lambda_k-a_{ii})^2x_{ik}^2=\sum_{j\ne i}a_{ij}^2x_{jk}^2.
$$
Sum over $k$, we obtain
$$
\sum_k(\lambda_k-a_{ii})^2x_{ik}^2=\sum_{j\ne i}\left(a_{ij}^2\sum_kx_{jk}^2\right)=\sum_{j\ne i}a_{ij}^2.\tag{1}
$$
But we also have
$$
\min_k(\lambda_k-a_{ii})^2=\left(\min_k(\lambda_k-a_{ii})^2\right)\left(\sum_kx_{ik}^2\right)\le\sum_k(\lambda_k-a_{ii})^2x_{ik}^2.\tag{2}
$$
Hence the result follows from $(1)$ and $(2)$.


text:
Q: Binutils ld linker how to configure emulation mode (no supported emulations after build with mingw) After successfully building binutils/ld with mingw and trying to run it I am getting this message-
$ ld-new
h:/binutils-2.23.1/ld/.libs/ld-new.exe: unrecognised emulation mode:
Supported emulations:
I've looked through the internals documentation and from what I understand you need to set up the configure or makefile so that the emulation mode you want is installed during the build process but I can't work out how you actually do that.
Would appreciate it if someone could explain the process.
Thanks very much.

A: It seems that default emulation mode is determined based on target tuple that is provided to binutils configure script (--target option).
See also: https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=blob;f=ld/configure.tgt;hb=HEAD


text:
Q: Let user create celery periodic tasks I want to ask you about celery and redis usage in django app. I'm learning about celery for about 2 days and I'm still a bit confused :/ I've installed celery and redis and it's working just fine. My problem is, that I want user to create, update and suspend periodic tasks. I've read this article - http://kindshofer.net/2016/11/19/dynamically_adding_a_periodic_task_to_celery.html and this question - How to dynamically add / remove periodic tasks to Celery (celerybeat) a loooot of other articles, but not as useful as these two), and it appears, that I need to use django-celery. I thought, that it's a great option, but then I've read (here --> https://github.com/celery/django-celery ), that django-celery uses django result backend (it means - my db, rigth? And I want to use redis!). Is it possible to use django-celery with redis? Maybe with django-celery I don't need to use redis? Maybe there's some other way of letting user create periodic tasks? I really need my periodic tasks to be fast and lightweight, because there will be a lot of them and they need to be flawless (and that's why I thought that I need to push them somewhere else).
I'd really appreciate any suggestions!

A: Fast and lightweight and redis == Python RQ. However, job suspension may be an issue.
On the Celery issue: the result backend only stores results. It does not handle the queues. But even then, you can send the results to Redis:
CELERY_RESULT_BACKEND = 'django-cache'

Configure cache:
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

However - the reason to use the django-db backend is that it's possible to create querysets over the results. This is generally more useful, since results are displayed in views and jobs generally are not. Being able to aggregate results (like average job execution time) and create graphs, is very useful to do in Django and much easier to accomplish with the ORM then sorting / aggregating this stuff yourself in python with a key/value store.

A: I think you are making some confusion... Celery needs Redit server as message broker and this 2 things must be installed globally in your system.. In order to integrate this 2 tools with django you install (the best choice would be in your virtual environment) django_celery_beat for periodic tasks with crontab and django_celery_results in order to store Celery tasks using the Django...
Of course it is possible to enable the user to launch and make customized periodic tasks.. You could (in your template, with a form) take user input and, in your views, take that input and pass it to a function on your tasks.py file.. On your tasks.py you could make a function that makes tasks!
This guide is very useful:
https://github.com/codingforentrepreneurs/Guides/blob/master/all/Celery_Redis_with_Django.md


text:
Q: If $A$ is an element of $B$ does that imply that $A$ is a subset of $B$? Question: Suppose that $A\in B$, does this imply that $A\subset B$? If so, why?
I have tried to look at using the following example:
Suppose that $A = 4$ and $B = \{4\}$. We definitely have $A \in B$, but I'm not sure whether this implies $A\subset B$, since $A$ is not even a set, but a number.
I read here that an element of a set can be a subset of a set. But I don't think that it mentions $A\in B \Rightarrow A\subset B$.

A: You are correct all the way through. $A\in B$ does not imply $A\subseteq B$ (and indeed $4\in\{4\}$ but the only subsets of $\{4\}$ are: $\emptyset$ and the whole set $\{4\}$).
Sometimes something can be an element of a set and a subset of it, e.g. $\emptyset\in\{\emptyset\}$ and $\emptyset\subseteq\{\emptyset\}$, though (unless you are a set theorist) this is more of a curiosity.

A: This is generally wrong. If $A$ is an element of $B$, then we can write $B= \{A,\ldots\}$.
A set $A$ is a SUBSET of a set $B$ iff each element $x$ of $A$ is also an element of $B$.
In your case, $A$ is a subset of $B$ would require that $A$ is an element of $A$; the latter would be a cyclic definition of a set: $A=\{A,\ldots\}$.

A: This property is one of the properties defining ordinals, in von Neumann's definition:
it is a set $X$ such that

*

*The relation $\in$ on elements of $X$ is a strict order and $X$ is well-ordered by this relation.

*$X$ is transitive, i.e. $\;\forall x\in X, \:x\subset X$.

For instance, natural numbers are ordinals, and their set $\mathbf N$ is the first transfinite ordinal. Transfinite ordinals  are particularly useful for proofs by transfinite induction.
Elementary examples of this situation: a construction of the set of natural numbers:
$0$ being defined as $\varnothing$, $\; 1=\{\varnothing\}$, $\:2=\{\varnothing,\{\varnothing\}\}$, $\:3=\{\varnothing,\{\varnothing\},\{\varnothing,\{\varnothing\}\}\}$, &c.


text:
Q: regex match whole joined string Trying to write a function that will return the whole section of 'conjoined string'.
The only break should be the start or end of the string and a space character

*

*I would like to match a section of "touching" sting.

*If it contains a matching regex, return the "touching" part

*Else return false
function function_a(string, regex) {
    try {
    const reg = new RegExp(/(?:^|\s)/.source + '(' + /.*?/.source + regex.source + /.*?/.source + ')' + /(?:\s|$)/.source, regex.flags)
    const match = string.match(reg)
    if (match) {
        return match[1]
    } else {
        return false;
    }
} catch (error) {
    console.error(error);
    return false;
} }

The tests I have are
describe('function_a', () => {
    it('should return awordplease', () => {
        const xyz = "mister potter, awordplease";
        expect(function_a(xyz, /(word)/)).toEqual('awordplease');
    });

    it('should return a-man-witha', () => {
        const xyz = "a-man-witha wierd way of sayingit";
        expect(function_a(xyz, /(man|wierd|people)/)).toEqual('a-man-witha');
    });

    it('should return wierd', () => {
        const xyz = "a-man-witha wierd way of sayingit";
        expect(function_a(xyz, /(lady|wierd|people)/)).toEqual('wierd');
    });

    it('should return 3434this__432eed2e-tro_py', () => {
        const xyz = "skdjmdkas 3434this__432eed2e-tro_py wdsds asjbchjzxacuyvdkajsnfrsd";
        expect(function_a(xyz, /(this|that)/)).toEqual('3434this__432eed2e-tro_py');
    });

it('should return skdjmdkas3434select__432eed2e-tro_py', () => {
    const xyz = "skdjmdkas3434select__432eed2e-tro_py";
    expect(function_a(xyz, /(select)/)).toEqual('skdjmdkas3434select__432eed2e-tro_py');
});

});
I can't quite get the regex to work out. I think the issue is with the (?:^|\s) at the start, it matches too much.

A: Based on How to non-greedy multiple lookbehind matches
I added a greedy non-capturing group before the match and a positive look behind,
.*(?<=\s|^)

so now the RegExp is built as follows
new RegExp(/(?:.*)(?<=\s|^)/.source + '(' + /.*?/.source + regex.source + /.*?/.source + ')' + /(?:\s|$)/.source, regex.flags)


text:
Q: include content file inside PCL within Xamarin iOS app I have a Xamarin.iOS app.  It links to a C# PCL.  Within the PCL, I have a text file Foo.txt.  Its build action is set to Content and Copy Always.  Yet when running on the iOS simulator from Visual Studio, I usually can't find it anywhere in the app bundle.
One time I actually did find it, at:
PortableLibrary/Foo.txt.

But other times it has not appeared.  What could be the matter?

A:
Just tested it on the latest Xamarin.IOS version and it works just fine. Make sure that you rebuilt after changing the file settings. But its not found within the .app file if thats what you mean.


text:
Q: Header with scrpage2 disappears on "last page" when using subfiles package When I put two or more TeX files together with the subfiles package, the header disappears on the last pages of the included files.
Why is that?
The Root.tex file:
 \documentclass[a4paper]{scrartcl}
 \usepackage{subfiles}
 \usepackage{scrpage2}
 \usepackage[ngerman]{babel}
 \usepackage{blindtext}

 \clearscrheadfoot
 \pagestyle{scrheadings}

 \begin{document}
   \subfile{test1.tex}\newpage
   \subfile{test2.tex}
 \end{document}

The used subfiles have the same content and are named test1.tex and test2.tex:
 \documentclass[Root.tex]{subfiles}
 \clearscrheadfoot
 \chead[Test]{Test}

 \begin{document}
   \Blindtext
   \Blindtext
 \end{document}

A: After nobody answered here, I have asked Markus Kohm on komascript.de (in German: "Kopfzeile verschwindet mit scrpage2 mit subfiles Paket").
As I understood to keep it local, insert an \clearpage at the end of each subfile will solve the problem.
He also mentioned an global solution which is the following code (insert in root preamble):
\makeatletter
\renewcommand{\skip@preamble}{%
  \expandafter\def\expandafter\document\expandafter{%
    \expandafter\endgroup
    \expandafter\def\expandafter\document\expandafter{\document}%
  }%
  \expandafter\def\expandafter\enddocument\expandafter{%
    \expandafter\endinput
    \expandafter\def\expandafter\enddocument\expandafter{\enddocument}%
    \begingroup
    \edef\@currenvir{document}%
  }%
  \renewcommand{\documentclass}[2][subfiles]{}%
}
\renewcommand*{\subfile}[1]{\skip@preamble\input{#1}}
\makeatother


text:
Q: Struggling with The C Programming Language exercise 1-13 The exercise that I am struggling with says "Write a program to print a histogram of the lengths of words in it's input."
Here is my code so far:
#include <stdio.h>

#define IN  1
#define OUT 0

int main()
{
    int length[15];
    int i, j, k;
    i = j = k = 0;
    int count, c, state = OUT;
    for(i; i<15; i++)
        length[i] = 0;
    while ((c = getchar()) != EOF)
    {
        if ((c == '\n' || c == ' ' || c == '\t') && (state == IN))
        {
            state = OUT;
            if ((count > 0) && (count < 16))
                length[count -1]++;
            if (count >= 16)
                length[14]++;
        }
        if ((c != '\n' && c != ' ' && c != '\t') && (state == OUT))
        {
            state = IN;
            count = 0;
        }
        if (state == IN)
            count++;
    }
    for(j; j<15; j++)
    {
        printf("length %d\t",j+1);
        for(k; k<length[j]; k++)
            printf("X");
        printf("\n");
    }
    return 0;
}

When I run this code with a test like:
a bb ccc
^d

or:
aaa bb c
^d

it gives me a histogram with just one 'X' in the 1 column. I do not know what I am doing wrong. Any help or advice would be greatly appreciated!

A: The "normal" way to write a for loop is:
for (k = 0; k < length[j]; k++)

You skip the initialisation step, relying on the i = j = k = 0 set up at the start of the program. Setting aside the fact that most compilers will complain (issue warnings) about an unused value k here, a deeper problem is the fact that this loop is nested inside another loop. The first iteration goes through okay, k starts at 0 and goes up to length[0] - 1 as it should; but on the second iteration, k starts at length[0] and goes up to length[1] - 1, which is likely to be a lower number, therefore shortening or skipping the bar for this line. And if it did get printed, the "bar" (if you'll excuse the pun) will have been set higher, so each successive line will be shortened by the maximum length of the preceding lines.

A: The error in your code has been already pointed out by @Amadan.
I'm going to present you your code with a few printf statements to help isolate the problem.
If you are not able to or not comfortable with a debugger, I think you need to get acquainted with one.
A poor man's way of debugging is by inserting printf statements at crucial places to understand how the code is working.
#include <stdio.h>

#define IN  1
#define OUT 0

int main()
{
    int length[15];
    int i, j, k;
    i = j = k = 0;
    int count, c, state = OUT;
    for(i; i<15; i++)
        length[i] = 0;
    while ((c = getchar()) != EOF)
    {
       printf("%c\n", c);
       printf("Came here 1.\n");
        if ((c == '\n' || c == ' ' || c == '\t') && (state == IN))
        {
           printf("Came here 2. Count= %d\n", count);
            state = OUT;
            if ((count > 0) && (count < 16))
                length[count -1]++;
            if (count >= 16)
                length[14]++;
            printf("length[%d] = %d\n", count-1, length[count-1]);
        }
        else if ((c != '\n' && c != ' ' && c != '\t') && (state == OUT))
        {
           printf("Came here 3.\n");
            state = IN;
            count = 1;
        }
        else if (state == IN)
        {
           printf("Came here 4.\n");
            count++;
        }
        else
        {
           printf("Didn't expect here.\n");
        }
    }
    for(j; j<15; j++)
    {
        printf("length %d\t",length[j]);
        for(k; k<length[j]; k++)
            printf("X");
        printf("\n");
    }
    return 0;
}


text:
Q: apt: Automatically runs initramfs after install package I have Ubuntu 21.10 installed on my Raspberry Pi 4. When I runs apt install <Any package>, it will trigger initramfs. How to disable it?
Output:
Reading package lists... Done Building dependency
tree... Done Reading state information... Done The following
additional packages will be installed:   buildah catatonit conmon
containernetworking-plugins   crun fuse-overlayfs fuse3
golang-github-containernetworking-plugin-dnsname   golang-github-containers-common
golang-github-containers-image libfuse3-3   libostree-1-1 podman uidmap Suggested
packages:   containers-storage docker-compose The following
packages will be REMOVED:   fuse The following NEW packages will
be installed:   buildah catatonit cockpit-podman conmon
Selecting previously unselected package fuse-overlayfs.
Preparing to unpack .../12-fuse-overlayfs_1.4.0-1_arm64.deb ...

Unpacking fuse-overlayfs (1.4.0-1) ...
Selecting previously unselected package
golang-github-containernetworking-plugin-dnsname.                           Preparing to unpack
.../13-golang-github-containernetworking-plugin-dnsname_1.1.1+ds1-4_arm64.deb ...               Unpacking
golang-github-containernetworking-plugin-dnsname (1.1.1+ds1-4) ...
Setting up crun (0.17+dfsg-1) ...
Setting up uidmap (1:4.8.1-1ubuntu9) ...
Setting up libostree-1-1:arm64 (2020.8-2) ...
Setting up golang-github-containers-image (5.12.0-2) ...
Setting up conmon (2.0.25+ds1-1.1) ...
Setting up containernetworking-plugins (0.9.0-1) ...
Setting up catatonit (0.1.5-2) ...
Setting up libfuse3-3:arm64 (3.10.3-2) ...
Setting up golang-github-containernetworking-plugin-dnsname
(1.1.1+ds1-4) ...
update-initramfs: deferring update (trigger activated)    Setting up
fuse-overlayfs (1.4.0-1) ...
                                Installing
/lib/firmware/5.13.0-1015-raspi/device-tree/broadcom/bcm2711-rpi-4-b.dtb into /boot/dtbs/5.13.0-1015-raspi/./bcm2711-rpi-4-b.dtb
                                 Taking backup of
bcm2711-rpi-4-b.dtb.                     Installing new bcm2711-rpi-4-b.dtb.
                     Installing
/lib/firmware/5.13.0-1015-raspi/device-tree/broadcom/bcm2711-rpi-4-b.dtb into /boot/dtbs/5.13.0-1015-raspi/./bcm2711-rpi-4-b.dtb
                                 Taking backup of
bcm2711-rpi-4-b.dtb.                     Installing new bcm2711-rpi-4-b.dtb.
                     Taking backup of spi0-2cs.dtbo.
                     Installing new spi0-2cs.dtbo.
                     Taking backup of w1-gpio.dtbo.
                     Installing new w1-gpio.dtbo.
                     Installing new rpi-proto.dtbo.
                     Taking backup of ads1015.dtbo.
                     Installing new ads1015.dtbo.
                     Taking backup of max98357a.dtbo.
                     Installing new max98357a.dtbo.
                     Taking backup of spi5-1cs.dtbo.
                     Installing new spi5-1cs.dtbo.
                     Taking backup of iqaudio-dacplus.dtbo.
                     Installing new iqaudio-dacplus.dtbo.
                    Taking backup of pca953x.dtbo.
                    Installing new pca953x.dtbo.
                    Taking backup of mz61581.dtbo.
                    Installing new mz61581.dtbo.
                    Taking backup of spi-rtc.dtbo.
                    Installing new spi-rtc.dtbo.
                    Taking backup of hifiberry-dac.dtbo.
                    Installing new hifiberry-dac.dtbo.
                    Taking backup of spi2-1cs.dtbo.
                    Installing new spi2-1cs.dtbo.
                    Taking backup of w5500.dtbo.
                    Installing new w5500.dtbo.
                    Taking backup of cap1106.dtbo.
                    Installing new cap1106.dtbo.
                    Taking backup of minipitft13.dtbo.
                    Installing new minipitft13.dtbo.

Sorry for poor log quality..
Update: I saw When installing updates or from software center in Ubuntu 12.04, error messages which is similar to my issue, but solution in that post is not working for me.

A: This is answer to "How can I remove triggers for Initramfs"
initramfs is included in the post-installation script of the package you are trying to install. The package might depend on some other package that needs to upgrade initramfs. Removing its triggers will BE DANGEROUS and can make that package unresponsive.
From the official Ubuntu Wiki documentation:

Initramfs is used as the first root filesystem that your machine has access to. It is used for mounting the real rootfs which has all your data. The initramfs carries the modules needed for mounting your rootfs. But you could always compile your kernel to have these modules. Then would you need the initramfs? The answer to this is "depends on your system". Some system configurations need a user space utility to provoke the kernel to configure the devices appropriately. Eg: cryptdevices : they need to have a password from the user. This password requesting utility being a user space utility, could pose a chicken and egg problem i.e your rootfs contains the user space utilities, but the rootfs cannot come up till the user space utilities are available. In such cases, the initramfs plays a mediator in between giving a temporary rootfs which has bears the user space utilities needed for mounting the real rootfs.

You can remove it by one of the following steps.

*

*Purge it:
sudo dpkg -P initramfs-tools --force-all

*Alternatively, you can remove it from the post-installation script.
Find the post-installation script by running:
ls /var/lib/dpkg/info | grep <package> | grep ".post"

Edit the file:
sudo gedit <file name>

Remove the update initramfs... line.

*Remove triggers for initramfs:
sudo rm -rf /var/lib/dpkg/info/initramfs*

All of the above commands are 99% guaranteed to break your system. Don't run them unless or until you know what you're doing.
Good Luck!


text:
Q: Gaussian Kernel in Tensorflow Torch7 has a library for generating Gaussian Kernels over a fixed support. Is there anything comparable in Tensorflow? I see these distributions in TF contrib, but I am not sure how I would use that to get a kernel (on a fixed grid with weights summing to 1).

A: I am using the following function to generate the kernel to blur images:
def gaussian_kernel(size: int, mean: float, std: float):
    """Makes 2D gaussian Kernel for convolution."""
    d = tf.distributions.Normal(mean, std)
    vals = d.prob(tf.range(start = -size, limit = size + 1, dtype = tf.float32))
    gauss_kernel = tf.einsum('i,j->ij', vals, vals)
    gauss_kernel = gauss_kernel/tf.reduce_sum(gauss_kernel)
    return gauss_kernel

Kernel size is 2 * size + 1. E.g. size=2 generates a 5x5 kernel.
I am using it in a lambda layer by convolving the kernel with each channel of the original input (tf.nn.conv2d). This is with tf 1.12, but it should for tf2 work with some adjustments (e.g. tfp.distributions.Normal instead of tf.distributions.Normal)


text:
Q: Why is ItemSearch in Amazon's Product Advertising API returning invalid XML? The Amazon Product Advertising API appears to be fatally buggy and I'm wondering if it's just me, and if there's any work around for this apparent bug.
When I present the following parameters to the Product Advertising API:
<Arguments>
    <Argument Name="Operation" Value="ItemSearch"></Argument>
    <Argument Name="Service" Value="AWSECommerceService"></Argument>
    <Argument Name="Signature"
        Value="<omitted>"></Argument>
    <Argument Name="Manufacturer" Value="Leg Avenue"></Argument>
    <Argument Name="AssociateTag" Value="<omitted>"></Argument>
    <Argument Name="Version" Value="2009-03-31"></Argument>
    <Argument Name="AWSAccessKeyId" Value="<omitted>"></Argument>
    <Argument Name="Timestamp" Value="2012-10-18T15:49:10Z"></Argument>
    <Argument Name="ResponseGroup" Value="ItemAttributes,SalesRank"></Argument>
    <Argument Name="SearchIndex" Value="Apparel"></Argument>
</Arguments>

I get back a whole bunch of XML, part of which contains a clear and significant bug:
<Publisher>Rubies/Publisher>

Note the missing proper close tag for the <Publisher> element.  As you might expect, this causes any XML parser to blow up.
I don't see any easy work around for this.  I searched around a bit and did not find anyone else reporting the same problem, which I find kind of surprising given the severity of this issue.  It basically makes the entire API useless.
I'm sure I'm missing something - the API can't be this buggy.  Anyone know what I'm doing wrong?  Can anyone else confirm whether this is a bug?
[Edit] This appears to be intermittent.

A: If you make too many requests to the Amazon Product API in a row you get throttled. This can make debugging issues frustrating. If the problem is intermittent and you can get the information you expect from the API and your code given different parameters then perhaps there is bad data in Amazon's Product API database or you should wait a day and see if you're getting throttled.
If you're getting throttled you don't get any data instead an error code of some sort, it has been a while since I debugged some issues, my code works, perhaps you can adapt it.


text:
Q: Can i insert form inputs in other parts of SQL queries? I'm trying to insert form values into the tables and column spots in SQL queries, in hopes of PHP passing it's value to MySQL.
like this:
$sql= "SELECT * FROM  '{$table}' WHERE '{$catagory}' = '{$value}'";

So is there a way I can do something like this without getting a syntax error?

A: Did you try like this
$sql= "SELECT * FROM  $table WHERE $catagory = '$value'";

or if you trying to select from form input fields you can try like this
$sql= "SELECT * FROM $_POST[table] WHERE $_POST[category] = '$_POST[value]'";

just please be aware that this second example is not secure way to inserting input fields values into query since someone can SQL inject your query, so you know.

A: Yes, just like this...
$sql= "SELECT * FROM $table WHERE $category ='$value'";

Just make sure the whole string is within double quotes "   "
I do this all the time, but I use prepared statements...you should as well

A: First of all, let me make my disclaimer that you should never use raw input data from a form to determine databases, tables, or columns in your queries. It's bad news. Create some sort of mapping that does not expose your database schema to end users and restricts the values to only what you want and cannot be changed by developer tools in the browser or a bot trying to hack your site.
If you want to do it with mysql you will need to do to escape the form data with mysqli_real_escape_string to prevent SQL injection. I use sprintf to make it cleaner but it's not required.
$sql = sprintf(
    "SELECT * FROM `%s` WHERE `%s` ='%s'",
    mysqli_real_escape_string($table),
    mysqli_real_escape_string($column),
    mysqli_real_escape_string($value)
);

Please note the backticks (`) around the table  and column names. There are not apostrophes a.k.a. single quotes ('). It's the proper way to encapsulate databases, tables, and columns in MySQL queries. It will help prevent issues with special characters in the names.


text:
Q: HTML/Prestashop, moving the category image to the left In the normal prestashop theme, there is a box at the top of the category pages for a description of the category as a whole. The box has an outline and contains a picture and some text.
The text is normally below the image, so the block takes up a lot of room. I would like to float the image to the left, and wrap the text around it, so it's smaller.
I suspected this would be easy, because the image and text are in divs, and both of them are in another div for the outline. So I simply added float:left to the image's DIV.
The image moved to the right OK, and the text flowed too. However, the surrounding DIV did not resize properly, so the image now runs right out of the box.
How do I get the enclosing DIV to resize properly?

A: You need to force the containing div to wrap the floated contents. You can do this a few ways, one being to add overflow:hidden.
.content_scene_cat {overflow:hidden;}


text:
Q: How to see built-in rules with nmake? With GNU make one can say make -npf /dev/null (or on Windows NUL) in order to show the built-in rules. Where -n means --just-print, -p means --print-data-base and -f specifies the make file to use.
How can I achieve the same with nmake?

A: The command nmake -p will give:
INFERENCE RULES:

.asm.obj::
        commands:       $(AS) $(AFLAGS) /c $<

.asm.exe:
        commands:       $(AS) $(AFLAGS) $<

.c.obj::
        commands:       $(CC) $(CFLAGS) /c $<

.c.exe:
        commands:       $(CC) $(CFLAGS) $<

.cc.obj::
        commands:       $(CC) $(CFLAGS) /c $<

.cc.exe:
        commands:       $(CC) $(CFLAGS) $<

.cpp.obj::
        commands:       $(CPP) $(CPPFLAGS) /c $<

.cpp.exe:
        commands:       $(CPP) $(CPPFLAGS) $<

.cxx.obj::
        commands:       $(CXX) $(CXXFLAGS) /c $<

.cxx.exe:
        commands:       $(CXX) $(CXXFLAGS) $<

.rc.res:
        commands:       $(RC) $(RFLAGS) /r $<

.SUFFIXES: .obj .asm .c .cc .cpp .cxx .f .f90 .for .rc

See nmake /? for other switches, such as -n. Also see my answer here for some useful references to the older nmake documentation.


text:
Q: send a GetFeatureInfo to Geoserver over a time range I want query geoserver about FeatureInfo from a set of images temporally spaced. How I should build this route?

A: There is a link where time support for GetMap in Geoserver is described, which seems to be available from version 2.2. You could check, if using time parameter for GetFeatureInfo on a time-enabled wms will work, too.
Otherwise, I am pretty sure, there is time support with the thredds WMS/ ncWMS, where you can expose netCDF files containing time series data. Maybe it's worth to check them as well.


text:
Q: I could do two different NavDrawers in the same Android App? my problem is that:
I want to make a login service in my application and depending on which user logs in, go to a different NavDrawer activity. In Android Studio when you create the NavDrawer activity that comes by default, it generates one perfectly. But when I want to generate a different one, having the same name doesn't create anything.
The only way I have found is by refactoring everything generated by the Android Studio wizard and changing all the names of the layouts.
I would like to know if there is an easier way to create another NavDrawer without having to refactor so much and without so many errors.
Thank you!
NavDrawers Generated

Conceptual Scheme

A: Its Solved, you only need to make an instance of one of these nav drawers and then extend that to another one.


text:
Q: What is the procedure for having my spouse/significant other as a member of the same SE site? If my spouse or significant other shares a passion for one or more of the same topics as me, then joining a stack exchange site would seem like a good idea. But this does create a potential issue.
If this site is on a topic we both discuss together a lot in person, then it is inevitable that recent questions or answers of mine (or theirs) would come up in discussion, and probably lead to viewing it on-line. Then the problem becomes - am I getting a lot of instant rep merely because my significant other upvotes my questions/answers?
What should I do about this? Should we make it clear, if both of us are well-known on the StackExchange site, of our relationship (i.e. in chat)? Should we refrain from voting at all on each others' questions & answers? If we answer each others' questions, and another user has an answer of similar quality, should we default to accepting the other users' answer?
Please note I am not advocating that the significant other not be allowed/discouraged to join the site, nor am I suggesting that it should be mandatory that a relationship be revealed.

A: I think the same rules apply to you two as everyone else. If the other's post is good, upvote it. However, if it's bad, don't hesitate to downvote it. So long as you stay objective, I don't think anyone will have a problem with it.

A: We would never allow a situation to develop where it became mandatory for you to disclose anything personal in your public profile.
We do require that you disclose affiliation with something you are promoting in your posts if you are involved with that something, but I don't think that situation would arise in the context of offering up one's spouse. At least I hope not. Still, this disclosure would need to be within the post.
That said, if excessive, the patterns would be indistinguishable from co-workers that tend to up-vote each other's posts quite frequently, and we do contact people to warn them when we notice it. Just be sure to show your appreciation for outstanding contributions as a matter of habit, if your spouse wrote some of them then fine :)

A:
Should we refrain from voting at all on each others' questions & answers?

Personally I'd do this. It's much easier than trying to remember how many you've voted on and worrying about whether you might trigger any vote fraud scripts etc. It also saves you from any accusations of sockpuppetry even if they're "light-hearted".
My son is active on Gaming and I make it a point not to vote on his posts regardless of how good (or bad) they are.
I also don't answer his questions on the site.

A: Essentially:
Always vote for the post, not the person.  If you find yourself visiting your spouse's profile just to see their questions and answers (and subsequently vote on them), then that's likely a Bad Thing.


text:
Q: Passing Mouse Events to Base Control, search of a good solution Hallo,
Thank you for reading. The Answers i get realy helped me, A LOT!
But to the Problem. I have UserControl as a base Class. The child Class adds its Controls on the UserControl, lets call first BaseControl and the second ChildControl.
At BaseControl Level i have some Delegates attached on some MouseEvents.
The Problem is that they will not fire, if there is an Child control added to them. So I know i can Take all the Mouseevents from all the the Childrensevent and tunnle them through. But thats first very dirty an second not enough. Cause i want to like Paint a Border around or move the BaseControl.
So my Question is realy: Is there a way to gain full access to the MouseEvents in at Base Control, if there are ChildControls added?
Thank you lots!
Thomas
EDIT:
Here is the snippets, hope you understand:
 public partial class baseControl : UserControl
{
    public baseControl()
    {

        InitializeComponent();

        //will not be called
        this.MouseUp += delegate(object sender, MouseEventArgs e)
        {
            // some code
        };
    }

}

public partial class child : baseControl
{
    secretControl childControl;
    public child()
    {
        InitializeComponent();
        this.childControl= new secretControl ();
        this.childControl.Visible = true;
        //... ,more
        this.forChildUsePanel.Add(this.childControl);

        // works fine , as it will be called
        this.childControl.MouseUp += delegate(object sender, MouseEventArgs e)
        {
            // some code
        };

    }

}

Reminder: This are snipptes, so for understanding purpose it cut some corners.
Simpelput:
I want to get some Mouse Event on every Control added to the BaseControl.

A: I believe you should attach the event handler to every single child control and not to the parent control, if you want to intercept it in the child.

A: What kind of controls are you adding? It might be a solution to customize these controls. If you add a Label for example, make a new MousePassthroughLabel which inherits from Label und whose inbuild MouseEvent simply fires the one of its parent control. Do this once for every type of control and use you own "MousePassthrough"-Controls instead of the native controls.

A: There is this new Microsoft technology, Reactive Extensions, which will make event-driven programming easier.


text:
Q: Getting date from web, returns nil Doing a check to get the current time and date from Google.  The first option works although not the best way to do this as it's using a depreciated method and waiting for everything to finish with the synchronous method is not good UX.
-(NSDate*)timeAndDateFromWeb{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL URLWithString:@"https://google.co.uk"]];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *httpResponse = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:nil];
    NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
    DebugLog(@" *** GOOGLE DATE:  %@ ****",dateString);
    if (httpResponse){
        hasDataConnection = YES;

    }
    else{
        hasDataConnection = NO;

    }

    // Convert string to date object
    NSDateFormatter *dateformatted = [NSDateFormatter new];
    [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    [dateformatted setLocale:locale];

    return [dateformatted dateFromString:dateString];
}

Trying to adapt it is almost there although I'm returning nil for my date string: [dateformatted dateFromString:dateString];
    NSURL *url = [NSURL URLWithString:@"https://google.co.uk"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSHTTPURLResponse *httpResponse = nil;
    NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
      if (error) {
          hasDataConnection = NO;
          //NSLog(@"\n\n ----> Not connected Error,%@", [error localizedDescription]);
      }
      else {
          //NSLog(@"\n\n -----> connected:  %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
          hasDataConnection = YES;

      }
    }];

    // Convert string to date object
    NSDateFormatter *dateformatted = [NSDateFormatter new];
    [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    [dateformatted setLocale:locale];

    DebugLog(@" *** GOOGLE DATE:  %@ ****",[dateformatted dateFromString:dateString]);

    return [dateformatted dateFromString:dateString];

A: When you're switching from sync to async, can't return value the same way as before.
When you call sendAsynchronousRequest method, it starts a background task, but your thread continues work instantly. That's why both httpResponse and dateString are null.
So instead of that you should change your return type to void, because you can't return result instantly, and add a callback, which will be run when the job is done. And process your formatting in the completion of the task too:
- (void)timeAndDateFromWeb:(void (^)(NSDate *))completion {
    NSURL *url = [NSURL URLWithString:@"https://google.co.uk"];
    NSURLSessionTask *task = [NSURLSession.sharedSession
     dataTaskWithURL:url
     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
//            hasDataConnection = NO;
            //NSLog(@"\n\n ----> Not connected Error,%@", [error localizedDescription]);
        }
        else if ([response isKindOfClass:NSHTTPURLResponse.class] ) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];

            // Convert string to date object
            NSDateFormatter *dateformatted = [NSDateFormatter new];
            [dateformatted setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
            NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
            [dateformatted setLocale:locale];

//            DebugLog(@" *** GOOGLE DATE:  %@ ****",[dateformatted dateFromString:dateString]);

            completion([dateformatted dateFromString:dateString]);
            //NSLog(@"\n\n -----> connected:  %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
//            hasDataConnection = YES;

        }
    }];
    [task resume];
}

And so the result of this method will be returned to the block, same as result of the background task.
Don't forget, that it will be called on the background thread, same as the download task completion block. So if you wanna change some UI you need to move back to the main thread:
[self timeAndDateFromWeb:^(NSDate *date) {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%@", date);
        // UI changes
    });
}];

Alternatively you can move it to the main thread inside your function, right before returning the result:
NSDate *date = [dateformatted dateFromString:dateString];
dispatch_async(dispatch_get_main_queue(), ^{
    completion(date);
});


text:
Q: What is SRUJet? I see in Event log many error entries  :

svchost (1500) SRUJet: An attempt to open the file
  "C:\Windows\system32\SRU\SRUDB.dat" for read / write access failed
  with system error 5 (0x00000005): "Access is denied. ".  The open file
  operation will fail with error -1032 (0xfffffbf8).

The key in the event log is ESENT : ESENT 490 error
I already made that error to disappear by setting Everyone - full control to the C:\Windows\system32\SRU\ folder....
But :
Question
1) What is SRUJet ?
2) What's the purpose of the  C:\Windows\system32\SRU\ folder  ?
3) What is ESENT?

A: SRUJet is a database engine working with database file srudb.dat.
This thread shows that:

*

*You should be safely able to delete srudb.dat and Windows should re-create it.

*The functionality is part of Diagnostic Policy Service.

You can post permissions of the file for further details.

A:
3) What is ESENT?

ESENT is the Windows "Extensible Storage Engine" runtime, and is essentially a data store creator for applications such as Desktop Search. In the context of your question, ESENT is used by the Diagnostic Policy Service to build the srudb.dat data file.

A: Stop the Diagnostic Policy Service and delete srudb.dat. Worked for me.
To stop the Diagnostic Policy Service:  + R -> Type in services.msc -> press Enter -> Scroll down and double-click on Diagnostic Policy Service -> Click the Stop button.


text:
Q: iSeries JDBC Sql statement with "é" in column name throws java.sql.SQLException: [SQL0104] I am having trouble using the character "é" in a returned column name from an SQL query.  Running this query
SELECT PRCAT as Categorie, PRYEA as Année, PRDSC as Designation from DEMO.PRODUCT

using the IBM Toolbox JDBC driver connecting to an iSeries produces this exception:
 java.sql.SQLException: [SQL0104] Token é was not valid. Valid tokens: , FROM INTO. Cause . . . . . :   A syntax error was detected at token é.  Token é is not a valid token.  A partial list of valid tokens is , FROM INTO.  This list assumes that the statement is correct up to the token.  The error may be earlier in the statement, but the syntax of the statement appears to be valid up to this point. Recovery  . . . :   Do one or more of the following and try the request again: -- Verify the SQL statement in the area of the token é. Correct the statement.  The error could be a missing comma or quotation mark, it could be a misspelled word, or it could be related to the order of clauses. -- If the error token is <END-OF-STATEMENT>, correct the SQL statement because it does not end with a valid clause.
    at com.ibm.as400.access.JDError.throwSQLException(JDError.java:650)
    at com.ibm.as400.access.JDError.throwSQLException(JDError.java:621)
    at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1481)
    at com.ibm.as400.access.AS400JDBCPreparedStatement.<init>(AS400JDBCPreparedStatement.java:185)
    at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:1903)
    at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:1726)
...

Is this an issue of improper jdbc driver setup, or is there some built in limitation to what characters can be used (and where can I find this?  I find IBM doco impossibly labyrinthine...).  My jdbc connection code looks like this:
Class.forName("com.ibm.as400.access.AS400JDBCDriver").newInstance();
Connection cnnobj=DriverManager.getConnection("jdbc:as400://"+ipAddress+";errors=full;date format=iso;time format=iso;", user, pass);

A: What happens if you quote the alias name?
SELECT PRCAT as Categorie, PRYEA as "Année", PRDSC as Designation from DEMO.PRODUCT


text:
Q: Unable to display extracted data from API into HTML form I started using the AlchemyAPI key to extract json/xml data from url's. The alchemy url api key works just great when entered along with the queried url but I wanted the url part to come from the user side so first I created a form with the following code:
<form method="post" class="SearchCSS" action="/NENSearch.php?go" id="categorizer">

Enter your Queries

<input type="text" name="Search" placeholder="Enter the article URL">
<input type="submit" value="Search">
</form>

Then using PHP passed the user's submitted url into the endpoint of the alchemy api and stored the json data into a variable and later displayed the parsed data using the following code (Problem: Code actually doesn't display anything):
<?php
echo "this works here";
if(isset($_POST['submit'])){
  if(isset($_GET['go'])){
  if(preg_match("%^((http?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i", $_POST['Search'])){
  $url=$_POST['Search'];}

  echo $url;}
  $response = file_get_contents("http://gateway-a.watsonplatform.net/calls/url/URLGetCombinedData?extract=page-image,entity,keyword,taxonomy&apikey=1f324507a9d516d9429e14f970ccc83de9df2&showSourceText=1&sentiment=1&outputMode=json&quotations=1&url='.$url.'");
  $response = json_decode($response);
  echo $response;}
  echo "
 this is not working";
?>

The basic alchemyAPI url I used looks like this (drupal url added at the end) :
http://access.alchemyapi.com/calls/url/URLGetRankedTaxonomy?apikey=1f324507a9d51694a29e14f970ccc83de9df2&outputMode=jsonp&knowledgeGraph=1&extract=taxonomy&url=https://www.drupal.org/node/2148541
I just started working with API's and Any help in displaying the parsed json data into html form will be of great help. Thanks in advance. :)

A:
"(Problem: Code actually doesn't display anything)"

That's because everything that's inside this conditional statement will not execute:
if(isset($_POST['submit'])){...}

Due to the fact that there isn't an input bearing the "submit" name attribute.
What you need to do is to name your submit's input:
<input name="submit" type="submit" value="Search">

Had error reporting been set to catch and display on your system, would have thrown an undefined index submit notice.
Reference:

*

*http://php.net/manual/en/function.error-reporting.php
Also make sure that $_GET['go'] is populating correctly. Error reporting will also let you know if it is or isn't.
Sidenote:
Having used an else{...} against your opening if{...} conditional statement, would have fired up.
You should also check against $_POST['Search'] for content, if it's set or not empty.


text:
Q: What is /sbin/zonename ? Where do I get it for CentOS? What is /sbin/zonename ? Where do I get it for CentOS?
I am trying to use puppet  (system administration), and it can't find this command.

A: If I'm not mistaken, zonename is used on Solaris to identify the current local zone.
I don't believe that there is a CentOs equivalent, because CentOS does not use Solaris zones.

A: You can use:
yum whatprovides '*bin/zonename'
but our Puppet installs run just fine without it.  Are you using the puppet package from EPEL?  You'll also want facter from EPEL.
Assuming CentOS 5.x (cat /etc/redhat-release) and an x86_64 architecture (uname -a), after deleting any version of Puppet you installed outside of RPM, just do:
rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-3.noarch.rpm
yum install puppet facter

And that should sort you out nicely.  If it doesn't, can you give us the exact error message you're getting, and where and when you're seeing it?


text:
Q: How can I add/destroy new objects to existing formation? In the manager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FormationsManager : MonoBehaviour
{
    public Transform squadMemeberPrefab;
    public int numberOfSquadMembers = 20;
    public int columns = 4;
    public int gaps = 10;
    public Formations formations;

    private int numofmembers;

    // Use this for initialization
    void Start()
    {
        numofmembers = numberOfSquadMembers;
        formations.Init(numberOfSquadMembers, columns, gaps);
        GenerateSquad();
    }

    // Update is called once per frame
    void Update()
    {
        if (numofmembers != numberOfSquadMembers)
        {
            GenerateSquad();
        }
    }

    private void GenerateSquad()
    {
        Transform go = squadMemeberPrefab;

        for (int i = 0; i < formations.newpositions.Count; i++)
        {
            go = Instantiate(squadMemeberPrefab);
            go.position = formations.newpositions[i];
            go.tag = "Squad Member";
            go.transform.parent = gameObject.transform;
        }
    }
}

And the Formations script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Formations : MonoBehaviour
{
    public List<Vector3> newpositions;

    private int numberOfSquadMembers;
    private int columns;
    private int gaps;
    private List<Quaternion> quaternions;

    private Vector3 FormationSquarePositionCalculation(int index)
    {
        float posX = (index % columns) * gaps;
        float posY = (index / columns) * gaps;
        return new Vector3(posX, posY);
    }

    private void FormationSquare()
    {
        newpositions = new List<Vector3>();
        quaternions = new List<Quaternion>();

        for (int i = 0; i < numberOfSquadMembers; i++)
        {
            Vector3 pos = FormationSquarePositionCalculation(i);
            Vector3 position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
            newpositions.Add(position);
        }
    }

    public void Init(int numberOfSquadMembers, int columns, int gaps)
    {
        this.numberOfSquadMembers = numberOfSquadMembers;
        this.columns = columns;
        this.gaps = gaps;
        FormationSquare();
    }
}

What I want to do is in the FormationsManager in the Update not only just calling GenerateSquad but to add the new once to the last/next position of the existing already formation.
void Update()
        {
            if (numofmembers != numberOfSquadMembers)
            {
                GenerateSquad();
            }
        }

If the value of numberOfSquadMembers is 20 first time and then I changed it to 21 add new object to the end of the formation and same if I change the value of numberOfSquadMembers for example from 20 to 19 or from 21 to 5 destroy the amount of objects from the end and keep the formation shape.

The soldiers the last line is on the right side.
So if I change the value to add more then add it to the right and if I change to less destroy from the right side. The most left line of soldiers is the first.

A: It is possible if you keep GameObject instances inside FormationsManager class, and then reuse them in GenerateSquad method.
In FormationsManager class, add and modify code as follows.
public GameObject squadMemeberPrefab;
List<GameObject> SquadMembers = new List<GameObject>();

void Update()
{
    if (numofmembers != numberOfSquadMembers)
    {
        numofmembers = numberOfSquadMembers;
        formations.Init(numberOfSquadMembers, columns, gaps);
        GenerateSquad();
    }
}

private void GenerateSquad()
{
    Transform go = squadMemeberPrefab;
    List<GameObject> newSquadMembers = new List<GameObject>();

    int i = 0;
    for (; i < formations.newpositions.Count; i++)
    {
        if (i < SquadMembers.Count)
            go = SquadMembers[i];
        else
        {
            go = Instantiate(squadMemeberPrefab);
            newSquadMembers.Add(go);
        }
        go.position = formations.newpositions[i];
        go.tag = "Squad Member";
        go.transform.parent = gameObject.transform;
    }

    for (; i < SquadMembers.Count; i++)
        Destroy(SquadMembers[i]);

    SquadMembers = newSquadMembers;
}

However, I recommend you to consider GameObject Pool (Object Pool), which can thoroughly resolve such object recycle problem. For this purpose, you can use ClientScene.RegisterSpawnHandler. Go to this Unity Documentation page and search  text "GameObject pool". You can see an example code there.


text:
Q: Не получается установить AndroidStudio Ubuntu Скачал с офф.сайт архив с адроид студией, распаковал ее в /opt/ далее по инструкции нужно перейти  в /opt/android-studio/bin/ и выполнить команду studio.sh в ответ получаю studio.sh: command not found
Пытался пропатчить ее в файле /etc/environment но этот файл доступен только для чтения.
Как можно исправить эту ситтуацию?


text:
Q: Kraken API AssetPairs I am consuming the Kraken API, and I am not able to find a good explanation to the info I have in the response.
Actually, for a given pair, I have the following info:
altname             = alternate pair name
aclass_base         = asset class of base component
base                = asset id of base component
aclass_quote        = asset class of quote component
quote               = asset id of quote component
lot                 = volume lot size
pair_decimals       = scaling decimal places for pair
lot_decimals        = scaling decimal places for volume
lot_multiplier      = amount to multiply lot volume by to get currency volume
leverage_buy        = array of leverage amounts available when buying
leverage_sell       = array of leverage amounts available when selling
fees                = fee schedule array in [volume, percent fee] tuples
fees_maker          = maker fee schedule array in [volume, percent fee] tuples (if on maker/taker)
fee_volume_currency = volume discount currency
margin_call         = margin call level
margin_stop         = stop-out/liquidation margin level

I have some questions about this payload. Thanks to everyone who will help.

*

*lot_decimals and pair_decimals: how do these apply ? I am guessing that maybe the former means that the quantity of the first currency can be represented with a maximum of lot_decimals decimals, with the latter meaning that you can represent the pair value with a maximum of pair_decimals decimals. Is this any reasonable ?

*lot_multiplier: the explanation is clear, but it's always 1. Any reason for this being there ?

*lot: is this the amount of first currency that you want to calculate in the second currency ? Example: 100 EURBTC, 100 is the lot size ?
Thanks

A: I copied this over from inside the question by @Bruno Ripa:
I had feedback from Kraken. It is:

*

*lot_decimals is the maximal precision of order size (volume), which is in base currency. pair_decimals is price precision

*lot_multiplier is unused at the moment.

*lot: pair is BTC/EUR, the volume of 100 is denominated in BTC, which is a base currency


text:
Q: Neo4j and apoc procedure At my organization IT will not permit me to download the apoc jar library. My next option is to download the source and compile. However the rub in that is that Gradle is not an approved tool nor do I have Internet access.
Is there a manual process for me to compile the source using Java? What are the other dependencies?

A: You could use a service like https://travis-ci.org for your own build. APOC uses https://travis-ci.org/neo4j-contrib/neo4j-apoc-procedures for automating tests after a git push (or for testing PRs).
In the same way you should be able to run travis on your own, maybe on a forked version of apoc that uses gradle shadowJar. Additionally you need to tweak travis config to deploy your artifact to an approriate location - see https://docs.travis-ci.com/user/deployment/ for details.
On a different notice: If my organization would not permit me to download jar artifacts, nor provide internet access to run builds, my immediate next action would be updating mv CV - just sayin'.


text:
Q: Partial Isometries: Subspaces This thread was only Q&A.
Given Hilbert spaces $\mathcal{H}$ and $\mathcal{K}$.
Consider an operator:
$$J\in\mathcal{B}(\mathcal{H},\mathcal{K}):\quad P:=J^*J$$
By a previous thread:*
$$\mathcal{R}:=\mathcal{N}^\perp:\quad\mathcal{N}:=\mathcal{N}P=\mathcal{N}J$$

Then one has:
  $$\|J\varphi\|=\|\varphi\|\quad(\varphi\in\mathcal{R})\iff P\varphi=\varphi\quad(\varphi\in\mathcal{R})$$

How can I prove this?
*See the thread: Kernel

A: Note: This answer is community wiki.
Suppose partial isometry:
$$\|J\varphi\|=\|\varphi\|\quad(\varphi\in\mathcal{R})$$
By polarization one gets:
$$\langle J\varphi,J\psi\rangle=\langle\varphi,\psi\rangle\quad(\varphi,\psi\in\mathcal{R})$$
Note that one has:
$$\mathcal{N}=\overline{\mathcal{N}}:\quad\mathcal{H}=\mathcal{N}\oplus\mathcal{R}$$
So one obtains:
$$\langle P\varphi,\chi\rangle=\langle J\varphi,J\chi\rangle=\langle\varphi,\chi\rangle\quad(\chi\in\mathcal{R})$$
$$\langle P\varphi,\chi\rangle=\langle\varphi,P\chi\rangle=0=\langle\varphi,\chi\rangle\quad(\chi\in\mathcal{N})$$
Conversely one has:
$$\|J\varphi\|^2=\langle P\varphi,\varphi\rangle=\langle\varphi,\varphi\rangle=\|\varphi\|^2\quad(\varphi\in\mathcal{R})$$
Concluding equivalence.


text:
Q: How to ensure Cloud-Init runs exactly once and once only? As far as I can see, cloud-init runs every time the config changes. Not just the very first time the system boots, but every time the provided configuration changes. This makes somewhat sense, as I guess it's hard to define the "first time" (the cloned VM already ran before being frozen and used as template, so it's never really the first time). However, I've—from time to time, quite rarely, but still—found that cloud-init re-runs on already provisioned system when they reboot.
Some steps, however, seem to screw up the setup when cloud-init is run on a fully configured system. For example, if it is run one more time after the initial setup and cloud-init sets some configuration to value X, but you had it manually overridden afterwards to Y and now cloud-init re-runs to set it back to X. Or, have the system recreate your SSH host keys.
I've thus found it quite useful to manually run:
sudo touch /etc/cloud/cloud-init.disabled

...after the initial setup to prevent it from ever running cloud-init again. (In cases, where cloud-init really is only used for an initial "clone & set IPs/hostname" kind of configurations.)
But is there any way to automate this? Like adding some parameter to the /etc/cloud/cloud.cfg that disabled itself after the next run?

A: Different cloud-init modules have different frequencies: once-per-instance and always. You can check attribute Module frequency for each module in the Modules documentation. For example, bootcmd runs on every boot but runcmd only on the first boot. The frequencies can be overridden in a cloud-config file modules lists - cloud_init_modules, cloud_config_modules and cloud_final_modules. Example override:
cloud_final_modules:
- [scripts-user, always]


text:
Q: Post to remote file without a form Without using a form, is it possible to _POST to a different file?
In my case, I want to send a string via _POST, to that file.
Thanks.

Update:
Based on a response to my post, I used this:
<?php

$ipCreation = $_SERVER['REMOTE_ADDR'];

$ipCreationCurl = curl_init(); // initiate curl
$url = "accountcreation.php"; // where you want to post data
curl_setopt($ipCreationCurl, CURLOPT_URL,$url);
curl_setopt($ipCreationCurl, CURLOPT_POST, true);  // tell curl you want to post something
curl_setopt($ipCreationCurl, CURLOPT_POSTFIELDS, $ipCreation); // define what you  want to post
curl_setopt($ipCreationCurl, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$output = curl_exec ($ipCreationCurl); // execute

curl_close ($ipCreationCurl); // close curl handle

var_dump($output); // show output
?>

This returns:
"308 Moved Permanently"  "nginx"

What's my error? Thanks.

A: You can post using curl. Here is a basic example: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
$ch = curl_init();                    // initiate curl
$url = "http://www.somesite.com/curl_example.php"; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // define what you  want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$output = curl_exec ($ch); // execute

curl_close ($ch); // close curl handle

var_dump($output); // show output


text:
Q: Logic for pairing up two sets of values in ArrayList with duplication I'm baffled on the logic of programming this. I'm sure it's extremely simple.
So, I have an ArrayList<String> with values A, B, C, D, E, F, G. Indexed in that order.
I would like to randomly select a unique letter for each but have no duplication.
The output would look similar to this.
A:B
B:A
C:E
D:F
E:C
F:D

I've tried shuffling the ArrayList then moving the index by two, but couldn't think of a way to prevent duplication, and also randomly selecting indexes then pairing them up but this only works with even numbers.

A: This should be all you need:
ArrayList<String> list = // your list containing the values

ArrayList<String> shuffled = new ArrayList<>(list);
Collections.shuffle(shuffled);

This will give you a second ArrayList<String> that  contains all the values of list in random order without duplicates.

A: class Solution
{
    public static class Pair
    {
        public String a;
        public String b;

        public Pair(String a,String b)
        {
            this.a=a;
            this.b=b;
        }

        @Override
        public boolean equals(Object o)
        {
            if((this.a.equals(o.a))&&(this.b.equals(o.b)))
            {
                return true;
            }
            if((this.b.equals(o.a))&&(this.a.equals(o.b)))
            {
                return true;
            }
            return false;
        }

        @Override
        public String toString()
        {
            return a+":"+b;
        }
    }
    public static void main(String args[])
    {
        ArrayList<String> list=new ArrayList<String>();
        ......
        .....
        ......
        //list now contains {A,B,C,D,E,F,G}
        Set<Pair> letterset=new HashSet<Pair>();
        for(int i=0;i<list.size();i++)
        {
            for(int j=0;j<list.size();j++)
            {
                Pair pair=new Pair(list.get(i),list.get(j));
                letterset.add(pair);
            }
        }
        Iterator<Pair> iter=letterset.iterator();
        while(iter.hasNext())
        {
            System.out.println(iter.next());
        }
    }
}

Here
 1. Pair: it is a class which holds two letters a and b, if two objects same set they are considered to be equal as implemented in the equals() function
 2. letterset: set has been creates to remove the  duplicate objects.
 3. nested loop created to create pairs
I hope this is what you wanted.


text:
Q: Project Euler Exercise 30 I'm trying to solve the 30th problem of project euler.
My implementation of this problem produces the good result for 4th power, but the answer for 5th power is not accepted by the site.
Can someone explains what's wrong in my code ?
Also, I'm not sure if my formula for upper bound to check is ok. If it's not, I'd appreciate to know to good solution.
Here's my code :
class P30
{
    static void Main(string[] args)
    {

        Console.WriteLine("   " + GetMatchingNumbers(4).Sum());

        Console.WriteLine("   " + GetMatchingNumbers(5).Sum());
        Console.ReadLine();
    }

    static IEnumerable<int> GetMatchingNumbers(int power)
    {
        for (int i = 2; i <(power + 1)*(Math.Pow(9,power)); i++)
        {
            var sumOfPowers = 0;
            var tempi = i;
            for (int x = 0; x < power; x++)
            {
                sumOfPowers += (int)Math.Pow( tempi % 10, power);
                tempi /= 10;
            }
            if (sumOfPowers == i)
            {
                yield return i;
                Console.WriteLine("With Power {0}, {1} matches", power, i);
            }
        }
    }
}

[Edit] I've asked if my theory is exact.

A: Your code is only summing the first 5 digits of the number it's checking.
Instead of
for (int x = 0; x < power; x++)

you should use a while loop instead
while (tempi > 0)

This produces the missing number you need. (hint it's 6 digits long.)


text:
Q: Is there any benefits of using fewer SQL database tables for similar types of content? I usually add standalone photos, photos associated with photo albums, standalone downloadable files for and media files associated to media albums to the database using different ASP.NET to insert to and update database tables as follow:
  -Articles
   --Pictures
   --Downloads
   --PhotoAlbums
   ---Photos
   --MediaAlbums
   ---MediaFiles

What I'm trying to understand is what benefits may I get if merged all these tables in one using something like "Type" or "TypeID" (for example like WordPress posts)? of course I know I will have to change my codes but need to know does it make any difference when I have few or many database tables and if this (after doing the code changes) will reflect on how the code is more organized and easier to handle?
Note:
For sure I currently use different asp.net page to add, edit and list each of the above.


text:
Q: How to render a full image of decision tree using Matplotlib I am working on a program to create a decision tree. The following method below should save an image of the tree:
def save_image(clf_, filename, feat_names, class_names, show=True):
    """Plot the tree and save to file."""
    plt.figure(dpi=200)
    tree.plot_tree(
        clf_, filled=True,
        feature_names=feat_names,
        class_names=class_names
    )
    plt.savefig(f'{filename}.png')
    if show:
        plt.show()

Expected:
Output image of full tree
Actual:

The image outputted is not what is expected. How can I trouble-shoot this problem?


text:
Q: angular 2 material table date column mix string In my date column when dates are not set or blank I want to display the string "Not Set". I also want it to sort correctly so Not Set dates are highest in value and shown last when sorted ascending. How do you guys handle this scenario in your apps. Right now I am showing some high value like 09/09/9999 just so it sorts correctly but user is confused since it should really say "Not Set".
I cannot assign strings to a date column and cannot put dates in a string column for the sorting to work right so in a tailspin right now.
Please advise.

A: You can mix types like below.
let date: String|Date
That way, you allow date to be either String or Date type.


text:
Q: TextInputLayout endIcon background color Is it possible to have background color only behind endIcon?

At the moment all I can do is only showing the custom icon.

Here the code I write to get current design.
<com.google.android.material.textfield.TextInputLayout
                android:id="@+id/date_of_birth_input_layout"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                app:endIconDrawable="@drawable/ic_calendar"
                app:endIconMode="custom"
                app:endIconTint="@color/redText"
                app:endIconTintMode="multiply"
                app:hintEnabled="false"
                app:layout_constraintTop_toBottomOf="@id/date_of_birth_title">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/date_of_birth_input"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_horizontal_margin"
                    android:layout_marginTop="6dp"
                    android:layout_marginEnd="@dimen/activity_horizontal_margin"
                    android:focusable="false"
                    android:fontFamily="@font/opensans_regular"
                    android:hint="@string/date_of_birth_hint"
                    android:imeOptions="actionNext"
                    android:inputType="text"
                    android:paddingLeft="10dp"
                    android:paddingTop="13dp"
                    android:paddingRight="10dp"
                    android:paddingBottom="13dp"
                    android:textSize="16sp" />
            </com.google.android.material.textfield.TextInputLayout>

A: Add new calendar.xml to drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:bottom="1.5dp"
    android:top="1.5dp"
    android:right="1.5dp"
    android:drawable="@drawable/background"
    android:gravity="center_horizontal|center_vertical"
    android:width="48dp"
    android:height="48dp"
    />
<item
    android:drawable="@drawable/ic_calendar"
    android:gravity="center_horizontal|center_vertical"
    android:width="36dp"
    android:height="36dp"
    />
</layer-list>

backgroud.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="@color/red"  />
<corners android:bottomRightRadius="2.5dp"
android:topRightRadius="2.5dp"/>
</shape>

and change like this:
app:endIconDrawable="@drawable/calendar"

if you get an error(vector) you should add this to build.gradle:
defaultConfig {
    vectorDrawables.useSupportLibrary = true
}


text:
Q: Mask and modify 8-byte signal from FPGA serial communication I struggle with creating a mask to only write certain bits of my data.
Currently i read 32bit data over serial. After reading i get the following information:
b'rt 00000000\n'

This has the type bytes. I assume, my 32bit from a certain register get converted to 8 bytes. However, this register has multiple fields, lets say field1 ranges from bit 0 to 4, field2 from bit 4 to 5, field3 from bit 5 to 8 and so on, so they vary in number, length and position, depending on the register. Now i want to read the information, apply a mask over a certain field, modify that field, and write the information back to my serial device. I have written additional functions to get information of the number of fields, fieldoffsets and fieldwidths.
What i have achieved so far:
    read_value = read_register_byte(s, r, regName) #output: '00000000'
    #from hex to int
    read_value = int(read_value, 16)
    #from int to 32bit-bin without prefix
    read_value = format(read_value, '032b')

    #define mask range
    maskStart = len(read_value) - (offsets[fieldNo] + widths[fieldNo]) #for field0 this results in 28
    maskStop = len(read_value) - offsets[fieldNo] #this results in 32

    #create mask template (32bit)
    mask = [0]*32
    j = 0
    #insert F for mask range
    for i in read_value:
        mask[j] = read_value[j]
        if j >= maskStart and j < maskStop:
            mask[j]='F'
        j+=1
    #to string
    tempMask=""
    for i in mask:
        tempMask += i
    mask = tempMask

read_value
Out[96]: '00000000000000000000000000000000'

mask
Out[97]: '0000000000000000000000000000FFFF'

What im trying to do is to allow only modification of those bits marked with F. Im sure this is very bad practise, however it should work if i could only achieve the following steps: manipulate read_value with my mask, convert my data back to that 8-byte format and write to my serial-device.
Edit:
Field = namedtuple("Field", ["pos_lsb", "width"])
REG_WIDTH = 32 #r.width
REG_HEX_DIGITS = REG_WIDTH // 4

def create_mask(pos_lsb, width):
    mask = ((1 << width)-1) << pos_lsb
    return mask

def get_field(reg_value, field):
    mask = create_mask(*field)
    field_value = (reg_value & mask) >> field.pos_lsb
    return field_value

def set_field(reg_value, field, new_value):
    mask = create_mask(*field)
    reg_value = (reg_value & ~mask) | (new_value << field.pos_lsb)
    return reg_value

def value_from_string(reg_value_string):
    return int(reg_value_string, 16)

def value_to_string(reg_value):
    return f"{reg_value:0{REG_HEX_DIGITS}X}"

def write_field(s, r, regName, fieldNo, data):
    """ Writes to a single field of a Trixel register """
    """ debug block """
    # s = open_serial_port()
    # r = Registermap()
    # regName = 'tcm_control'
    # fieldNo = 0 #1st field
    # data = 5
    """ end of debug block """

    regAddress = r.get_register_address(regName)
    fields = r.get_register(regName, 'fields')
    offsets = r.get_register(regName, 'offsets')
    widths = r.get_register(regName, 'widths')

    if fieldNo+1 > fields:
        print('fieldNo out of range (max fields: ' + str(fields) + '). Aborting..')
        return 0

    fieldStart = r.baseAddress + regAddress + offsets[fieldNo]
    addr = r.baseAddress + regAddress
    register_value_string = read_register_byte(s, r, regName)
    field = Field(pos_lsb=offsets[fieldNo], width=widths[fieldNo])
    new_field_value = data

    # Update field
    print("Register: " + str(regName) + ", fieldNo: " + str(fieldNo+1) + "(" + str(fieldNo) + ")" + ", offset (hex): " + hex(fieldStart))
    print("Fieldname: " + str(r.get_register(regName,'descriptions')[fieldNo]))
    print(f"Original register value: {register_value_string}")
    reg_val = value_from_string(register_value_string)
    field_value = get_field(reg_val, field)
    print(f"Original field value: {field_value} (0x{field_value:x} in hex)")
    print(f"Setting field to {new_field_value} (0x{new_field_value:x} in hex)")
    reg_val = set_field(reg_val, field, new_field_value)
    field_value = get_field(reg_val, field)
    print(f"New field value: {field_value} (0x{field_value:x} in hex)")
    new_reg_val_string = value_to_string(reg_val)
    print(f"New register value to write to FPGA: {new_reg_val_string}")

    #write to FPGA
    cmd = ("mwr {:08X}".format(addr) + " " + new_reg_val_string + " \n").encode()
    message = s.write(cmd)

    if message != len(cmd):
        print('Error in Write! Bytes expected: ' + str(len(cmd)) + ', written: ' + str(message) + ', cmd: ' + str(cmd))
    elif message == len(cmd):
        print('Write to register ' + str(hex(addr)) + ' OK.')

Working example:
write_field(s, r, 'tcm_control', 3, 1)
Register: tcm_control, fieldNo: 4(3), offset (hex): 0x50000406
Fieldname: Should be released after configuring all TCM registers over AXI
Original register value: 00000071
Original field value: 1 (0x1 in hex)
Setting field to 1 (0x1 in hex)
New field value: 1 (0x1 in hex)
New register value to write to FPGA: 00000071
Write to register 0x50000400 OK.

Failing example:
write_field(s, r, 'tcm_control', 3, 2)
Register: tcm_control, fieldNo: 4(3), offset (hex): 0x50000406
Fieldname: Should be released after configuring all TCM registers over AXI
Original register value: 00000071
Original field value: 1 (0x1 in hex)
Setting field to 2 (0x2 in hex)
New field value: 0 (0x0 in hex)
New register value to write to FPGA: 000000B1
Write to register 0x50000400 OK.

read_register_byte(s, r, 'tcm_control')
Out[15]: '00000031'

A: I think you are approaching this the wrong way. Please have a look at this (not very commented) code and see if that is what you actually wants:
from collections import namedtuple

REG_WIDTH = 32
REG_HEX_DIGITS = REG_WIDTH // 4

Field = namedtuple("Field", ["pos_lsb", "width"])

def create_mask(pos_lsb, width):
    mask = ((1 << width)-1) << pos_lsb
    return mask

def get_field(reg_value, field):
    mask = create_mask(*field)
    field_value = (reg_value & mask) >> field.pos_lsb
    return field_value

def set_field(reg_value, field, new_value):
    mask = create_mask(*field)
    reg_value = (reg_value & ~mask) | (new_value << field.pos_lsb)
    return reg_value

def value_from_string(reg_value_string):
    return int(reg_value_string, 16)

def value_to_string(reg_value):
    return f"{reg_value:0{REG_HEX_DIGITS}X}"

register_value_string = "0F00F0FF"
field1 = Field(pos_lsb=3, width=5)
new_field_value = 0x12

# Update field1.
print(f"Original register value: {register_value_string}")
reg_val = value_from_string(register_value_string)
field_value = get_field(reg_val, field1)
print(f"Original field value: {field_value} (0x{field_value:x} in hex)")
print(f"Setting field to {new_field_value} (0x{new_field_value:x} in hex)")
reg_val = set_field(reg_val, field1, new_field_value)
field_value = get_field(reg_val, field1)
print(f"New field value: {field_value} (0x{field_value:x} in hex)")
new_reg_val_string = value_to_string(reg_val)
print(f"New register value to write to FPGA: {new_reg_val_string}")

Output:
Original register value: 0F00F0FF
Original field value: 31 (0x1f in hex)
Setting field to 18 (0x12 in hex)
New field value: 18 (0x12 in hex)
New register value to write to FPGA: 0F00F097

I believe this is more in line with what you would want. If you want me to explain it further, please let me know.


text:
Q: Put array values in `usecallback deps` I have created a member registration function.
I want to pass the value of formState.values from useCallback Hook to axios.post.
However, when I put formState.values in useCallback dependencies in the handleSubmit function, a ',' expected. type error occurs.
What should I do? You need to put the values array values in formState as axios argument.
Can't you put formState.values in deps, axios argument values like this?
How do I pass the value value as an argument?
const [formState, setFormState] = useState<formState>({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
});

const handleSubmit = useCallback((event: FormEvent) => {
    event.preventDefault();

    axios.post<Login>(
        'http://www.minsususu.com/login',
        {formState.values},
        {
            withCredentials: true,
        },
    )
    .then(response => {
        const { accessToken } = response.data;
        axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
        router.history.push('/');
    })
    .catch(error => {
        console.log(error);
    });

}, [formState.values])

A: would say the problem is in the post call:
axios.post<Login>(
  'http://www.minsususu.com/login',
  formState.values, // or {values: formState.values}
  { withCredentials: true },
)


text:
Q: AMPScript to create Campaign Member Using AMPscript, I need to check if the form submission is an existing SF Campaign Member. If not, I need to create a new SF campaign member record using AMPscript.
%%[
var @id, @row, @campaignId, @emailParam, @SfCampaign

SET @id = Id
SET @campaignId = '7012M000001JHyA'
SET @emailParam = RequestParameter('EmailAddress')

IF NOT EMPTY(@emailParam) THEN
SET @SfCampaign = RetrieveSalesforceObjects('CampaignMember', 'Id', 'Email', '=', @emailParam)

IF RowCount(@SfCampaign) > 0 THEN
      SET @row = Row(@SfCampaign, 1)
      SET @id = Field(@row, 'Id')

 ELSE

CreateSalesforceObject(
'CampaignMember', 3,
'CampaignId',@campaignId,
'ContactId',@contactId,
'Status','Sent'
)
EndIF
]%%

A: You're missing an ENDIF at the after your CreateSalesforceObject function call.  Secondly, looks like you're overwriting the value of @id.  Seems like the second instance should be @contactID.
Regarding my comment about outputting the values before doing the operations -- here's what I mean:
%%[

var @id, @row, @campaignId, @emailParam, @SfCampaign

SET @id = AttributeValue("Id")
SET @campaignId = '7012M000001JHyA'
SET @emailParam = RequestParameter('EmailAddress')

output(concat("
id: ", @id))
output(concat("
campaignId: ", @campaignId))
output(concat("
emailParam: ", @emailParam))

IF NOT EMPTY(@emailParam) THEN

    SET @SfCampaign = RetrieveSalesforceObjects('CampaignMember', 'Id', 'Email', '=', @emailParam)

    output(concat("
RowCount(@SfCampaign): ", RowCount(@SfCampaign)))

    IF RowCount(@SfCampaign) > 0 THEN

          SET @row = Row(@SfCampaign, 1)
          SET @contactId = Field(@row, 'Id')

          output(concat("
@contactId: ", @contactId))

    ELSE

    /*
        CreateSalesforceObject(
        'CampaignMember', 3,
        'CampaignId',@campaignId,
        'ContactId',@contactId,
        'Status','Sent'
        )
    */

    ENDIF

EndIF

]%%

Once you've validated that you're getting the values you intend, uncomment the code and move on to the next part.  It's just the process of elimination instead of trying to make it all work at once.


text:
Q: How can I compare the columns elements in 2d array? I have created a 2d array, so lets say as I did in the code below the array elements shows like this:
3 4
8 2
I want to compare the" ROWS"  and get the minimum number, like what I do with 3 & 4, I get 3 is the min number and with the second row between 8 & 2, I get 2 is the min number.
My problem is that I can't get it to compare the columns as in 3 & 8 to get the max out between them, and 4 & 2.
In the code it just outputs the max number in the rows it still comparing the "ROWS"
P.S sorry for the long explanation. I just had to clarify it .
int main()
{
    int d;
    int max;
    //array dimention
    cout << "Enter the array dimention :- " << endl;
    cin >> d;
    //max_min for the final maximum numbers
    int max_num[d];
    //the 2d array
    int arr[d][d];
    // array input
    cout << "please enter the array elements :- " << endl;
    for (int i = 0; i < d; i++) {
        for (int j = 0; j < d; j++) {
            cin >> arr[i][j];
        }
    }
    //array output
    cout << "the array elements you enterd :-" << endl;
    for (int i = 0; i < d; i++) {
        for (int j = 0; j < d; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    //the max numbers
    for (int i = 0; i < d; i++) {
        max = arr[0][i];
        for (int j = 0; j < d; j++) {
            if (max < arr[j][i]) {
                max = arr[j][i];
            }
        }
        max_num[i] = max;
    }
    cout << "the maximum elements in array  :-" << endl;
    for (int i = 0; i < d; i++) {
        cout << max_num[i] << endl;
    }
}