text:
Q: Location of the mdf file of the database I have a database Project. My problem is where can I find the .mdf and _log.ldf of my database so that I can transfer my database to another user. I am using Microsoft SQL Server 2008 Management Studio

My Ssms.exe is stored in this path
C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe

A: There are few ways to determine the location of the SQL Server mdf file(s) and associated log file(s).

*

*Open Enterprise Manager, right click on the database you are interested in and select properties. Select the Files section and scroll across to the Path and FileName columns.

*Open a query window and run the relevant query below and view the Physical_Name column.
SQL 2005 or later:
SELECT * FROM sys.database_files

SQL 2000:
SELECT * FROM dbo.sysfiles

*Open a query window and run sp_helpfile and view the FileName column.

Of course, as these files are in use by SQL Server you should not attempt to copy the files to a different location.
The best method is to perform a backup from within Enterprise Manager by right clicking on the database you are interested in and selecting Tasks -> Backup.
Alternatively you can detach your database, copy the files and then attach.
A third alternative once you have a copy of the database running elsewhere, is to set up log shipping or replication.

A: The best and easy way to find the (.mdf & .ldf) file , size and growth rate, etc. details of the particular database through below mention TSQL Query.
exec sp_helpdb @dbname='Databasename';
Go

A: SQL 2005 onwards: Following query will give you list of all databases and associated files:
SELECT sd.NAME
,smf.NAME
,smf.type_desc
,(CAST(smf.size AS FLOAT) * 8096) AS SizeBytes
,(CAST(smf.size AS FLOAT) * 8096) / (1024) AS SizeKB
,(CAST(smf.size AS FLOAT) * 8096) / (1024 * 1024) AS SizeMB
,(CAST(smf.size AS FLOAT) * 8096) / (1024 * 1024 * 1024) AS SizeGB
,smf.physical_name
,sd.log_reuse_wait_desc
,sd.recovery_model_desc
,*
FROM sys.databases sd
INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id
WHERE
smf.type_desc IN (
    'ROWS'
    ,'LOG'
    )
ORDER BY SizeGB DESC

A: You were in the right dialog, but wrong tab
Open the Files tab, the path is shown for all database files

A: The path for .mdf and .ldf will be
Root drive(where Os is installed )->
Programfiles(for 64bit applications) or
programfiles(x86) for 32 but applications->
Microsoft SQL Server->
MSSQL11.SQL2012->
MSSQL->
DATA

MSSQL11.SQL2012
This is for users having using SQL 2012...
So you may easily recognize what's the folder name for you as you are using SQL 2008 under "Microsoft SQL Serve" folder in the mentioned path


text:
Q: Determine if these spaces are connected, Hausdorff, or compact.
Let $X = [0,1]/(0,1)$ and let $\pi: [0,1] \rightarrow X$ be the quotient map. Answer the following questions, proving your assertions:
a) Is $X$ contractible?

We need $s:X \rightarrow \{pt\}$ and $t: \{pt\} \rightarrow X$ with $s \circ t \simeq id_{\{pt\}}$ and $t \circ s \simeq id_{X}$.
$s$ is the obvious map. Define $t$ with $pt \mapsto 0$. We have $s \circ t = id_{\{pt\}}$. Now define $H(x,t) = (t \circ s)(1-t) + id_{X}(t)$, which is a homotopy from $t \circ s$ to $id_{X}$. So Yes, $X$ is contractible.

b) Are $\pi(0)$ and $\pi(1/2)$  dense in $X$?

$\{0\}$ is closed in $X$ because $\pi^{-1}(\{0\})$ is closed in $[0,1]$. So $\overline{\{0\}} \not = X \implies \pi(0)$ is not dense in $X$.
Since $\overline{\pi(1/2)}=\overline{(0,1)} = [0,1]$, $\pi(1/2)$ must be dense in $X$.

c) Consider the complement of $\pi(0)$ in $X$. Is it Hausdorff? Is it connected?

No it's not Hausdorff. For $[1/2]$ and $1$, we need to find $U$ and $V$ open and disjoint in $X$ with $[1/2] \in U$ and $1 \in V$. But we need $V \subseteq X - (0,1)$. So $V = \{1\}$, which is closed (since $\pi(\{1\})$ is not open in $[0,1]$).
It is connected. Suppose we have $X=A \cup B$ for $A,B$ open, nonempty, and disjoint in $X$. Since there are only two elements, the only possibilities for $A$ and $B$ are $(0,1)$ and $\{1\}$. But $\pi(\{1\})$ is not open so, so $\{1\}$ cannot be open in $X$. By the definition of the subspace topology, it is not open in $X - \pi(0)$ either.

d) Consider the complement of $\pi([1/2])$ in $X$. Is it Hausdorff? Is it connected?

Yes it is Hausdorff. Since $X - \{0\}$ is open in $X$, $(X -\{0\}) \cap (X - \pi([1/2]) = \{1\}$ is open in the subspace topology. Similarly for $\{0\}$. Hence the subspace is Hausdorff.
It's not connected since $X - \pi([1/2]) = \{0\} \cup \{1\}$.
Are my answers correct?

A: As I see, your answers are correct. There are minor issues with your definition of $H$. One thing is that $t$ stands there both for name of a function and a variable. Another is that you pass $t ∈ [0, 1]$ to $id_X$ but $X$ is not $[0, 1]$, there should be composition with the projection. But the idea is clear: you take the standard homotopy for contraction of $[0, 1]$ and show that it factors through $π$.
For other questions you may also forget $[0, 1]$ and see that $X$ is just three point space with a certain topology which can be easily visualized so the answers are clear.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arithmetic/calculations with lengths I want to define a new command to add vertical "padding" before and after the content of a table cell. I'm stealing the idea of using rules/struts from the accepted answer to this question.
My concept is something like
\newcommand{\vpad}[2]{
   \rule{0pt}{\baselineskip + #1}              % top padding
   \rule[-0.4*\baselineskip - #2]{0pt}{0pt}}   % bottom padding

I know that there are many cases where this won't work, but that's not the issue, at present. My question is about the arithmetic expressions involving \baselineskip and the command arguments. Clearly I don't have the syntax correct. So, what is the right syntax for this sort of thing?
Edit
I'm starting to think that things like 0.4*baselineskip - #2 are not allowed. If so, maybe I have to settle for '-4pt - #2'. Is negation allowed?

A: There are several ways to calculate equations in (La)TeX. (Therefore I created the adjcalc package as part of the adjustbox bundle so that users can select which way they want it.).
You can either 1) use eTeX macros like \dimexpr, \glueexpr, 2) the calc package or 3) the pgfmath package.
The simplest thing is to use \dimexpr ... \relax. It expands to the calculation result. The \relax can be used as an endmarker which is also removed in the expansion. This requires eTeX (extended TeX) which is part of all main TeX distributions.
\newcommand{\vpad}[2]{
   \rule{0pt}{\dimexpr\baselineskip + #1\relax}              % top padding
   \rule[\dimexpr-0.4*\baselineskip - #2\relax]{0pt}{0pt}}   % bottom padding


text:
Q: How to display data from API inside a bootstrap collapse/modal? I have a school project about API, and I have problems displaying specific data inside a bootstrap collapse.
I have a school project, where I take data about coins from API server and present it. Every coin is presented in a different div and within that div there is a button.  This button is "More Info", and should display more info about that coin, from a link with a specific id, similar to the coin. I managed to present the data from the API server, but couldn't make the button work.
This is the link for the "More Info" button: https://api.coingecko.com/api/v3/coins/{id}
This is the html:

        Cryptonite

                <button type="button" class="btn btn-link" id="home-btn" onClick="selectTab" name="home">Home</button>
                <button type="button" class="btn btn-link" id="live-btn" onClick="selectTab" name="live">Live Reports</button>
                <button type="button" class="btn btn-link" id="about-btn" onClick="selectTab" name="about">About</button>

                <input type="search" placeholder="Search" aria-label="Search through site content"/> <button type="button" class="btn btn-link" id="src-btn" name="src">Search</button>

This is the script:
//This is the function to call the data from the API server
function callCoins() {
$.ajax({
    url: "https://api.coingecko.com/api/v3/coins/list",
    dataType: "json",
    success: function(data){
        console.log(data);
        for(let i=0;i<100;i++){
            $(".coins").append(`

${data[i].symbol}

${data[i].name}

                        <button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}">More Info</button>

example

                     <input type="checkbox" class="custom-control-input" id="b${data[i].id}">

            `)

        }
    }
})
}

//This is the function for 'More Info'
function moreInfo() {
    $.ajax({
        url: "https://api.coingecko.com/api/v3/coins/{id}",
        dataType: "json",
        success: function(data){
            $(".collapse").append(`

${data.image.thumb}

            `)
        }
    })
}

When I click on "More Info", it should display data from a link with the coin specific id.
Here is a Demo File

A: Seems like you are not invoking the moreInfo function on click of the button. so your More Info HTML Button has to be like this.
<button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}"  onClick="moreInfo('${data[i].id}')">More Info</button>

and the moreInfo() function to be like this
function moreInfo(id) {  /* change 1 - added id parameter*/
    $.ajax({
        url: "https://api.coingecko.com/api/v3/coins/"+id, /* change 2 - added the id parameter to the api call */
        dataType: "json",
        success: function(data){
            $(".collapse").append(`

${data.image.thumb}

            `)
        }
    })
}

Hope this helps. And to Make it appear as an image you have add an image tag inside the p tag and bind the image url into the src attribute.


text:
Q: How to persist checkbox checked state in Acumatica PXGrid? I have "selected" checkbox column in PXGrid, when i checked it then page postback and checked state does not lost, But when i click on Custom Action button then checked checkbox, unchecked, what should i do to persist checkbox state?
In Action button click, I am opening a Dialogbox, here all checkbox unchecked, PrimaryView and dialogbox data-member are different.
what should i do to persist checkbox state?

A: The Selected identifier has a special meaning in processing screens. Acumatica framework applies different behaviors to fields which are named Selected. For processing screen it is required to have a field named Selected. Outside this scenario you should avoid naming fields Selected.
Make sure field is decorated with PXDBBool attribute instead of PXBool attribute. Only fields with PXDB prefix are persisted to database.
Change the field name in database and in the DAC from Selected to something else like IsChecked.
public abstract class isChecked : PX.Data.BQL.BqlBool.Field<isChecked> { }

[PXDBBool]
[PXUIField(DisplayName="Selected")]
public virtual Boolean? IsChecked
{
    get;
    set;
}

A: yourviewname.Cache.Persist(PXDBOperation.Update);


text:
Q: Does anyone know where to find the datasheet for an Electrocraft Model E19-2 motor? More details from the motor casing:

*

*Electrocraft

*Model: E19-2

*Serial: A01314

*Part #: 0643-08-013

It looks like it was made by Robbins Myers Motor & Control Systems Division.
In case anyone is wondering, this motor comes from inside of a PUMA 560 robotic arm.
It also has an encoder/potentiometer attached to it which I am interested in getting datasheets for as well:

*

*esoline (? it's actually kind of hard to read the first character on the label) encoder.

*Type: P.4201717

*S. No.: 70754086

*7223C30903

Any help in finding datasheets, or at the very least pinouts for either of these would be much appreciated.

A: http://www.cnczone.com/forums/servo_motors_drives/9435-techical_specification_electrocraft_0643-08-013_a.html

I have the catalogue specs on
  0643-31-011 & 0643-32-011 models,
  these were the 0643 off-the-shelf
  models and I believe the other numbers
  are special order and may have been
  just different mounts or shaft size
  etc.
  Al
I will post them here in case someone
  has the same question in the future.
  Of the two models, one show the specs
  in oz-in and the other in lb-in, but
  converted they appear to be close to
  the same.
  0643-33-004
  continuous stall 155 oz-in
  pk torque 720 oz-in
  max terminal voltage 60
  max speed 4800 rpm
  inertia .0304 oz-in-sec^
  Kt 16.8 oz-in/amp
  Ke 12.4 v/krpm
  max pulse current 43 amp
  Inductance .5mH
0643-32-004
  continuous stall 9.7 lb-in
  pk torque 45 lb-in
  max terminal voltage 60
  max speed 3700 rpm
  inertia .0019 lb-in-sec^
  Kt 1.34 lb-in/amp
  Ke 15.9 v/krpm
  max pulse current 33 amp
  Inductance .8mH
  Good luck
  Al


text:
Q: Cannot do php upgrade because dependencies error while running sudo apt-get upgrade, I stumbled this problem:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 php5.6-fpm : Depends: php5.6-common (= 5.6.26-2+deb.sury.org~precise+1) but 5.6.28-1+deb.sury.org~precise+1 is installed
E: Unmet dependencies. Try using -f.
then after I do the suggestion by running sudo apt-get -f install, the new error message shows:
dpkg: dependency problems prevent configuration of php5.6-fpm:
 php5.6-fpm depends on php5.6-common (= 5.6.26-2+deb.sury.org~precise+1); however:
  Version of php5.6-common on system is 5.6.28-1+deb.sury.org~precise+1.
dpkg: error processing php5.6-fpm (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                Errors were encountered while processing:
 php5.6-fpm
E: Sub-process /usr/bin/dpkg returned an error code (1)
I could not remove php5.6-fpm either because it also return Sub-process /usr/bin/dpkg returned an error code (1)
It seems the php5.6-fpm has different dependencies but cannot upgraded or removed because there is a configuration missing

A: A way to meet all required dependencies, is to install the lamp package by running the command below (including the ^ symbol)

sudo apt-get install lamp-server^


text:
Q: What is the expected behaviour for multiple set-returning functions in SELECT clause? I'm trying to get a "cross join" with the result of two set-returning functions, but in some cases I don't get the "cross join", see example
Behaviour 1: When set lenghts are the same, it matches item by item from each set

postgres=# SELECT generate_series(1,3), generate_series(5,7) order by 1,2;
 generate_series | generate_series
-----------------+-----------------
               1 |               5
               2 |               6
               3 |               7
(3 rows)

Behaviour 2: When set lenghts are different, it "cross join"s the sets

postgres=# SELECT generate_series(1,2), generate_series(5,7) order by 1,2;
 generate_series | generate_series
-----------------+-----------------
               1 |               5
               1 |               6
               1 |               7
               2 |               5
               2 |               6
               2 |               7
(6 rows)

I think I'm not understanding something here, can someone explain the expeted behaviour?
Another example, even weirder:

postgres=# SELECT generate_series(1,2) x, generate_series(1,4) y order by x,y;
 x | y
---+---
 1 | 1
 1 | 3
 2 | 2
 2 | 4
(4 rows)

I am looking for an answer to the question in the title, ideally with link(s) to documentation.

A: Postgres 10 or newer
pads with null values for smaller set(s). Demo with generate_series():
SELECT generate_series( 1,  2) AS row2
     , generate_series(11, 13) AS row3
     , generate_series(21, 24) AS row4;

row2 | row3 | row4
-----+------+-----
   1 |   11 |   21
   2 |   12 |   22
null |   13 |   23
null | null |   24

dbfiddle here
The manual for Postgres 10:

If there is more than one set-returning function in the query's select
list, the behavior is similar to what you get from putting the
functions into a single LATERAL ROWS FROM( ... ) FROM-clause item. For
each row from the underlying query, there is an output row using the
first result from each function, then an output row using the second
result, and so on. If some of the set-returning functions produce
fewer outputs than others, null values are substituted for the missing
data, so that the total number of rows emitted for one underlying row
is the same as for the set-returning function that produced the most
outputs. Thus the set-returning functions run "in lockstep" until they
are all exhausted, and then execution continues with the next
underlying row.

This ends the traditionally odd behavior.
Some other details changed with this rewrite. The release notes:

*

*Change the implementation of set-returning functions appearing in a query's SELECT list (Andres Freund)
Set-returning functions are now evaluated before evaluation of scalar
expressions in the SELECT list, much as though they had been placed
in a LATERAL FROM-clause item. This allows saner semantics for cases
where multiple set-returning functions are present. If they return
different numbers of rows, the shorter results are extended to match
the longest result by adding nulls. Previously the results were cycled
until they all terminated at the same time, producing a number of rows
equal to the least common multiple of the functions' periods. In
addition, set-returning functions are now disallowed within CASE and
COALESCE constructs. For more information see Section 37.4.8.

Bold emphasis mine.
Postgres 9.6 or older
The number of result rows (somewhat surprisingly!) is the lowest common multiple of all sets in the same SELECT list. (Only acts like a CROSS JOIN if there is no common divisor to all set-sizes!) Demo:
SELECT generate_series( 1,  2) AS row2
     , generate_series(11, 13) AS row3
     , generate_series(21, 24) AS row4;

row2 | row3 | row4
-----+------+-----
   1 |   11 |   21
   2 |   12 |   22
   1 |   13 |   23
   2 |   11 |   24
   1 |   12 |   21
   2 |   13 |   22
   1 |   11 |   23
   2 |   12 |   24
   1 |   13 |   21
   2 |   11 |   22
   1 |   12 |   23
   2 |   13 |   24

dbfiddle here
Documented in manual for Postgres 9.6 the chapter SQL Functions Returning Sets, along with the recommendation to avoid it:

Note: The key problem with using set-returning functions in the select
list, rather than the FROM clause, is that putting more than one
set-returning function in the same select list does not behave very
sensibly. (What you actually get if you do so is a number of output
rows equal to the least common multiple of the numbers of rows
produced by each set-returning function.) The LATERAL syntax produces
less surprising results when calling multiple set-returning functions,
and should usually be used instead.

Bold emphasis mine.
A single set-returning function is OK (but still cleaner in the FROM list), but multiple in the same SELECT list is discouraged now. This was a useful feature before we had LATERAL joins. Now it's merely historical ballast.
Related:

*

*Parallel unnest() and sort order in PostgreSQL

*Unnest multiple arrays in parallel

*What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?

A: I cannot find any documentation for this.  However, I can describe the behavior that I observe.
The set generating functions each return a finite number of rows.  Postgres seems to run the set generating functions until all of them are on their last row -- or, more likely stop when all are back to their first rows.   Technically, this would be the least common multiple (LCM) of the series lengths.
I'm not sure why this is the case.  And, as I say in a comment, I think it is better to generally put the functions in the from clause.

A: There is the only note about the issue in the documentation. I'm not sure whether this explains the described behavior or not. Perhaps more important is that such function usage is deprecated:

Currently, functions returning sets can also be called in the select list of a query. For each row that the query generates by itself, the function returning set is invoked, and an output row is generated for each element of the function's result set. Note, however, that this capability is deprecated and might be removed in future releases.


text:
Q: Corruption of the heap during memory allocation I am trying to read from a text file into a linked list of structs in C.
In the program I have a struct definition in a .h file as such:
typedef struct SystemDetails *SyDetails;

The struct itself is defined in a .cpp file as such:
struct SystemDetails //stores system users data from the list
{
char fname[20],lname[20],password[7],email[30],SQuestion[10],SAnswer[10];
long unsigned int id;
int memory_alloc, request_ind,delete_ind;
SystemDetails *next;
};

The function that deals with the file and the data transfer is:
SyDetails System_Data()
{
FILE *fp=NULL;
SyDetails head=NULL,curr=NULL;
char fname[20],lname[20],password[7],email[30],SQuestion[10],SAnswer[10];
long unsigned int id=0;
int memory_alloc=0,request_ind=0,delete_ind=0;
fp=fopen("SystemList.txt","r+");
if(fp==NULL)//if file doesn't exist on the pc open a new file
{

    printf("error,file cant open\n");
    exit(-1);

}
else
{

    while(fscanf(fp, "%s %s %d %s %s %s %s %d %d %d", &fname,&lname,&id,&email,&password,&SQuestion,&SAnswer,&memory_alloc,&request_ind,&delete_ind)!=EOF)
    {
        if(head==NULL)
        {
            head=(SyDetails) malloc(sizeof (SyDetails));
            curr=head;
        }
        else
        {

            curr->next=(SyDetails) malloc(sizeof (SyDetails));
            curr=curr->next;
        }
        strncpy(curr->fname, fname, 20);
        strncpy(curr->lname, lname, 20);
        curr->id=id;
        strncpy(curr->email, email, 30);
        strncpy(curr->password, password, 10);
        strncpy(curr->SQuestion, SQuestion, 10);
        strncpy(curr->SAnswer, SAnswer, 10);
        curr->memory_alloc=memory_alloc;
        curr->request_ind=request_ind;
        curr->delete_ind=delete_ind;
        curr->next=NULL;

    }

}
return head;

}

Anyway the text file has 3 records , the first row works when head==NULL but at the second time when the function gets to the else to malloc the next node of the linked list it crashes at the malloc line and I get an error that says:
"Windows has triggered a breakpoint in final-project.exe.

This may be due to a corruption of the heap, which indicates a bug in final-project.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while final-project.exe has focus.
The output window may have more diagnostic information."
My guess is that there is something with the way I defined the pointers in the function.
I would appriciate any help , thanks!

A: The line
head=(SyDetails) malloc(sizeof (SyDetails));

is wrong in two ways. First, the reason why you are corrupting the memory: SyDetails is a pointer, so this will allocate only sizeof(pointer) bytes which is less than the necessary sizeof(struct SystemDetails) - for which you should change it. Even better, change it to sizeof(*head) to be safe in case the type of head ever changes.
The second thing is that in C, you should not cast the return value of malloc().
All in all:
head  = malloc(sizeof(*head));

is what you really want.

A: One problem I've noticed is the following:
head=(SyDetails) malloc(sizeof (SyDetails));
....
curr->next=(SyDetails) malloc(sizeof (SyDetails));

It should be:
head=(SyDetails) malloc(sizeof (struct SystemDetails));
....
curr->next=(SyDetails) malloc(sizeof (struct SystemDetails));

because you want to allocated the number of bytes occupied by your structure and not by a pointer to it (SyDetails).


text:
Q: Tensorflow Model runs fine as a directory, but throws an error when used as an .h5 file: "...values to be kept must have known shape...." Interesting issue that I can't quite wrap my head around.
We have a working Python project using Tensorflow to create and then use a model. This works great when we output the model as a directory, but if we output the model as an .h5 file, we run into the following error whenever we try to use the model:
ValueError: All `axis` values to be kept must have known shape. Got axis: (-1,), input shape: [None, None], with unknown axis at index: 1

Here is how we were and how we are currently saving the model:
# this technique works (saves model to a directory)
tf.keras.models.save_model(
dnn_model, filepath='./true_overall', overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True )

#this saves the file, but throws an error when the file is used
tf.keras.models.save_model(
dnn_model, filepath='./true_overall.h5', overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True )

This is how we're importing the model for use:
dnn_model = tf.keras.models.load_model('./neural_network/true_overall.) #works
dnn_model = tf.keras.models.load_model('./neural_network/true_overall.h5') #doesn't work

What would cause a model to work when saved as a directory but have issues when saved as an h5 file?


text:
Q: How to fix resizing between Graphics and Plot when using Inset I have the following code:
g[u_,p_] = Graphics{
                    Circle[{2 Sqrt[u], u}, u],
                    Circle[{-2 Sqrt[u], u}, u],
                    Point[{2 Sqrt[u], u}],
                    Point[{-2 Sqrt[u], u}],
                    Inset[p,{0,1},{0,0},{15,10}]
                   }

and I want to draw the parabola that goes through the centers of both of these circles, for every $u \neq 0$ with its value in $0$ equal to $1$. We can see that, if we let $y$ to be the needed curve, that $y(2\sqrt{u}) = u, \forall u \neq 0$ and $y(0) = 1$. By making $u:= u^2$, we see that $y(2u) = u^2$, so by making again $u := u/2$ we see that $y(u) = u^2/4,$ and we also need to subtract one because we map $(0,1)$ to $(0,0)$.
However, if I try to plot this by saying
f[u_] = g[u, Plot[u^2/4 - 1,{u,-100,100}]

I don't really get what I want. I suspect this is because of the resizing done by Graphics and Plot. I have tried using PlotRange and PlotRangeClipping, but nothing works.
Is there any way I can do this or do I need another method to draw this curve? As a matter of fact, can it be done without Inset?

A: A couple of changes:

*

*do not use Inset to combine the two plots; use Show instead, which will plot both on the same coordinate system;

*I think that there may have been a small error in your calculation; it seems to work if I plot $u^2/4$ instead of $u^2/4-1$;

*finally, a practical consideration: you will want to reduce the range over which you plot your parabola, or your circles become too small (here I used $-5,5$).

With those changes:
ClearAll[g]
g[u_] := Graphics@{
    Circle[{2 Sqrt[u], u}, u],
    Circle[{-2 Sqrt[u], u}, u],
    Point[{2 Sqrt[u], u}],
    Point[{-2 Sqrt[u], u}]
  };

Show[
  Plot[u^2/4, {u, -5, 5}],
  g[0.7]
]

... and just for fun:
ClearAll[gcombo]
gcombo[u_] := Show[
  Plot[x^2/4, {x, -5, 5}],
  Graphics@
    Through[{Point, Map[Circle[#, u] &]}[{# Sqrt[u], u} & /@ {2, -2}]]
 ]

Animate[
  gcombo[u],
  {u, 0, 2},
  AnimationDirection -> ForwardBackward,
  AnimationRunning -> False
]


text:
Q: Restore file modification time from backup Due to some careless copy/zip/unzip operations, all files in a folder and its subfolders had their last-modified time updated.
I would like to restore the correct file timestamp from an older backup.
Some files were actually modified, created and deleted since the backup. I would like to leave those files untouched, and only reset the date for the files that are bitwise identical.
How can I do that? Maybe with some clever application of robocopy? It is a windows machine, but git-bash is available as well.

A: I guess it would be something like this:
robocopy "Source" "Destiny" /copy:T /Timfix /e


text:
Q: Are the outputs of /proc/meminfo, /proc/cpuinfo etc always in English? I am writing code that relies on the output of /proc/meminfo, /proc/cpuinfo etc. Are the file contents always in English? For example, will MemTotal in /proc/meminfo always be MemTotal in all locales?

A: proc virtual filesystem has two part:
1. /proc/[PID]/blahblah
2. /proc/* #versus of no.1 such as cpuinfo meminfo partitions and so on.

May be you will be see another locale in content of /proc/[PID]/files , because some of them such as environ fill up by user, so may be you can see another locale.But in part no2 or some of part no1 never you don't see another loccale.Also they aren't translatable.

A: Yes, usually that is the case, as those messages are provided by the kernel itself, and including a hundred translations into the kernel image itself would serve no purpose other than increasing the kernel size dramatically.
For many things there are front-ends, user space programs which read the kernel info and present it in a translated fashion.


text:
Q: Git 'blob' versus 'commit' problems. I have a project in which I want to embed a python module. I git cloned the python module and rearranged it in my python structure. Now when I try to add the python module in my git repository it is added as following:
100755 blob 7899dc9d74b1fbe3b1bf0e54a2480b68da2dddcc    code_base/frroleutils/entityutils/arktweetnlp/scripts/show.py
100755 blob a959deef0f9833e60b5446adefab6796f5f71449    code_base/frroleutils/entityutils/arktweetnlp/scripts/simple_tests.sh
100755 blob 80c8009bb48811962968bcf3c4705009f6497eb1    code_base/frroleutils/entityutils/arktweetnlp/scripts/toconll.py
100755 blob d712af76ca62b2fa1f2b93533cead693b96c053a    code_base/frroleutils/entityutils/arktweetnlp/twokenize.sh
100644 blob 24d5c14ece8f45018126d97232579b088396d2f8    code_base/frroleutils/entityutils/ners.py
100644 blob 347c43fba86db13c195c508614c1cb630f437794    code_base/frroleutils/entityutils/ners.pyc
160000 commit fbc6094e8634dd7b64c40d26c587ee074499b879  code_base/frroleutils/entityutils/twitter_nlp
100644 blob e7b4ac061b6b721bca87f52941a13f8438fd9b9b    code_base/frroleutils/utils.py
100755 blob af369b76f0fb7f4d0d3314919a4be0d1bd82ac06    code_base/init.py
100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391    code_base/location_script/Untitled Document
100644 blob 108cae5da47c8dadd1b21897dfdcf7a9a8a6d55b    code_base/location_script/__init__.py
100644 blob 5a1fef41e997e5c29037110f4d489e7628969dba    code_base/location_script/blacklist.list
100644 blob 5a1fef41e997e5c29037110f4d489e7628969dba    code_base/location_script/blacklist.list~
100644 blob d8fd99d73318712b4cde674fc235d50a771f2ba1    code_base/location_script/load.py

As you can see the python module is twitter_nlp and for strange reason, it's appearing as type 'commit' in my git repo tree.
A problem is that I'm unable to add any files under twitter_nlp in my git repo. I have no idea what is happening here, any help is greatly appreciated.

A: The mode 160000 indicates that it's a submodule.  See also Rename a git submodule.


text:
Q: how to use multiple threads to draw multiple bitmaps on the canvas in surfaceview? I am developing a game in which I have to show multiple image moving in directions but one image cannot over lap other how can i achieve this. I think I should use multiple threads one thread for every image but when i try to initialize thread by sending it canvas using canvas it gives
error 01-11 17:18:15.409: E/AndroidRuntime(1046): java.lang.IllegalThreadStateException: Thread already started.

How can I achive this. Can any body give me idea or some tutorial. Any help will be appreciable.

A: Your error happens when you try to start an already started thread. You don't need to have multiple threads. One thread for all your drawing is more than enough.
I have written a tutorial series for introduction into android 2d drawing. I recommend you to start with the second part that introduce the thread usage.


text:
Q: Rebuilding a jQuery slick carousel after AJAX call; "unslick" not working I am using the slick carousel plug-in defined here:
http://kenwheeler.github.io/slick/
My carousel resides within content that is refreshed by an AJAX call. When the call returns, I attempt this within the .complete method, after I have replaced the content:
$('.thumbnails')
.slick('unslick')
.slick({ ... });

where "..." is the same set of parameters used to build the original carousel.
The problem is that slick.js is throwing an error:
TypeError: _[i].slick is undefined
ret = _[i].slick[opt].apply(_[i].slick, args);

where "opt" is apparently "unslick", at least according to my debug attempts.
If I omit the "unslick" method, then I don't get an error message, but my carousel appears with a full extra set of images; they are all squashed together and overlay one another, until I navigate to a new slide, and then things straighten themselves out ... but I really don't want the old images, just the new ones in the AJAX content.


text:
Q: How to use select the appropriate column in GROUP BY while using group by command if both tables have customer_id column then which table column should we use in the below illustration please tell me how to select the table:
FROM A
INNER JOIN B ON A.customer_id = B.customer_id
GROUP BY A.customer_id
I'm really having a hard time determining the appropriate column when combined with a JOIN where both tables have that table


text:
Q: Variable not working inside an if statement when used in a for loop with enabledelayedexpansion I have a text file with MS Windows update names:
...
KB3072019
KB3044374
KB3011780
KB3083711
...

And having a folder with

:
My goal is to check wether an update is downloaded or not according to the text file.
@echo off
set /a x=0
setlocal ENABLEDELAYEDEXPANSION

for /F "tokens=*" %%A in (d:\WindowsUpdate.log) do (
set /a x=x+1
echo Update number !x!, name %%A, state:
IF EXIST d:\!Del\Win8Updates_x64\Merged\*%%A*.cab (echo Downloaded) ELSE (echo MISSING!)
)
pause

The output should be like this:
Update number 83, name KB3045999, state:
MISSING
Update number 84, name KB3045746, state:
Downloaded
Update number 85, name KB3066441, state:
Downloaded
Update number 86, name KB3071663, state:
MISSING

But actually it looks like this:
Update number 83, name KB3045999, state:
MISSING
Update number 84, name KB3045746, state:
MISSING
Update number 85, name KB3066441, state:
MISSING
Update number 86, name KB3071663, state:
MISSING

My question: why does %%A not work inside the if statement?
Important: I don't want to skip the line numbers, because they're representing the order of the updates. Later I'll modify the script to copy/move the existing updates to another location prefixed with it's order number, like 83_windows8.1-kb3045999-x64.cab

A: There is a path containing an exclamation mark, d:\!Del, which causes the problem, because when delayed expansion is enabled, the ! is removed. This is also true for the echoed text MISSING!. Removing @echo off temporarily will allow you to see that behaviour when examining the output.
To avoid that, there are (at least) the following options:

*

*Escaping exclamation marks:
@echo off
set /A x=0
setlocal EnableDelayedExpansion

for /F "tokens=*" %%A in (d:\WindowsUpdate.log) do (
    set /A x+=1
    echo Update number !x!, name %%A, state:
    if exist "d:\^!Del\Win8Updates_x64\Merged\*%%A*.cab" (
        echo Downloaded
    ) else (
        echo MISSING^^!
    )
)
endlocal
pause

*Disabling delayed expansion temporarily:
@echo off
set /A x=0
setlocal EnableDelayedExpansion

for /F "tokens=*" %%A in (d:\WindowsUpdate.log) do (
    set /A x+=1
    echo Update number !x!, name %%A, state:
    setlocal DisableDelayedExpansion
    if exist "d:\!Del\Win8Updates_x64\Merged\*%%A*.cab" (
        echo Downloaded
    ) else (
        echo MISSING!
    )
    endlocal
)
endlocal
pause

*Enabling delayed expansion only where needed:
@echo off
set /A x=0
setlocal DisableDelayedExpansion

for /F "tokens=*" %%A in (d:\WindowsUpdate.log) do (
    set /A x+=1
    setlocal EnableDelayedExpansion
    echo Update number !x!, name %%A, state:
    endlocal
    if exist "d:\!Del\Win8Updates_x64\Merged\*%%A*.cab" (
        echo Downloaded
    ) else (
        echo MISSING!
    )
)
endlocal
pause


text:
Q: ListView does not update at once I am making a "Note" program to practice and learn - my first "freestyle" project after reading a book on the subject. The way i figured i would do this is to store the title and content of the note in a SQLite table, and insert and remove from the table as needed.
The first activity consists of a ListView which gets all the notes(rows) from the DB. The user is supposed to press a button at the first activity, which says "New note", which then leads to another activity where you can enter the title and the content of the note, press the "Save" button, and then with an intent, return to the activity with the ListView where the newly added note plus all earlier created notes are displayed in the ListView.
My problem is that when the intent starts the activity with the ListView from the NewNote activity, the newly added note wont show in the ListView at once. If i then add a new note again, it returns to the first activity, but then the note i added first is displayed. And so it goes on. In other words the list on the first activity is always "one note behind", as it only adds the note i added the last time and not the one i recently added. Maybe its a bad explanation, but i think thats as clear as it gets. I spent alot of time today logging and trying to find the problem but i cant seem to figure this out on my own.
Here is my code.
Starting with my database class:
public class DatabaseHandler extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "DB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NOTES = "Notes";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_PERSON_TABLE = "CREATE TABLE " + TABLE_NOTES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT," + KEY_CONTENT + " INTEGER" + ")";
    db.execSQL(CREATE_PERSON_TABLE);
}

public void dropTable() {
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
    onCreate(db);
}

public void newNote(String title, String content) {

    SQLiteDatabase db = this.getReadableDatabase();
    ContentValues values = new ContentValues();

    values.put(KEY_TITLE, title);
    values.put(KEY_CONTENT, content);
    db.insert(TABLE_NOTES, null, values);

    db.close();
}

public void deleteNote(String id) {
    SQLiteDatabase db = getReadableDatabase();
    db.delete(TABLE_NOTES, KEY_ID + "=" + id, null);
}

public ArrayList<Note> getNotes() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<Note> notes = new ArrayList<>();

    Cursor cursor = db.query(TABLE_NOTES, new String[]{KEY_ID, KEY_TITLE, KEY_CONTENT}, null, null, null, null, KEY_ID + " DESC", null);
    if (cursor != null) {
        cursor.moveToFirst();
    }

    while(cursor.moveToNext()) {
        Note note = new Note(cursor.getString(0), cursor.getString(1), cursor.getString(2));
        notes.add(note);
    }

    db.close();
    return notes;
}

public void deleteAll() {
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL("delete from " + TABLE_NOTES);
    db.close();
   }
}

My Main activity, ListActivity:
public class ListActivity extends AppCompatActivity {
    private DatabaseHandler dbh;
    private ListView list;
    private ArrayAdapter<Note> listAdapter;
    private Button newBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    dbh = new DatabaseHandler(this);

    Intent intent = getIntent();
    String id = intent.getStringExtra("Id");
    String title = intent.getStringExtra("Title");
    String content = intent.getStringExtra("Content");

    //If save button is pressed at NewNote
    if (title != null && content != null) {
        dbh.newNote(title, content);
        Log.d("note", title + " added");
    }

    //If delete button is pressed at NewNote
    if (id != null) {
        dbh.deleteNote(id);
    }

    initWidgets();

    }

public void initWidgets() {
    list = findViewById(R.id.list);
    newBtn = findViewById(R.id.newButton);

    newBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent newButtonIntent = new Intent(ListActivity.this, NewNote.class);
            startActivity(newButtonIntent);
        }
    });

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Note note = listAdapter.getItem(i);
            Intent editIntent = new Intent(ListActivity.this, EditNote.class);
            editIntent.putExtra("Title", note.getTitle());
            editIntent.putExtra("Content", note.getContent());
            editIntent.putExtra("Id", note.getId());
            startActivity(editIntent);

        }
    });

    refreshList();

}

public void refreshList() {
    listAdapter = new ArrayAdapter(this, R.layout.list_item, dbh.getNotes());
    list.setAdapter(listAdapter);

    Log.d("note", "View updated");
}
}

My NewNote class:
public class NewNote extends AppCompatActivity {
    private EditText title;
    private EditText content;
    private Button btnSave;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_note);
    initWidgets();
}

public void initWidgets() {
    title = findViewById(R.id.title);
    content = findViewById(R.id.content);
    btnSave = findViewById(R.id.saveButton);

    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                    Intent i = new Intent(NewNote.this, ListActivity.class);
                    i.putExtra("Title", title.getText().toString());
                    i.putExtra("Content", content.getText().toString());
                    startActivity(i);
        }
    });

}
}

Not really relevant as i have not implemented it fully, if you are just reading through the code you can 100% just ignore this class - my EditNote class:
public class EditNote extends AppCompatActivity {
    private EditText title;
    private EditText content;
    private Button saveBtn;
    private Button deleteBtn;
    private String noteId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_note);

    initWidgets();

    Intent intent = getIntent();
    title.setText(intent.getStringExtra("Title"));
    content.setText(intent.getStringExtra("Content"));
    noteId = intent.getStringExtra("Id");
}

public void initWidgets() {
    title = findViewById(R.id.titleEdit);
    content = findViewById(R.id.contentEdit);
    deleteBtn = findViewById(R.id.deleteButton);

    deleteBtn.setOnClickListener(new View.OnClickListener(){
       @Override
        public void onClick(View view) {
            Intent i = new Intent(EditNote.this, ListActivity.class);
            i.putExtra("Id", noteId);
            startActivity(i);
        }
    });

}
}

Also there are my XML files, and a Note class which only consists of member variables and setters/getters, either of them i consider relevant. I think the problem is somewhere in the DB class, ListActivity class, or NewNote class.
Maybe this is alot to read for you and maybe its messy or im doing something wrong with the posting but i would be grateful for help on how to resolve this issue. Also if you see other things i can do better please point them out!
Thanks!


text:
Q: ComboBox.ValueMember problem during subelements creation I have some problem with my combobox, I'm trying to fill it with some values from database, everything work fine, except the fact that last line of this code (with ValueMember in it) generate UnknownException in free translation it says that it cannot create a list of sub elements for the "table" field.
connection = new MySqlConnection(connectionString);
connection.Open();

MySqlDataAdapter mda = new MySqlDataAdapter(query, connection);

DataSet my_dataset = new DataSet("dataset");
mda.Fill(my_dataset);
connection.Close();

DataViewManager dvm_cb2 = my_dataset.DefaultViewManager;
my_combobox.DataSource = dvm_cb2;
my_combobox.DisplayMember = table + "." + name;
my_combobox.ValueMember = table + "." + my_id;

Any ideas, what could be the problem?

A: DisplayMember and ValueMember should be string repreentations of the object property
So for example if you had a collection of the following object
public class MyObject
{
    public string ItemId = "";
    public string DisplayValue = "";
}

So you make a collection of the object
List<MyObject> list = new List<MyObject>();

Then assign this and the properties to the combo box
combobox.DataSource = list ;
combobox.DisplayMember = "DisplayValue";
combobox.ValueMember = "ItemId ";

That should work.

A: try out this
my_combobox.DisplayMember = "fieldname";
my_combobox.ValueMember = "fieldname";
my_combobox.DataSource = dvm_cb2;


text:
Q: Column name set in stored procedure but not working Column name set in stored procedure but not working. But when I run this script empty rows appears. What I do this for run this script?
Create Procedure Test
()
AS
BEGIN
   Declare @columnName nvarchar(50);

   set @columnName ='StoreName';

   SELECT *
   FROM testtable
   WHERE @columnName = 'storemanager'
END

A: You need to use dynamic SQL because you can't reference a column with a variable - T-SQL just doesn't parse things in that order. Try something like:
CREATE PROCEDURE dbo.Test
  @columnName NVARCHAR(50),
  @value NVARCHAR(4000)
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @sql NVARCHAR(MAX);

  SET @sql = N'SELECT * FROM dbo.testtable WHERE '
    + QUOTENAME(@columnName) + ' = @value;';

  EXEC sp_executesql @sql, N'@value NVARCHAR(4000)', @value;
END
GO

QUOTENAME() wraps the column in [square brackets] and hopefully protects you from SQL injection. You should also read these posts:

*

*Bad habits to kick : using SELECT * / omitting the column list

*Bad habits to kick : avoiding the schema prefix

*My stored procedure "best practices" checklist


text: Q: How to draw bezier path around a concave white portion of black-and-white image? I need to find the contour of a black and white image and draw a bezier path around the white portion in a black and white image, the white portion is concave, is there a way to get a bezier path around the white portion, wrapping the entire white portion on it's boundary?


text:
Q: Liferay CSS @import Issue I tried to take a look around here and on the Liferay forums but I couldn't find a documented solution to my issue.
I am currently using Liferay 6.2 and am very new to the environment. My issue arises from CSS @import functions. Our architecture is one main stylesheet with all supporting stylesheets imported into this document. Those CSS documents in the same directory present no issue - for example @import url(document.css);. We do have a master stylesheet located in another portlet and all other portlets reference this stylesheet with an import call similar to @import url(../../../../folder/folder/document.css);. When using this command, the CSS in this file isn't imported into the portlet. If I place the master stylesheet in the same directory as the CSS for that portlet and adjust the import path accordingly, the stylesheet is imported without any issues. I can also place it one directory up such as @import url(../folder/document.css); and the CSS is imported correctly.
Several team members do not have this issue, while several members do experience this issue - all running the same version of Liferay and on identical machines.
I'm sure my question is fairly vague due to me being new with the environment so if I can clarify or provide any additional details, please let me know!

A: If all of the portlets reference the same CSS file they shouldn't: Just assume that the necessary CSS is deployed through the theme and add it to the theme once. This is way more elegant than delivering it multiple times, relying on relative paths to not have changed, and potentially not being available (at runtime, nobody guarantees that an appserver even unzipps your warfiles).
Through enforcing the assumption that you're running in an environment that has proper styling, life will be so much easier.


text:
Q: Extract data from table using html agility pack I have the following table and I want to extract the values Value_1 and Value_2 by matching Description_Line_1 and Description_Line_2.

Description_Line_1

Value_1

Description_Line_2

Value_2

The code I came up with is below, but it raises a null reference exception.
string filename = "TableSample.htm";
HtmlDocument doc = new HtmlDocument();
doc.Load(filename);
var tableNode = doc.DocumentNode.SelectSingleNode("//table[@id='tableId' and class='tableClass']//tr");
var value1 = tableNode.SelectSingleNode(".//th[contains(text(),'Description_Line_1')]/td/text()").InnerText;


text:
Q: need regular expression in jmeter {"string":"{\"data\":[{\"id\":\"2c9180834e532f54014e6759d2ac004b\",\"unitName\":\"Actual11\",\"owner\":\"Nikolus\",\"description\":\"performance\",\"nofChairs\":0,\"nofBeds\":0,\"nofApptStartWithInHour\":0,\"nofApptDischargeWithInHour\":0,\"modifiedDateTime\":\"Jul 7, 2015 12:10:17

this is my response. this id will be used in next scripts. plz help me

A: Try this,
\{"string":"\{\\"data\\":\[\{\\"id\\":\\"(\w+)\\",

This will work only if your response data is as you have given. I think some \ are extra like {\"data\":[{\"id\". This should be like, {"data":[{"id". In such case,
\{"string":"\{"data":\[\{"id":"(\w+)",

This should be enough. Next time show your efforts first.

A: May be you'd better use any JSON decoder instead?
UPD
/{"string":"{\\"data\\":\[{\\"id\\":\\"([a-f0-9]+)\\".*/

I don't actually know whether order and names of your keys remains the same.


text:
Q: Keyboard Input in Assembly 8086 I'm trying to create an animation in assembly 8086, controlled by the keyboard, using Ctrl and Shift as left and right.
I tried to look for how to receive input from the keyboard in 8086, and then how to find out if the key that was pressed is Ctrl or Shift (and generally, which key was pressed).

A: Are you sure you wouldn't rather use the arrow keys for left and right? The problem with control and shift is that they don't "return" a key, they modify another key that is pressed. This is handled in the keyboard interrupt handler (9, IIRC), and you could "hook" that. I think it would be easier to look in the "Bios Data Area" and watch where the interrupt handler keeps track of the state of control and shift keys. Seems to me the BDA was in segment 40h. Keyboard status flags at... 17h and 18h? Don't take my word for those offsets, look it up. Ralf Brown's Interrupt List. This all assumes that "8086" means, like... antiquities. :)

A: Assuming that you're doing this running under only BIOS, you may find it easier to use the higher level BIOS keyboard interrupts - int 0x16 AH=0x01 for general keystrokes, and int 0x16 AH=0x02 for ctrl/shift etc are likely possibilities, although there are a number of other possibilities (including other int 0x16 command and -as has been previously suggested - the low level keyboard int 0x09 and the BIOS data area.. I strongly second the recommendation of Ralf Brown's Interrupt List - an excellent resource!

A: The Bios stores the keys in a 16 letter buffer. Meaning if an os is too slow, whenever it reads the next keystroke it reads from the buffer.
You can use int 16h with ah set to 02h to set al as the next char in the buffer. HOWEVER if you are checking the status of the buffer (is there a key) look at this. It basically goes into more depth of ah 02h
Since you are asking about the arrow keys, here are their hex codes:

*

*U 0x18

*D 0x19

*L 0x1B

*R 0x1A

A: The usual choice to control movement is through the arrow keys on the keyboard. The Shift, Ctrl, and Alt keys are often used as action keys: think of actions like firing, jumping, using gadgets, ...
Using the arrow keys
In your main loop you check whether a keystroke is available. BIOS has the CheckKeystroke function 01h for this. If it returns with the zero flag set (ZF=1) then no key is waiting and you can just continue the loop. But if the zero flag is clear (ZF=0) then a key (at least one) is waiting in the keyboard buffer that BIOS maintains. It is imperative that you remove this key from the buffer. If you didn't, the buffer would rapidly fill up to its maximum of 15 keys and you could be loosing control of your program. BIOS has the GetKeystroke function 00h to fetch the oldest key from the buffer, returning its ASCII code in the AL register and its scancode in the AH register. (If the buffer were empty this function would wait for a key to get pressed, but in our case this will not be happening since we checked the availability of a key beforehand).
The arrow keys that interest us are identified by their scancode in the AH register: Up=48h, Left=4Bh, Right=4Dh, Down=50h.
Using the modifier keys
In your main loop you ask BIOS for its keyboard flags. If you don't need to distinguish between the Left-Ctrl, Left-Alt, Right-Alt, Right-Ctrl keys then you can use the BIOS GetKeyboardFlags function 02h that returns the following items in the AL register:
76543210
.......1  Right shift key is depressed
......1.  Left shift key is depressed
.....1..  Either ctrl key is depressed
....1...  Either alt is depressed
...1....  Scroll lock is enabled
..1.....  Num lock is enabled
.1......  Caps lock is enabled
1.......  Insert key is enabled

If you do need to distinguish between the Left-Ctrl, Left-Alt, Right-Alt, Right-Ctrl keys then you can use the BIOS GetKeyboardFlags function 12h that additionally returns the following items in the AH register:
76543210
.......1  Left ctrl key is depressed
......1.  Left alt key is depressed
.....1..  Right ctrl key is depressed
....1...  Right alt is depressed
...1....  Scroll lock is depressed
..1.....  Num lock is depressed
.1......  Caps lock is depressed
1.......  SysRq key is depressed (Acer reports Insert key)

The included demo program shows a paddle floating near the bottom of the screen going back and forth from left to right.
If UseArrows is enabled (non-zero), then pressing Left-Arrow or Right-Arrow will set the paddle's direction.
If UseShifts is enabled (non-zero), then pressing Left-Shift or Right-Shift will set the paddle's direction, and right has precedence over left if both shifts are pressed together.
You can have UseArrows and UseShifts enabled together.
Press Esc to stop the program.
  ORG  256              ; Assembled with FASM
  UseShifts = 0
  UseArrows = 1

  mov  ax, 0003h        ; BIOS.SetVideoMode 80x25 text
  int  10h
  mov  dx, 1724h        ; DX is position (36,23)
  xor  bx, bx

MainEx:
  mov  cx, bx           ; CX is direction [-1=Left,0=Right]
Main:
  call Delay

  jcxz .Right
.Left:
  cmp  dl, 2            ; Left border
  ja   .Move
  jmp  .Turn
.Right:
  cmp  dl, 72           ; Right border
  jb   .Move
.Turn:
  not  cx               ; -> CX is new direction
.Move:
  call MovePaddle       ; -> DX is new position
  call MovePaddle       ; -> DX is new position

  IF UseShifts
    mov  ah, 02h          ; BIOS.GetKeyboardFlags
    int  16h              ; -> AL
    test al, 00000011b
    jz   .Neither
    xor  bx, bx
    test al, 00000001b
    jnz  MainEx           ; Set direction=0 on <RIGHT-SHIFT>
    not  bx
    jmp  MainEx           ; Set direction=-1 on <LEFT-SHIFT>
  .Neither:
  END IF

  mov  ah, 01h          ; BIOS.CheckKeystroke
  int  16h              ; -> AX ZF
  jz   Main             ; No key available
  mov  ah, 00h          ; BIOS.GetKeystroke
  int  16h              ; -> AX
  IF UseArrows
    xor  bx, bx
    cmp  ah, 4Dh
    je   MainEx           ; Set direction=0 on <RIGHT-ARROW>
    not  bx
    cmp  ah, 4Bh
    je   MainEx           ; Set direction=-1 on <LEFT-ARROW>
  END IF
  cmp  al, 27
  jne  Main             ; Ignore all other keys except <ESC>
Exit:
  int  20h              ; DOS.TerminateProgram
; ----------------------
; IN () OUT ()
Delay:
  push ds ax
  xor  ax, ax
  mov  ds, ax
  mov  ax, [046Ch]      ; BIOS.TimerTick
.Again:
  cmp  ax, [046Ch]
  je   .Again           ; TimerTick didn't change
  pop  ax ds
  ret
; ----------------------
; IN (cx,dx) OUT (dx)
MovePaddle:
  push ax bx cx
  mov  ax, 0001h        ; Move right .. Wipe at +0, Draw at +1
  jcxz .Wipe
  mov  ax, 05FAh        ; Move left  .. Wipe at +5, Draw at -6
.Wipe:
  push ax               ; (1)
  add  dl, ah           ; AH is {0,5}
  mov  bx, 0007h        ; BH is DisplayPage, BL is Attribute
  mov  ah, 02h          ; BIOS.SetCursorPosition
  int  10h
  mov  cx, 1            ; ReplicationCount (PaddleStep)
  mov  ax, 0920h        ; BIOS.WriteCharacterAndAttribute, AL is Space
  int  10h
.Draw:
  pop  ax               ; (1)
  add  dl, al           ; AL is {1,-6}
  mov  ah, 02h          ; BIOS.SetCursorPosition
  int  10h
  mov  cx, 6            ; ReplicationCount (PaddleLength)
  mov  bl, 0Eh          ; BL is Attribute
  mov  ax, 09DCh        ; BIOS.WriteCharacterAndAttribute, AL is HalfBlock
  int  10h
  pop  cx bx ax
  ret
; ----------------------


text:
Q: Kubernetes - Completely avoid node with PreferNoSchedule taint The problem:
We have nodes in kubernetes, which will occasionally become tainted with an effect of PreferNoSchedule. When this happens, we would like our pods to completely avoid scheduling on these nodes (in other words, act like the taint's effect were actually NoSchedule). The taints aren't applied by us - we're using GKE and it's an automated thing on their end, so we're stuck with the PreferNoSchedule behaviour.
What we can control is the spec of our pods. I'm hoping this might be possible using a nodeAffinity on them, however the documentation on this is fairly sparse: see e.g. here. All the examples I can find refer to an affinity by labels, so I'm not sure if a taint is even visible/accessible by this logic.
Effectively, in my pod spec I want to write something like:
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/taints *I've invented this, it doesn't work
            operator: NotIn
            values:
            - DeletionCandidateOfClusterAutoscaler

where DeletionCandidateOfClusterAutoscaler is the taint that we see applied. Is there a way to make this work?
The other approach we've thought about is a cronjob which looks for the PreferNoSchedule taint and adds our own NoSchedule taint on top... but that feels a little gross!
Any neat suggestions / workarounds would be appreciated!
The long version (if you're interested):
The taint gets applied by the autoscaler to say the node is going to go away in 30 minutes or so. This issue describes in some more detail, from people having the same trouble: https://github.com/kubernetes/autoscaler/issues/2967

A: I have tested your same scenario and indeed, GKE reconciles the current node configuration at the moment the autoscaler starts to spin up. This is in order to ensure no downtime in case of a lack of resources in the node which the pods/workloads can be scheduled. I believe there is no way to set the hard NoSchedule taint cleanly.
So, the critical information to keep in mind when using the autoscaler is:

*

*Pods will not be scheduled to the soft-tainted nodepool if there are resources available in the regular one.

*If not enough resources are available in the regular one, they will be scheduled to the soft-tainted nodepool.

*If there aren't enough resources in the nodepools, the nodepool with the smallest nodetype will be autoscaled no matter the taints.
As you mentioned a dirty workaround will be to:
A.- Create a cron or daemon to set the  NoSchedule and overwrite the soft one set by the autoscaler.
B.- A.- Ensure the resources habitability, maybe by setting perfect resource limits, and requests.


text:
Q: React Native - Navigation through routestack When I press the second Highlight, it should navigate to the third Scene.
But it navigates to a blank/white screen.
The only way to get to the third scene is only if you go to the second scene by pressing the first highlight, pop, and then press to the second highlight and then it works.
But what if I want to get to the third right away?
<Navigator initialRoute={routes[0]} initialRouteStack={routes} renderScene={(route, navigator) =>
    <View>
    <TouchableHighlight onPress={() => {
      if (route.index == 0) {
        navigator.push(routes[1]);
      } else {
        navigator.pop();
      }
      }
    }
    >
    <Text>Hello {route.title}!</Text>
    </TouchableHighlight>

    <TouchableHighlight onPress={() => {
      if (route.index == 0) {
          navigator.push(routes[2]);
      } else {
        navigator.pop();
      }
      }
    }
    >
    <Text>Please {route.title}!</Text>
    </TouchableHighlight>
    {getPage(route.index)}
</View>
}
/>

A: Updated:
You need to remove initialRouteStack prop from your Navigator if you have already set initialRoute prop so you are able to navigate to the third scene from the first scene.
Not sure why you can't have both props set for it to work.


text:
Q: C#7 tuple & async Old format:
private async Task<Tuple<SomeArray[], AnotherArray[], decimal>>
GetInvoiceDetailAsync(InvoiceHead invoiceHead) { ... }

How can you do that in C#7 with new tuples format?

A: Step 1: add the ValueTuple nuget package to your project.
Step 2: as Lucas says in his comment, change the syntax to:
private async Task<(SomeArray[], AnotherArray[], decimal)>GetInvoiceDetailAsync(
    InvoiceHead invoiceHead)
{
    ...
    return (x, y, z);
}

Note though that you can also then add names to those tuple items, along the lines of:
private async Task<(SomeArray[] x, AnotherArray[] y, decimal z)>GetInvoiceDetailAsync(
    InvoiceHead invoiceHead)
{
    ...
    return (x, y, z);
}

And you can then access them as those names, rather than Item1, Item2 and Item3.


text:
Q: How can I share a spawned SSH process between multiple procedures in TCL Expect? Edit: I've figured it out by referencing the Exploring Expect book. Please don't hesitate to add to my answer or make other suggestions, though! I will mark this as answered when I am allowed to (2 days from now).
I've looked around and unfortunately I'm not able to find too much on using SSH with expect here on this site.  I am relatively new to Expect but I have been teaching myself with the Exploring Expect book.
My question is: How can I use a single spawned SSH process for multiple tcl procedures?  My workaround right now is to close the SSH connection at the end of procedure 1 and re-spawn a new SSH connection in procedure 2.
Example: (The example is simplified quite a bit and only includes the necessary components to demonstrate my question... My whole program is over 200 lines as of now)
;# Proc definition for procedure1
    proc procedure1 {user host pw} {
     spawn /usr/bin/ssh $user@$host
     expect "Password:"
     send "$pw\r"
     expect "#" ;# This is my device's prompt
     ;# From here it does a bunch of stuff... sends commands to the SSH
     ;# session, captures output, builds arrays and lists, etc
     send "exit" ;# Disconnects the SSH session
     return $mylist ;# returns a list of numbers to be used in procedure 2
     }

;# Proc definition for procedure2
    proc procedure2 {resultofproc1 user host pw} {
     spawn /usr/bin/ssh $user@$host
     expect "Password:"
     send "$pw\r"
     expect "#" ;# This is my device's prompt
     ;# Proc 2 now continues on in the same device using the results (a
     ;# list) from proc1.
     return
    }

    ;# Procedure call for first procedure:
    set resultofproc1 "[procedure1 $user $host $pw]"

    ;# Procedure call for second procedure:
    procedure2 $resultofproc1 $user $host $pw

Instead of closing the SSH connection at the end of procedure1 and reopening the SSH connection at the beginning of procedure2, how can I send commands from procedure2 to the SSH connection opened in procedure1?  Obviously I would have to remove the sending of exit to keep the connection open.  Assuming this is possible... Is this even a good practice or am I better off separating connections between procedures? If so, can you modify my code example to demonstrate how?
From what I have gathered, I think it has to do with the spawn_id variable.. but I can't figure out how to implement that in my code.  I am currently reviewing chapter 10 "Handling Multiple Processes" in the Exploring Expect book. I will report back if I can figure it out on my own.
Thanks for your assistance!
I have viewed these answers on stackoverflow:
Tcl Expect Keep SSH Spawn open
Expect Procedure for SSH Login
Using procedure for spawing SSH doesn't work properly with expect

A: You can use global to declare spawn_id as a global var. According to expect's manual:

CAVEATS

...
Expect  takes  a rather liberal view of scoping.  In particular, variables read by commands specific to the Expect program will  be  sought first  from  the  local  scope, and if not found, in the global scope. For example, this obviates the need to place global timeout in every procedure  you  write  that uses expect.  On the other hand, variables written are always in the local scope (unless a global  command  has been  issued).   The  most common problem this causes is when spawn is executed in a procedure.  Outside the procedure,  spawn_id  no  longer exists,  so the spawned process is no longer accessible simply because of scoping.  Add a global spawn_id to such a procedure.
    ...

You can also take advantage Tcl's upvar command. For example:
[STEP 101] $ cat foo.exp
proc expect_prompt {} {
    upvar spawn_id spawn_id
    expect -re {bash-[.0-9]+[#$] $}
}

proc open_conn {} {
    upvar spawn_id spawn_id
    spawn bash --noprofile --norc
    expect_prompt
}

proc close_conn {} {
    upvar spawn_id spawn_id
    send "exit\r"
    expect eof
}

proc send_cmd { cmd } {
    upvar spawn_id spawn_id
    send "$cmd\r"
    expect_prompt
}

proc main {} {
    open_conn

    send_cmd "echo spawn_id=$spawn_id"
    send_cmd "ps Tu"

    close_conn
}

main
[STEP 102] $

Output:
[STEP 103] $ expect foo.exp
spawn bash --noprofile --norc
bash-4.4$ echo spawn_id=exp6
spawn_id=exp6
bash-4.4$ ps Tu
USER     PID  %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND
root   71513   0.0  0.0  2433012    788 s013  R+   12:58PM   0:00.00 ps Tu
pynexj 71510   0.0  0.0  2445360   1572 s013  Ss   12:58PM   0:00.01 bash --noprofile --norc
bash-4.4$ exit
exit
[STEP 104] $

A: Ah, I was so close!  Had I taken a few more minutes in the Exploring Expect book, I would have figured it out.  Anyways, here is my solution. Hopefully it helps someone else with the same problem.
It has everything to do with the spawn_id variable.  Basically, by default, the send and expect commands interact only with the last spawned process.  Each spawned process is assigned a unique spawn_id value.  You can set the spawn_id of a procedure to the spawn_id of another spawned process.
Here is the code in my original question modified to support the spawn_id variable:
;# Proc definition for procedure1
    proc procedure1 {user host pw} {
     spawn /usr/bin/ssh $user@$host
     global procedure1_spawnid         ;# Creates a global variable called
                                       ;# procedure1_spawnid
     set procedure1_spawnid $spawn_id  ;# Assigns the spawn_id of the SSH process to the
                                       ;# global variable.
     expect "Password:"
     send "$pw\r"
     expect "#" ;# This is my device's prompt
     ;# From here it does a bunch of stuff... sends commands to the SSH
     ;# session, captures output, builds arrays and lists, etc
     return $mylist ;# returns a list of numbers to be used in procedure 2
     }

;# Proc definition for procedure2
    proc procedure2 {resultofproc1} {
     global procedure1_spawnid
     set spawn_id $procedure1_spawnid   ;# Sets the spawn_id to that of the SSH connection
                                        ;# in procedure1.
     send "show ip interface brief"
     expect "#"
     ;# The show ip interface brief command is sent to the device through the
     ;# SSH connection opened in procedure1.
     return
    }

    ;# Procedure call for first procedure:
    set resultofproc1 "[procedure1 $user $host $pw]"

    ;# Procedure call for second procedure:
    procedure2 $resultofproc1

More information can be found in Exploring Expect, page 233.
If anyone has any suggestions or improvements, please feel free to lay them on me! I am still learning tcl/expect.


text:
Q: How to use WPF to visualize a simple 2D world (map and elements) I'm fairly new to WPF and looking for a simple solution to the problem described below. I've tried to make this as short as possible.
I'm trying to visualize a "world" that is modeled by:

*

*A map image, with a known origin in meters (e.g. top-left corner is 14,27) and resolution in cm/pixel. The map keeps growing every few seconds. Maps are small so no paging/tiling is required.

*Real-world elements and points of interest. Each element has a 2D position in meters within the map area. Also, each element might move.

Regarding the model side, I have a WorldState class that keeps the map and elements:
interface IWorldState
{
    IEnumerable<IWorldElement> Elements { get; }
    IMapData CurrentMap { get; }
}

interface IWorldElement
{
    WorldLocation { get; }
    event EventHandler LocationChanged;
}

interface IMapData
{
    string FilePath { get; }
    WorldLocation TopLeft { get; }
    Size MapSize { get; }
}

Now regarding the visualization, I've chosen the Canvas class to draw the map and elements. Each type of element (inherits from IWorldElement) should be drawn differently. There might be more than one map canvas, with a subset of the elements.
<Canvas x:Name="mapCanvas">
    <Image x:Name="mapImage" />
</Canvas>

In code, I need to set the map image file when it changes:
void MapChanged(IWorldState worldState)
{
    mapImage.Source = worldState.CurrentMap.FilePath;
}

To draw the elements, I have a method to convert WorldLocation to (Canvas.Left, Canvas.Top) :
Point WorldToScreen(WorldLocation worldLocation, IWorldState worldState)
{
    var topLeft = worldState.CurrentMap.TopLeft;
    var size = worldState.CurrentMap.Size;
    var left = ((worldLocation.X - topLeft.X) / size.X) * mapImage.ActualWidth;
    var top = ((worldLocation.Y - topLeft.Y) / size.Y) * mapImage.ActualHeight;
    return new Point(left, top);
}

Now for the question, how should I glue the world model and the canvas together? This can be summarized by:

*

*Where to put the MapChanged and WorldToScreen functions.

*When an element moves the world location needs to be converted to screen coordinates.

*Each type of element should be drawn differently, for example ellipse with text or filled rectangle.

What is the recommended way to implement the "glue" layer when using WPF?

A: DataBinding is the way to go.
Read here, http://msdn.microsoft.com/en-us/magazine/dd419663.aspx.
Once you've set up a viewmodel and set the datacontext of the view.
I suggest putting your elements in an observablecollection and bind it to an itemscontrol in the canvas.
For the elements to be positioned, you must create a custom ItemTemplate for the ItemsControl which uses a canvas, rather than the default stackpanel as container.
Then you can go ahead and create datatemplate for the various types of elements you have to get a specific look and feel pr element type.
This is a rough outline of a solution, hope this helps.
Example:
<Window x:Class="WorldCanvas.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WorldCanvas"
Title="WorldCanvas" Height="500" Width="500"
>
<Window.Resources>
    <DataTemplate DataType="{x:Type local:HouseVM}" >
        <Canvas>
            <Rectangle Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}" Width="13" Height="23" Fill="Brown" />
        </Canvas>
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:BallVM}">
        <Canvas>
            <Ellipse Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}" Width="13" Height="13" Fill="Blue" />
        </Canvas>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Canvas x:Name="TheWorld" Background="DarkGreen">
    <Button Content="MoveFirst" Click="Button_Click" />
    <ItemsControl ItemsSource="{Binding Entities}">
        <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding X}" />
                <Setter Property="Canvas.Top" Value="{Binding Y}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
</Canvas>

</Grid>

    public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        var worldViewModel = new WorldViewModel();
        DataContext = worldViewModel;
    }

    void Button_Click(object sender, RoutedEventArgs e)
    {
        var viewModel = DataContext as WorldViewModel;
        if(viewModel != null)
        {
            var entity = viewModel.Entities.First();
            entity.X +=10;
        }
    }
}

Viewmodels
  public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class WorldViewModel : ViewModelBase
{
    ObservableCollection<EntityVM> entities;

    public ObservableCollection<EntityVM> Entities {
        get { return entities; }
        set
        {
            entities = value;
            NotifyPropertyChanged("Entities");
        }
    }

    public WorldViewModel()
    {
        Entities = new ObservableCollection<EntityVM>();
        int y=0;
        for(int i=0; i<30; i++)
        {
            if(i %2 == 0)
            {
                Entities.Add(new BallVM(i*10, y+=20));
            }
            else
            {
                Entities.Add(new HouseVM(i*20, y+=20));
            }
        }
    }
}

public class EntityVM : ViewModelBase
{
    public EntityVM(double x, double y)
    {
        X = x;
        Y = y;
    }

    private double _x;
    public double X
    {
        get
        {
            return _x;
        }
        set
        {
            _x = value;
            NotifyPropertyChanged("X");
        }
    }

    private double _y;
    public double Y
    {
        get
        {
            return _y;
        }
        set
        {
            _y = value;
            NotifyPropertyChanged("Y");
        }
    }
}

public class BallVM : EntityVM
{
    public BallVM(double x, double y) : base(x, y)
    {
    }
}

public class HouseVM : EntityVM
{
    public HouseVM(double x, double y)  : base(x, y)
    {
    }
}


text:
Q: How to replace the Camunda Authentication with OAuth2 provider I was trying to write OAuth2 plugin for Camunda , I followed the interface

org.camunda.bpm.engine.impl.identity.ReadOnlyIdentityProvider

and I followed the process for LDAP, to replace the auth and get user list from Oauth2 provider and also the groups.
https://docs.camunda.org/manual/7.7/user-guide/process-engine/identity-service/
Is there any implantation is there for Camunda OAuth2 ?

A: Which Camunda deployment and which OAuth provider are you using?
Camunda offers an example for keycloak on GitHub:
https://github.com/camunda/camunda-bpm-identity-keycloak
The implementation for your provider would likely look very similar.
Have not QAed this, but you might also find inspiration here:
https://github.com/hobbstech/camunda-spring-oauth2-plugin/tree/master/src/main/java/io/github/hobbstech/camunda/oauth2/plugin


text:
Q: Set timeout to JAX-RS client with CXF I need to set a custom timeout to the following client or configuration:
import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.client.ClientConfiguration;

Client client = WebClient.client(api);
ClientConfiguration config = WebClient.getConfig(client);

I read this and especially this but I can't find those suggested property or methods in my objects. I'd rather not change the objects type.

A: import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
Client client = WebClient.client(api);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

A: I needed to add this to the code I posted before:
HTTPConduit conduit = config.getHttpConduit();
conduit.getClient().setReceiveTimeout(150000);
//conduit.getClient().setConnectionTimeout(120000);

And it worked. I just needed to set the receive timeout, but the connection timeout setting works too.


text:
Q: Homomorphisms from $\mathbb Z \rightarrow \mathbb Z_{6}$ Homomorphisms from $\mathbb Z \rightarrow \mathbb Z_{6}$
I have proven that the number of Homomorphisms from $\mathbb Z_6 \rightarrow \mathbb Z=6$
Is the reverse just simply $6$ also?
in $\mathbb Z_6$ we have $1+1+1+1+1+1=6=0$
let $f(1)=a \in \mathbb Z$
$f(1+1+1+1+1+1)=f(0)=0$
$6f(1)=0$
$6a=0 \in \mathbb Z_6$
So is $a=\mathbb Z$ or is $a=0,1,2,3,4,5$
Any explanation on this would be great.

A: How did you prove that $\left|\operatorname{Hom}(\mathbb{Z}_6,\mathbb{Z})\right| = 6$? We can state that for every $n \in \mathbb{N}$ $\left|\operatorname{Hom}(\mathbb{Z}_n,\mathbb{Z})\right| = 1$ which result to be the trivial homomorphism, since from the First Homomorphism Theorem
$ \mathbb{Z}_n / \operatorname{Ker}(\varphi) \cong \operatorname{Im}(\varphi) < \mathbb{Z}$, but all the subgroup of $\mathbb{Z}$ are of the form $d\mathbb{Z}$ which of course are infinite, and since $|\mathbb{Z}_n / \operatorname{Ker}(\varphi)| < +\infty$ we have $d = 0$ hence $\operatorname{Ker}(\varphi) = \mathbb{Z}_n$
Conversely to count $\left|\operatorname{Hom}(\mathbb{Z},\mathbb{Z}_6)\right|$ we know they are determined once assigned the image of a generator since $\mathbb{Z}$ is a cyclic group.
Because we can choose $\phi(1)$ in $|\mathbb{Z_{6}}| = 6$ ways there are 6 such homomorphisms.


text:
Q: Firebase Test Lab: ClassNotFoundException: Didn't find class "android.support.test.runner.AndroidJUnitRunner" Tests pass when executed from command line, but not in Firebase Test Lab.
FATAL EXCEPTION: main
Process: io.app, PID: 8460
java.lang.RuntimeException: Unable to instantiate instrumentation ComponentInfo{io.app.test/android.support.test.runner.AndroidJUnitRunner}:
java.lang.ClassNotFoundException: Didn't find class "android.support.test.runner.AndroidJUnitRunner" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/io.app.test-Lhy59NcEDyw4_BcWTLMjQw==/base.apk", zip file "/data/app/io.app-Pxsp6qUCO3AXUr6rsMhX1A==/base.apk"],nativeLibraryDirectories=[/system/lib, /system/vendor/lib]]

A: This happens when uploading the wrong androidTest APK to Firebase Test Lab. Use Android Studio to analyze the APK that you're uploading and check that classes.dex (or classes{i}.dex) has your tests.
Your test APK might be in a different directory: inside the build/ folder of a different module.

A: The testrunner specified in your manifest file must be present in the test APK (either passed as the --test argument to gcloud or uploaded in the FTL web console).


text:
Q: How to calculate the number of integers in a python string I want to calculate the number of integers in the string "abajaao1grg100rgegege".
I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.
Here is my attempt:
T = int(input())
for x in range(T):
    S = input()
    m = 0
    for k in S:
        if (k.isnumeric()):
            m += 1
print(m)

A: I'd use a very basic regex (\d+) then count the number of matches:
import re

string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2

A: Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:
result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))

In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:
def getNumbers(string):
    result = 0
    for i in range(len(string)):
        if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
            result += 1
    return result

A: You can use the regex library to solve this issue.
import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)

>>> ['1', '100']

You can check how many numbers you have on that list that the findall returned.
print (len(res))
>>> 2

In order to read more on python regex and the patterns, enter here

A: Not very Pythonic but for beginners more understandable:
Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.
Increase the counter only if the previous character was not a digit:
string = 'abajaao1grg100rgegege'
counter = 0                   # Reset the counter
was_digit = False             # Was previous character a digit?

for ch in string:
    if ch.isdigit():
        if not was_digit:     # previous character was not a digit ...
            counter += 1      # ... so it is start of the new number - count it!
        was_digit = True      # for the next iteration
    else:
        was_digit = False     # for the next iteration

print(counter)                # Will print 2

A: random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
  if (random[i].isnumeric()):
    z=i+1
    counter+=1
    while(z<length):
      if (random[z].isnumeric()):
        z=z+1
        continue
      else:
        break
    i=z
  else:
    i+=1
print ("No of integers",counter)


text:
Q: Python - Checking every item in a list against every other item efficiently I'm working on a game where each object should check if it is colliding with any other object. I have a single list of all the objects and a function which can determine if two objects are colliding and destroys them. The current method I'm using is very inefficient.
for i in list1:
    for j in list1:
        if collide(i, j):
            i.kill()
            j.kill()

Initially I removed both objects from the list after they were killed, but some collision occurred without detecting so I reverted back to this code. It works, but I'd like something more efficient.

A: first this is testing twice too much and also testing if one object collides with itself:
for i in list1:
    for j in list1:
        if collide(i, j):
            i.kill()
            j.kill()

This loops exactly len(list1)**2 times.
a very simple way to divide the number of tests by 2 (and avoiding testing against itself):
for i,obj1 in enumerate(list1):
   for j in range(i+1,len(list1)):
      obj2 = list1[j]
      if collide(obj1,obj2):
         obj1.kill()
         obj2.kill()

It takes advantage of the fact that collide(obj1,obj2) is the same as collide(obj2,obj1).
At this point, you probably want to break out the inner loop since obj1 is now dead. But that depends on what you want to do.
If an accurate collision test is expensive, you could consider a rougher check (distance, rectangle boundary, any quick method), so you can discard items which are too far away from each other without performing the "expensive" test.


text:
Q: CRM Plugin for Publish and Publish All messages I was wondering if we can write plugins that get executed for messages like "publish" and "publish all" in Dynamics CRM (any version). if so can you share any sample references for the same or code snippets.

A: This is a plugin that works for Publish and PublishAll messages and it will log the event using an entity that I created for this purpose (you can change to do whatever you want).
When the event is Publish, the plugin uses the ParameterXml parameter (MSDN) to log which components are being published. In the case of the PublishAll message, this parameter is not present so there's no detail (which makes sense because you're publishing all).
public class PublishPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        if (context.MessageName != "Publish" && context.MessageName != "PublishAll")
            return;

        string parameterXml = string.Empty;
        if (context.MessageName == "Publish")
        {
            if (context.InputParameters.Contains("ParameterXml"))
            {
                parameterXml = (string)context.InputParameters["ParameterXml"];
            }
        }

        CreatePublishAuditRecord(service, context.MessageName, context.InitiatingUserId, parameterXml);
    }

    private void CreatePublishAuditRecord(IOrganizationService service, string messageName, Guid userId, string parameterXml)
    {
        Entity auditRecord = new Entity("fjo_publishaudit");
        auditRecord["fjo_message"] = messageName;
        auditRecord["fjo_publishbyid"] = new EntityReference("systemuser", userId);
        auditRecord["fjo_publishon"] = DateTime.Now;
        auditRecord["fjo_parameterxml"] = parameterXml;

        service.Create(auditRecord);
    }
}

This is how it looks in CRM:

You can download the plugin project and CRM solution from my GitHub.

A: See here for a list of valid Dynamics CRM messages. Publish and PublishAll are both listed. They're also valid in all version of CRM from 2011 onward.
https://msdn.microsoft.com/en-us/library/gg328576.aspx
Just register your plugin like any other but use Publish or PublishAll for the message and leave the Entity as blank.
In the case of Publish, it seems by looking at the documentation that you can't narrow down which entity is being published. You'll have to take a look at what the Input Parameters give you to see if you can work out which entity you're dealing with, if you need it.


text:
Q: how to display the contents displayed in another html inside a div of the parent html file The below code shows that when the anchor tag is clicked the content related to that specific title is retrieved and shown in another html page name doc1.html.
The link that redirects it to next page in present in this file.
judge_civil.html file

    {% for data in law_data %} {% if data.law_type == 'civil' and
    data.law_category == 'limitations' %}

      {{data.title}}

    {% endif %} {% endfor %}

Here when the link is clicked the content that is associated with {{data.title}} is opened and displayed in a new html file dynamically using the primary key that i have passed along with it. The code in doc1.html is below

{{ object.judgements|safe}}

But now I want to display this content that is being displayed in doc1.html in the judge_civil.html inside the below :

I assume that this can only be done with javascript. I don't know javascript at all so if you can provide me the code to this task it will be really helpfull.
I am also providing the models and viwes and urls code if needed:
models.py
class Laws(models.Model):
    date= models.DateField(default=timezone.now)
    title= models.CharField(max_length=225, help_text="judgement title")
    judgements= RichTextField(blank=True, null= True)
    law_type= models.CharField(max_length=40, choices= type_of_law)
    law_category= models.CharField(max_length=60, choices= category)

    def __str__(self):
        return self.title

views.py
def judge_civil(request):
    law_data= Laws.objects.all().order_by('-date')

    return render(request, 'judge_civil.html', {'law_data': law_data} )

class Doc1DetailView(DetailView):
    model= Laws
    template_name = 'doc1.html'

urls.py
urlpatterns= [
        path('judge_civil',views.judge_civil, name='judge_civil'),
        path('doc1/<int:pk>/', Doc1DetailView.as_view(), name='doc1' ),
]

As I said before I don't know JavaScript at all so it would be appreciated if you write the JavaScript code as exactly what I've to do to achieve this. I've attached a image that should give you a more clear picture of what I want to do.
Thanks.

A: you can path it in { URL } so when came to file to { judge_civil.html file } , just call window.location.href and it will return current { URL }  with data passed to it


text:
Q: Run-time error 438 trying to pull a Dynamic array from an external excel sheet in VBA I am running my code from an excel file that is intended to aggregate data from a bunch of other excel file. I want to pull an array from an excel file called "Cases Received" but I get a runtime error 438: Object does not support this property or method.
Dim srcWarehouse As Workbook
'Storing the worksheet with my desired data as a variable with the object type workbook'
Set srcWarehouse = Workbooks.Open("C:\Users\christian.pignataro\Documents\Timeline Accuracy project\Cases Received 2021.xlsx", True, True)

Dim numbers() As Integer, size As Integer, i As Integer

'This next line is the line that throws the error it is intended to use the worksheet function
'CountA to count the length of the array since the size of the listed data on the Cases
'Received workbook will change each month
size = srcWarehouse.Worksheets("Sheet1").WorksheetFunction.CountA(Worksheets(1).Columns(1))

ReDim numbers(size)
For i = 1 To size
    numbers(i) = srcWarehouse.Worksheets("Sheet1").Cells(i, 1).Value
Next i

MsgBox numbers(size)


text:
Q: Testing Delphi DLL crashes VB6 IDE I've had my first go at writing a DLL in Delphi. So far so good. By using a typelib I've been able to pass Widestrings to and from the DLL without difficulty.
What's curious at the moment is that I'm using VB6 as the testbed, and every time I run a test within the IDE, the program runs and then the IDE process suddenly disappears from memory - no error messages, nothing. If I step through the code, everything works fine until I execute the last line, then the IDE disappears.
By contrast, when I compile the test to an EXE the program runs to its end, without error messages etc.
Has anyone had this problem before and is there an obvious solution that's staring me in the face?
Source code below, in case it matters:
-- project
library BOSLAD;

uses
  ShareMem,
  SysUtils,
  Classes,
  BOSLADCode in 'BOSLADCode.pas';

exports
  version,
  DMesg,
  foo;
{$R *.res}

begin
end.

-- unit
unit BOSLADCode;

interface
  function version() : Double; stdcall;
  procedure DMesg(sText : WideString; sHead : WideString ); stdcall;
  function foo() : PWideString; stdcall;

implementation
  uses Windows;

  function version() : Double;
  var
    s : String;
  begin
    result := 0.001;
  end;

  procedure DMesg( sText : WideString; sHead : WideString);
  begin
    Windows.MessageBoxW(0, PWideChar(sText), PWideChar(sHead), 0);
  end;

  function foo() : PWideString;
  var s : WideString;
  begin
    s := 'My dog''s got fleas';
    result := PWideString(s);
  end;
end.

-- typelib
 // This is the type library for BOSLAD.dll
      [
      // Use GUIDGEN.EXE to create the UUID that uniquely identifies
      // this library on the user's system. NOTE: This must be done!!
         uuid(0C55D7DA-0840-40c0-B77C-DC72BE9D109E),
      // This helpstring defines how the library will appear in the
      // References dialog of VB.
         helpstring("BOSLAD TypeLib"),
      // Assume standard English locale.
         lcid(0x0409),
      // Assign a version number to keep track of changes.
         version(1.0)
      ]
      library BOSLAD
      {

      // Now define the module that will "declare" your C functions.
      [
         helpstring("Functions in BOSLAD.DLL"),
         version(1.0),
      // Give the name of your DLL here.
         dllname("BOSLAD.dll")
      ]
      module BOSLADFunctions
      {
[helpstring("version"), entry("version")] void __stdcall version( [out,retval] double* res );
[helpstring("DMesg"), entry("DMesg")] void __stdcall DMesg( [in] BSTR msg, [in] BSTR head );
[helpstring("foo"), entry("foo")] void __stdcall foo( [out,retval] BSTR* msg );
      } // End of Module
      }; // End of Library

I moved the declaration of the WideString outside of the function in which I had declared it, in the expectation that that would increase the lifetime of the variable to longer than just the lifetime of the foo function. It made no difference whatsoever.
Likewise I commented out of the VB6 the call to the foo function. That made no difference either. No matter what I do, VB6 IDE dies after the last line of code is executed.
Something apart from pointers to local variables is the cause. But what?

A: result := PWideString(s);

You are returning pointer to a local variable here. It immediately becomes invalid.

A: To elaborate on GSerg's answer:
result := PWideString(s);

you'd think it would be ok because s was initialized with a string literal... but wide strings in Delphi are not reference counted like normal strings, so s actually holds a bit of dynamically allocated heap memory, and as soon as the function returns this memory can be reused :(
The following should be ok though:
function foo() : PWideString;
const s : WideString = 'My dog''s got fleas';
begin
  result := PWideString(s);
end;

A: Creating DLLs on the delphi.wikia.com site has the answer I've been looking for. And the solution too.
For example, Delphi automatically allocates and frees the memory for storing your strings, it knows when they are no longer needed etc. The same applies for e.g. Visual Basic, but both do it in different ways. So, if you were to pass a string that was allocated by Visual Basic to a DLL written in Delphi you would end up in big trouble, because both would now try to manage the string and would get into each other's hair.
The solution is to use FastMM and it works brilliantly!! I now have a replacement BORLNDMM.DLL in with my project and everything just works.

A: I just got thoroughly straightened out on this one, thanks to Rob Kennedy on news:comp.lang.pascal.delphi.misc
He said, amongst other things that:

*

*This DLL does not need ShareMem, SysUtils, or Classes.

*You've taken a WideString and told the compiler that it's really a pointer to a WideString. You're lying to the compiler. It doesn't care, but the caller of this function probably does.

So the revised code, which works fine without ShareMem (and SysUtils and Classes which were added by the DLL Wizard as it happens) is as follows:
library BOSLAD;
uses
  BOSLADCode in 'BOSLADCode.pas';
exports
  version,
  DMesg,
  foo;
{$R *.res}
begin
end.

BOSLADCode.pas:
unit BOSLADCode;

interface
  function version() : Double; stdcall;
  procedure DMesg(sText : PWideChar; sHead : PWideChar ); stdcall;
  function foo() : PWideChar; stdcall;

implementation
  uses Windows;

  var s : WideString;

  function version() : Double;
  begin
    result := 0.001;
  end;

  procedure DMesg( sText : PWideChar; sHead : PWideChar);
  begin
    Windows.MessageBoxW(0, sText, sHead, 0);
  end;

  function foo() : PWideChar;
  begin
    s := 'My dog''s got fleas';
    result := PWideChar(s);
  end;
end.

boslad.odl:
// This is the type library for BOSLAD.dll
[
uuid(0C55D7DA-0840-40c0-B77C-DC72BE9D109E),
helpstring("BOSLAD TypeLib"),
lcid(0x0409),
version(1.0)
]
library BOSLAD
{
[
helpstring("Functions in BOSLAD.DLL"),
version(1.0),
dllname("BOSLAD.dll")
]
module BOSLADFunctions
{
[helpstring("version"), entry("version")]
    void __stdcall version( [out,retval] double* res );
[helpstring("DMesg"), entry("DMesg")]
    void __stdcall DMesg( [in] BSTR msg, [in] BSTR head );
[helpstring("foo"), entry("foo")]
    void __stdcall foo( [out,retval] BSTR* msg );
}
};

test.bas:
Sub Main()
    Dim cfg As New CFGProject.cfg
    cfg.Load "test.cfg"
    Dim s As String
    s = cfg.Recall("msg")
    DMesg s, "" & version
    s = foo
    DMesg s, "" & version
End Sub

test.cfg
msg=毅訜訝

All of that works perfectly. VB6's IDE happily runs the DLL and the MsgBoxs appear with everything as it should be.

A: I think we can close this one. The code below seems to be enough to keep the folk on news:comp.lang.pascal.delphi.misc happy and I really need to move on from concept testing to actually doing something with it.
BOSLAD.bdsproj:
library BOSLAD;

uses
  BOSLADCode in 'BOSLADCode.pas';

exports
  version,
  DMesg,
  foo;
{$R *.res}

begin
end.

BOSLADCode.pas:
unit BOSLADCode;

interface
  function version() : Double; stdcall;
  procedure DMesg(const sText : WideString; const sHead : WideString ); stdcall;
  function foo() : PWideChar; stdcall;

implementation
  uses Windows, ActiveX;

  function version() : Double;
  begin
    result := 0.001;
  end;

  procedure DMesg( const sText : WideString; const sHead : WideString);
  begin
    Windows.MessageBoxW(0, PWideChar(sText), PWideChar(sHead), 0);
  end;

  function foo() : PWideChar;
  var s : WideString;
  begin
    s := 'My dog''s got fleas';
    result := SysAllocString(PWideChar(s));
  end;
end.

Now VB's happy and I don't get weird IDE crashes.