text:
Q: Exclude a set of files from htaccess rewrite rule I'm using the below htaccess rewrite rules to redirect users to the main website if they are accessing files directly and not logged into my website. With this the issue is that when any one share a post to social media the thumbnail picture is not showing in share links (eg:- facebook share).
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https://(www\.)?mywebsite\.com/ [NC]
RewriteCond %{REQUEST_URI} !hotlink\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov) [NC]
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ https://mywebsite.com/ [NC]

The Images which I want to show as a thumbnail for shared links have a common filename format. All ends with -FI.jpg
So is it possible to exclude all those files which ends with -FI.jpg in htaccess rewrite rule? If yes, how to do it?
Thanks.

A: Add one RewriteCond before RewriteRule:
RewriteCond %{REQUEST_URI} !-FI\.jpg$ [NC]


text:
Q: How to interpret the adjoint? Let $V \neq \{\mathbf{0}\}$ be a inner product space, and let $f:V \to V$ be a linear transformation on $V$.
I understand the definition1 of the adjoint of $f$ (denoted by $f^*$), but I can't say I really grok this other linear transformation $f^*$.
For example, it is completely unexpected to me that to say that $f^* = f^{-1}$ is equivalent to saying that $f$ preserves all distances and angles (as defined by the inner product on $V$).
It is even more surprising to me to learn that to say that $f^* = f$ is equivalent to saying that there exists an orthonormal basis for $V$ that consists entirely of eigenvectors of $f$.
Now, I can follow the proofs of these theorems perfectly well, but the exercise gives me no insight into the nature of the adjoint.
For example, I can visualize a linear transformation $f:V\to V$ whose eigenvectors are orthogonal and span the space, but this visualization tells me nothing about what $f^*$ should be like when this is the case, largely because I'm completely in the dark about the adjoint in general.
Similarly, I can visualize a linear transformation $f:V\to V$ that preserves lengths and angles, but, again, and for the same reason, this visualization tells me nothing about what this implies for $f^*$.
Is there (coordinate-free, representation-agnostic) way to interpret the adjoint that will make theorems like the ones mentioned above less surprising?

1 The adjoint of $f:V\to V$ is the unique linear transformation $f^*:V\to V$ (guaranteed to exist for every such linear transformation $f$) such that, for all $u, v \in V$,
$$ \langle f(u), v\rangle  = \langle u, f^*(v)\rangle \,.$$

A: The adjoint allows us to go from an active transformation view of a linear map to a passive view and vice versa.  Consider a map $T$ and a vector $u$ and a set of basis covectors $e^i$ for $i \in 1, 2, \ldots$.  Given the definition of the adjoint, we have
$$\left[\underline T(u), e^i \right] = \left[u, \overline T(e^i) \right]$$
where the commonly used bracket notation $[x, f]$ means $f(x)$.
On the left, we're actively transforming $u$ to a new vector and evaluating components in some pre-established basis.  On the right, we're passively transforming our space to use a new basis and evaluating $u$ in terms of that basis.  So for each active transformation, there is a corresponding (and equivalent)  passive one.
That said, while I think this can help identify the meaning of the adjoint, I don't see how this helps make intuitive the theorems you described.

A: It's difficult to give an intuitive description of the adjoint. Note that the adjoint is here even before we have scalar products. It's just that a scalar product allows to interpret the adjoint of a map $A:\ V\to V$ in one and the same space $V$.
A linear map $A:\ V\to W$ from one vector space $V$ to some other vector space $W$ (of any dimensions) produces for each vector $x \in V$  a vector $y:=Ax\in W$.
Assume now that on $W$ a linear function $\phi:\ W\to{\mathbb R}$, i.e., an element of $W^*$, is given, which assigns, e.g., to each point $y\in W$ a temperature value $\phi(y)$, or computes for each $y\in W$ the first coordinate with respect to some basis of $W$. Then the function
$$\psi:\quad V\to{\mathbb R},\qquad x\mapsto\phi\bigl(Ax\bigr)$$
computes for each point $x\in V$ the temperature felt at $Ax\in W$, "even before $x$ is actually mapped to $W$". In this way we can regard $\psi$ as a "virtual" temperature distribution on $V$. It is obvious that $\psi$ is a linear function from $V$ to ${\mathbb R}$, i.e., an element of $V^*$.
What we have described here for one $\phi\in W^*$ can of course be done with every $\phi\in W^*$: For each such $\phi$ we shall get a corresponding $\psi\in V^*$. All in all the map $A:\ V\to W$ given at the beginning induces a certain map $$W^*\to V^*, \quad \phi\to\psi\ .$$
This map is called the transpose of $A$ and is denoted by $A^*$. By definition we have the identity
$$A^*\phi.x\ =\ \phi. Ax\qquad\forall x\in V,\ \forall\phi\in W^*\ .$$
Here the . means that the linear functional on the left of the dot is applied to the vector on the right of the dot.
An example: Assume that $(e_k)_{1\leq k\leq n}$ is a basis in $V$ and $(f_i)_{1\leq i\leq m}$ is a Basis in $W$. Then $A$ has a certain matrix $[a_{ik}]$ with respect to these bases. Now  let $$\phi:=f_1^*:\quad y\mapsto y_1\tag{1}$$
be the functional that computes the first coordinate of any given vector $y\in W$. Then $\phi.Ax$ is the first coordinate $y_1$ of the vector $y:=Ax$. We all know that $$y_1=\sum_{k=1}^n a_{1k} x_k\ .\tag{2}$$ Since we can write $x_k$ as $x_k=e_k^*.x$ we can interpret $(2)$ as $$A^*\phi.x=\phi.Ax=\sum_{k=1}^n a_{1k} e_k^*.x\qquad(x\in V)\ ,$$
or, given the definition $(1)$ of $\phi$:
$$A^* f_1^*=\sum_{k=1}^n a_{1k} e_k^*\ .$$

A: For simplicity, let me consider only the finite-dimensional picture. In the infinite-dimensional world, you should consider bounded maps between Hilbert spaces, and the continuous duals of Hilbert spaces.
Recall that an inner product on a real [complex] vector space $V$ defines a canonical [conjugate-linear] isomorphism from $V$ to its dual space $V^\ast$ by $v \mapsto (w \mapsto \langle v,w\rangle)$, where I shamelessly use the mathematical physicist's convention that an inner product is linear in the second argument and conjugate-linear in the first; let us denote this isomorphism $V \cong V^\ast$ by $R$, so that $R(v)(w) := \langle v,w\rangle$.
Now, recall that a linear transformation $f : V \to W$ automatically induces a linear transformation $f^T : W^\ast \to V^\ast$, the transpose of $f$, by $\phi \mapsto \phi \circ f$; all $f^T$ does is use $f$ in the obvious way to turn functionals over $W$ into functionals over $V$, and really represents the image of $f$ through the looking glass, as it were, of taking dual spaces. However, if you have inner products on $V$ and $W$, then you have corresponding [conjugate-linear] isomorphisms $R_V : V \cong V^\ast$ and $R_W : W \cong W^\ast$, so you can use $R_V$ and $R_W$ to reinterpret $f^T : W^\ast \to V^\ast$ as a map $W \to V$, i.e., you can form $R_V^{-1} \circ f^T R_W : W \to V$. If you unpack definitions, however, you'll find that $R_V^{-1} \circ f^T \circ R_W$ is none other than your adjoint $f^\ast$. So, given fixed inner products on $V$ and $W$, $f^\ast$ is simply $f^T$, arguably a more fundamental object, except reinterpreted as a map between your original vector spaces, and not their duals. If you like commutative diagrams, then $f^T$, $f^\ast$, $R_V$ and $R_W$ all fit into a very nice commutative diagram.
As for the specific cases of unitary and self-adjoint operators:

*

*If you want to be resolutely geometrical about everything, the fundamental notion is not the notion of a unitary, but rather that of an isometry, i.e., a linear transformation $f : V \to V$ such that $\langle f(u),f(v)\rangle = \langle u,v\rangle$. You can then define a unitary as an invertible isometry, which is equivalent to the definition in terms of the adjoint. In fact, if you're working on finite-dimensional $V$, then you can check that $f$ is unitary if and only if it is isometric.

*In light of the longish discussion above, an operator $f : V \to V$ is self-adjoint if and only if $f^T : V^\ast \to V^\ast$ is exactly the same as $f$ after applying the [conjugate-linear] isomorphism $R_V : V \to V^\ast$, i.e., $f = R_V^{-1} \circ f^T \circ R_V$, or equivalently, $R_V \circ f = f^T \circ R_V$, which you can interpret as commutativity of a certain diagram. That self-adjointness implies all these nice spectral properties arguably shouldn't be considered obvious---at the end of the day, the spectral theorem, even in the finite-dimensional case, is a highly non-trivial theorem in every respect, especially conceptually!
I'm not sure that my overall spiel about adjoints and transposes is all that convincing, but I stand by my statement that the notion of isometry is the more fundamental one geometrically, one that happens to yield the notion of unitary simply out of the very definition of an adjoint, and that the spectral properties of a self-adjoint operator really are a highly non-trivial fact that shouldn't be taken for granted.

A: Here's a bit of intuition for the spectral theorem.  Suppose $V$ is a finite dimensional inner product space over $\mathbb C$ and $T:V \to V$ is self-adjoint. It's easy to show that all the eigenvalues of $T$ are real and that eigenvectors corresponding to distinct eigenvalues are orthogonal.
Typically all the eigenvalues of $T$ are distinct.  (It's in some sense an extraordinary coincidence if two roots of the characteristic polynomial coincide.)  In this case, we see immediately that there is an orthonormal basis of eigenvectors for $T$.
If not all eigenvectors of $T$ are distinct, we can perturb $T$ slightly to obtain a self-adjoint transformation $\tilde{T}$ which does have an orthonormal basis of eigenvectors.  By considering a sequence of slight perturbations $\tilde{T}_k$ which converges to $T$, we can hope to obtain a sequence of orthonormal bases which will converge to an orthonormal basis of eigenvectors of $T$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load RSA private key generated by openssl to MacOS SecKeyRef fails I am working on a project that needs to read a RSA private key (DER format) into a MacOS's SecKeyRef object.
I generate the key by
openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -outform DER -out private.der

I load the private.der to MacOS by using SecKeyCreateWithData:
unsigned char *keyBytes; // contains all the bytes from the file "private.der"
int keyBytesLen; // length of the data loaded
NSData keyData = [NSData dataWithBytes:keyBytes length:keyBytesLen];
NSDictionary* options = @{(id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
                          (id)kSecAttrKeyClass: (id)kSecAttrKeyClassPrivate,
                          (id)kSecAttrKeySizeInBits: @1024};
SecKeyRef privateKey = SecKeyCrecateWithData((__bridge CFDataRef) keyData, (__bridge CFDictionaryRef) options, &error);

OSstatus status = SecKeyDecrypt(privateKey, .... some encrypted message);
// status returns -50 (errSecParam)

So I notice the privateKey is loaded successfully, but it fails to decrypt the encrypted message. I am 100% sure other parameters I have put into SecKeyDecrypt() function is correct because it works if I generate the privateKey by macOS's built-in function rather than loading from a DER-format file generated by openssl.
I also notice that when I dump the key (binary format), the first few bytes (version header) is different from the key generated by MacOS's built-in function and openssl. If the key is generated by MacOS (ex: SecKeyGeneratePair) and outputed by SecKeyCopyExternalRepresentation, the first few bytes look like:
3082 025d 0201 0002 8181 ...

while the key generated by openssl looks like:
3082 025c 0201 0002 8181 ...

I know (based on PKCS#1) that these bytes represent the "version" of the private key but not sure how to interpret it.
Any help or similar working example to load key generated by openssl to MacOS's API will be appreciated


text:
Q: Bootstrap 3 - jerky scroll in Chrome and I've edited fair amount of CSS, and when I tred to test it in Chrome, I've noticed when I click on the upper left link and try to scroll down, instead of scrolling I get this weird wobble-jerky effect.
I thought I did something wrong in my coding so I went back to the original template in the download directory and on the template's website live preview, and it still displays the same error.
You can see it in live preview here (it's faster than me posting jsfiddle link) -  bootstrap freelance tempalte
Click on the upper left link and try to scroll down, you should see the error. In Firefox the website doesn't move or wobble, it stays "frozen" as you scroll the mousewheel down. The problem disappears when you scroll again for the second time.
How do I get rid of it, is there a way to identify what's causing it? Thanks for any help.

A: The issue is the script below (with the code below it).
When you click on that link, the .animate() function is executing for 1.5 seconds to automatically scroll to the top of the page, even if you are already at the top of the page. So after clicking the link JavaScript is scrolling up while you are trying to scroll down which gives you that jerky effect.
Removing this code will resolve the issue, but then you will loose the nice easing page scrolling functionality.
I'm sure there is a way to stop the .animate() function as soon as you hit the top of the page, but I'm not sure exactly the best way to do that... maybe someone else can help with that part.
This is one of those classic "Its a feature, not a bug" scenarios.
<script src="js/freelancer.js"></script>
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});


text:
Q: SIMPLE Javascript code to display data from a single field in a Google Spreadsheet First off, I am NOT a professional programmer, which is why I am here for help, so thanks in advance for your time and patience.  I need a bit of code for a website that will call and display information from a specific field in a published Google spreadsheet, to be displayed via HTML, through javascript or some other similar method.
Looking around, there seems to be several ways of doing this, but all of the examples and tricks I can find are a bit beyond my expertise, and my efforts at applying several of those methods have, frankly, failed miserably. I have searched through previous questions, but they all cite examples that are way more complicated than what I need.
If someone could cite me an easy example, I'd greatly appreciate it. (The simpler the better.) In the meanwhile, I will continue to experiment to see what I can do.

A: This is a duplicate of How can I access Google Sheet spreadsheets only with Javascript?
But since that example is not trivial for beginners, here is the code that will show the second cell of the spreadsheet using the code from the answer above

*

*Go to https://github.com/mikeymckay/google-spreadsheet-javascript and download the file google-spreadsheet.js

*Edit that file with a text editor and change

*

*this.jsonCellsUrl = "http:// to this.jsonCellsUrl = "// and

*this.jsonListUrl = "http://  to this.jsonListUrl = "//
to not have mixed http and https in your page

*Change the var url in the below to point your sheet

FIDDLE
<!DOCTYPE html>

<title>Spreadsheet example</title>

Here is the result:


text:
Q: How to create SQL table properly? I'm trying to create a SQL table with the following syntax in MySQL Workbench (in Mac OS),
CREATE TABLE orders (

        order_id                    INT NOT NULL PRIMARY KEY,
        company_id                  INT  NOT NULL,
        customer_id                 INT NOT NULL,
        order_number                VARCHAR(200),
        order_date                  TIMESTAMP NOT NULL,
        created                     TIMESTAMP NOT NULL,
        order_status                INT NOT NULL,

        CONSTRAINT orders_fk_company
            FOREIGN KEY (company_id) REFERENCES companies (company_id),

        CONSTRAINT orders_fk_customer
            FOREIGN KEY (customer_id) REFERENCES customers (customer_id)

    );

When I'm trying to execute this script, I'm getting the following message,
Error code: 1067. Invalid default value for 'created'

What is the issue here and how to create the table properly ? I have other 2 tables namely companies and customers provided below. There are executing properly and no issue there.
CREATE TABLE companies (

company_id                  INT     NOT NULL PRIMARY KEY,
company_name                VARCHAR(50)         NOT NULL,
contact_name                VARCHAR(50)         NOT NULL,
contact_phone               VARCHAR(30)         NOT NULL,
contact_email               VARCHAR(50)         NOT NULL,
created                     DATETIME            NOT NULL

);

CREATE TABLE customers (

customer_id                 INT             NOT NULL PRIMARY KEY,
company_id                  INT                NOT NULL,
customer_name               VARCHAR(100)        NOT NULL,
customer_company            VARCHAR(100),
CONSTRAINT customers_fk_company
    FOREIGN KEY (company_id) REFERENCES companies (company_id)

);


text:
Q: Is it possible to have a different language when calling my odata service than the logon language of my SAP UI5 application? I would like to call my odata service in a way that the system language of the NetWeaver gateway is different from the logon language in my SAP UI5 application
For example, a user logs into the UI5 application in German but when the service is called, I want the backend system-language to be in English.
Is there a way to do that, maybe by setting a specific header property in the model or a url parameter?
Thanks in advance.

A: ok, so you log into a app.. which is in german and you want to call your oData Service based on the backend system language? or what you mean with
"I want the backend system-language to be in English." ?
as parameter in your app sap-language=DE let this as default and set the backend language to en

A: For your question, I can relate two ways possible -

*

*Either you using some native programming language (in my case it is android (Java/Kotlin)):

use accept-language header key to pass
the desired language short-form. in the case of German, it is 'DE'.

*Or you are running services on the browser:

use sap-language as an additional header parameter in your URL and pass the desired language.

URL example:
http://serverhost:port/namespace/storename/XYZSet?sap-language='DE'


text:
Q: Excel / Power Bi – Group fixed numbers in dozens like price filters in eshops I have a table of data in Microsoft Power Bi:
IS-1   32
IS-2   76
IS-3   27
IS-4   35
IS-5   14
IS-6   81

And I need to create a new column with a function which will group those numbers in decaded so they can be easily represented in charts.
IS-1   32    31-40
IS-2   76    71-80
IS-3   27    21-30
IS-4   35    31-40
IS-5   14    11-20
IS-6   81    81-90

I know that it will be almost the same for Microsoft Excel so you can provide an Excel function.

A: Found it:
Group Size = IF(ISNUMBER(Data[Size]);CEILING(Data[Size]; 10)-9&" - "&CEILING(Data[Size];10))

(Microsoft Power Bi Formula)


text:
Q: Finding columns in dataframe with specific number of values in R I have a dataframe(data.table) with over 3000 columns. I need to find out the columns in my dataframe that have only 2 and less than 2 values in them. I then after extracting those columns with 2 and less then 2 values I want to drop them out of the original data frame.
I illustrate as follows:
Original data frame
Month   A       B         C
Jan-00  0.007   NA       1758.27
Feb-00  0.004   NA       1310.43
Mar-00  0.004   NA       1260.89
Apr-00  0.004   0.0002   1137.34
May-00  0.005   6.05E-05 1595.78
Jun-00  0.003   NA       4968.89
Jul-00  0.007   NA       NA
Aug-00  0.005   NA       NA
Sep-00  0.004   NA       NA

Desired output
     Month    A         C
    Jan-00  0.007   1758.27
    Feb-00  0.004   1310.435
    Mar-00  0.004   1260.89
    Apr-00  0.004   1137.342105
    May-00  0.005   1595.78125
    Jun-00  0.003   4968.895238
    Jul-00  0.007   NA
    Aug-00  0.005   NA
    Sep-00  0.004   NA

I would appreciate your help in this regard.

A: We can use Filter
Filter(function(x) sum(!is.na(x))>2, df1)
#   Month     A       C
#1 Jan-00 0.007 1758.27
#2 Feb-00 0.004 1310.43
#3 Mar-00 0.004 1260.89
#4 Apr-00 0.004 1137.34
#5 May-00 0.005 1595.78
#6 Jun-00 0.003 4968.89
#7 Jul-00 0.007      NA
#8 Aug-00 0.005      NA
#9 Sep-00 0.004      NA

Or
df1[colSums(!is.na(df1))>2]

If the dataset is data.table,
 library(data.table)
 setDT(df1)[,unlist(df1[, lapply(.SD, function(x)
                        sum(!is.na(x))>2)]), with=FALSE]

Or
 setDT(df1)[, Filter(function(x) sum(!is.na(x))>2, .SD)]


text:
Q: Laravel cashier with stripe : no such plan error? I have created a Plans table with some data. When I am trying to subscribe the plans, Laravel-Cashier says : No Such Plan.
What I am missing?
I also created a plan through Stripe dashboard, but nothing changed. How can I overcome this issue?
Here is my code :
Plans table have following fields:
protected $fillable = [
    'id',
    'name',
    'stripe_plan',
    'cost',
    'interval',
    'currency',
    'description'
];

And controller code is:
public function create(Request $request)
{
    // Getting choosed plan
    $plan = Plans::findOrFail($request->plan);

    $entity->newSubscription($plan->id,$plan->stripe_plan)->create($request->stripeToken);
    //I tried put hardcoded plans, but still same error
    //    $entity->newSubscription('phone', 'phone')->create($request->stripeToken);
    return redirect()->route('plans')->with('success', 'Your plan subscribed successfully');
}

A: I passed the plan_id as second param of newSubscription method, which i created in stripe portal and working fine. Also passing plan-name was not working, so i passrd the id of plan like this
$entity->newSubscription('primary', 'plan_EBttg1ziShQ51I')->create($request->stripeToken, [ ]);
but it's strange for me, bcoz if we have multiple plans then how can i pass different plan...


text:
Q: How to annotate the area of a polyline in autocad command / macro Does anyone know of macro or custom command I can make to quickly annotate the area of a polyline in autocad?
I'm doing a project where I need to measure the lot and house size of several city blocks.  I've got a drawing going but I don't want to measure and write out the area of each site, that will take to long.  I've seen custom commands in the past that quickly do this kind of thing but I don't know how to make my own.
And I'm desperately avoiding doing it by hand one at a time as most likely I will need to make adjustments to my design later on.

A: The best method I can think of is to utilize the MTEXT command and use a FIELD to link the Area of the Polyline to the MTEXT box.

Type FIELD at the command line, choose Object, select your Polyline and you will see the Area property.

Here is a link on the CADTutor site that covers it a bit more in depth along with a link to a forum post that has this automated via a Lisp routine.
http://www.cadtutor.net/forum/archive/index.php/t-46628.html


text:
Q: Get item by ID in Sitecore 6.5 I am on Sitecore 6.5.
The below code is working fine but I don't understand how. The GetItem() method has six overload functions where it takes string values as just item paths.
In this case it's taking in an id as a string and correctly returning the item (the location is Sitecore droplink field). Am I missing something?
private Sitecore.Data.Items.Item LocationItem
{
    get
    {
        return Sitecore.Context.Database.GetItem(Item["Location"]);
    }
}

A: Sitecore can take a path or an ID as the string. Item["Location"] will contain a GUID (as the field type is a droplink), which you're currently retrieving as a string.

A: This is expected functionality.
You can pass both ID or path to this method, however documentation may not be clear on this.

A: The string parameter for GetItem() can be an ID or a Path.
Both will work.


text:
Q: JQuery Collision Detection Not sure if I'm on the right track here, but I figured this should work:
    function collides(a, b) {
              return a.x  b.x &&
                a.y  b.y;
    }
    function handleCollisions() {
      $('#player').forEach(function(player) {
        $('#powerUp').forEach(function(powerup) {
          if(collides(player, powerup)) {
           $('#player').hide();
          }
        });
      });
    }
    handleCollisions();
    }

Basically I have my player running around the game and the object at a fix position. When the player collides with the object he should disappear. I will provide a fiddle if needed but I figured that there is something visibly wrong with the code. Any suggestions?
Edit:
  function collides(a, b) {
              return a.offset()  b.offset() &&
                a.position()  b.position();
    }

    function handleCollisions() {
        if (collides($('#player'), $('#powerUp'))) {
           $('#player').append("
collided
"); // hide player onCollision
          }
    }
    handleCollisions();
    }

`


text:
Q: Wordpress pagination doesn't work on PLAIN Permailnk I have created custom post in my Wp Page, and I set Pagination for this Page. But when I changed Permalink in PLAIN, pagination doesn't work. Url of page displayed in this form: "domain/wordpress/?page_id=2575&lang=de#038;lang=depage/2"
Code of Pagination is:
function custom_pagination($numpages = '', $pagerange = '', $paged='') {

if (empty($pagerange)) {
$pagerange = 2;
}

global $paged;
if (empty($paged)) {
$paged = 1;
}
  if ($numpages == '') {
   global $wp_query;
   $numpages = $wp_query->max_num_pages;
    if(!$numpages) {
      $numpages = 1;
     }
   }

$pagination_args = array(
'base'            => get_pagenum_link(1) . '%_%',
'format'          => 'page/%#%',
'total'           => $numpages,
'current'         => $paged,
'show_all'        => False,
'end_size'        => 1,
'mid_size'        => $pagerange,
'prev_next'       => True,
'prev_text'       => __('«'),
'next_text'       => __('»'),
'type'            => 'plain',
'add_args'        => false,
'add_fragment'    => ''
);

$paginate_links = paginate_links($pagination_args);

 if ($paginate_links) {
   echo "";
   echo "Page " . $paged . " of " .   $numpages . " ";
   echo $paginate_links;
  echo "";
}

}

A: Default WP query var for page number is "paged". In url = wordpress/?paged=2575
EDIT: if paginate_links() doesn't generate desired format, it's because your input args. 'base' determines url structure and "%_%" is placeholder for 'format', which is in your case set to non-plain. Try array( 'format' => '?paged=%#%' ).
UPDATE: change this code:
global $paged;
if (empty($paged)) {
    $paged = 1;
}

for
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

You have to include "paged" variable in url to make sure, it will load it and paste it into links created inside your pagination. Post me url in href="" attribute from your actual pagination.


text:
Q: Get the Count of a SubQuery I need to count the result of some SQL query which I have no control over.  My idea is to wrap the inner SQL with a wrapper count query.  The outer SQL is quite simple, here is what I got:
select count(*) from ( x ) as CountQuery

where x is whatever the inner SQL goes.  The problem with this is some query would crash, namely IF ELSE END.
How do I craft a wrapper SQL that will successfully wrap around any SQL?
Here is an example of one of the inner SQL I need to count:
IF null <> 'PIPELINE_STAGE'
BEGIN
WITH cnts AS
(
SELECT
       o.[OPPORTUNITY_ID]
      ,[OPPORTUNITY_NAME]
      ,[OPPORTUNITY_DETAILS]
      ,[IMAGE_URL]
      ,OPPORTUNITY_VALUE
      ,[PROBABILITY]
      ,[BID_CURRENCY]
      ,[BID_AMOUNT]
      ,[BID_TYPE]
      ,[BID_DURATION]
      ,[FORECAST_CLOSE_DATE]
      ,o.[CATEGORY_ID]
      ,c.CATEGORY_NAME
      ,c.BACKGROUND_COLOR
      ,o.[PIPELINE_ID]
      ,o.[STAGE_ID]
      ,[OPPORTUNITY_STATE]
      ,[RESPONSIBLE_USER_ID]
      ,u.[First_Name]
      ,u.[Last_Name]
      ,o.[VISIBLE_TO]
      ,o.VISIBLE_TEAM_ID
      ,o.[DATE_CREATED_UTC]
      ,o.[DATE_UPDATED_UTC]
      ,o.OWNER_USER_ID
      ,o.IMPORT_ID
      ,Follow_id
       ,ROW_NUMBER() OVER( ORDER BY CASE WHEN @sortOrder = 'OPPORTUNITY_NAME' THEN OPPORTUNITY_NAME END,
  CASE WHEN @sortOrder = 'RESPONSIBLE_USER' THEN ISNULL(u.[FIRST_Name], 'zz') END,
  CASE WHEN @sortOrder = 'FORECAST_CLOSE_DATE' THEN Forecast_Close_Date END,
  CASE WHEN @sortOrder = 'DATE_CREATED' THEN o.[DATE_CREATED_UTC]  END,
  CASE WHEN @sortOrder = 'FORECAST_CLOSE_DATE_DESC' THEN Forecast_Close_Date END DESC,
  CASE WHEN @sortOrder = 'DATE_CREATED_DESC' THEN o.[DATE_CREATED_UTC]  END DESC
       ) as intRow,
     COUNT(o.INSTANCE_ID) OVER() AS Count
  FROM [Insightly].[dbo].[Opportunity] o with (nolock)
  LEFT JOIN [Insightly].[dbo].[Reference.Category] c with (nolock)
  on o.CATEGORY_ID = c.CATEGORY_ID AND c.INSTANCE_ID = @instanceId
  LEFT JOIN [Insightly].[dbo].[User] u WITH (NOLOCK)
  ON u.USER_ID = o.RESPONSIBLE_USER_ID AND u.INSTANCE_ID = @instanceId
  LEFT JOIN [Insightly].[dbo].[User.Follow] uf WITH (NOLOCK)
  ON (o.OPPORTUNITY_ID = uf.OPPORTUNITY_ID AND uf.USER_ID = @currentUserId AND uf.INSTANCE_ID = @instanceId)
WHERE o.INSTANCE_ID = @instanceId AND TEMPORARY = 0
AND (@userId IS NULL OR [RESPONSIBLE_USER_ID] =@userId) AND (@categoryId IS NULL OR c.CATEGORY_ID = @categoryId)
AND (@importId IS NULL OR o.IMPORT_ID = @importId)
AND OPPORTUNITY_STATE in @opportunityState)
SELECT * FROM cnts
WHERE intRow BETWEEN @skip AND @take
END
ELSE
BEGIN
WITH cnts AS
(
SELECT
       o.[OPPORTUNITY_ID]
      ,[OPPORTUNITY_NAME]
      ,[OPPORTUNITY_DETAILS]
      ,[IMAGE_URL]
      ,OPPORTUNITY_VALUE
      ,[PROBABILITY]
      ,[BID_CURRENCY]
      ,[BID_AMOUNT]
      ,[BID_TYPE]
      ,[BID_DURATION]
      ,[FORECAST_CLOSE_DATE]
      ,o.[CATEGORY_ID]
      ,c.CATEGORY_NAME
      ,c.BACKGROUND_COLOR
      ,o.[PIPELINE_ID]
      ,o.[STAGE_ID]
      ,[OPPORTUNITY_STATE]
      ,[RESPONSIBLE_USER_ID]
      ,u.[First_Name]
      ,u.[Last_Name]
      ,o.[VISIBLE_TO]
      ,o.VISIBLE_TEAM_ID
      ,o.[DATE_CREATED_UTC]
      ,o.[DATE_UPDATED_UTC]
      ,o.OWNER_USER_ID
      ,o.IMPORT_ID
      ,Follow_id
       ,ROW_NUMBER() OVER( ORDER BY ISNULL(p.Pipeline_Name, 'zz'), ISNULL([Pipeline.Stage].Stage_Order, 999)
       ) as intRow,
     COUNT(o.INSTANCE_ID) OVER() AS Count
  FROM [Insightly].[dbo].[Opportunity] o with (nolock)
  LEFT JOIN [Insightly].[dbo].[Reference.Category] c with (nolock)
  on o.CATEGORY_ID = c.CATEGORY_ID AND c.INSTANCE_ID = @instanceId
  LEFT JOIN [Insightly].[dbo].[User] u WITH (NOLOCK)
  ON u.USER_ID = o.RESPONSIBLE_USER_ID AND u.INSTANCE_ID = @instanceId
  LEFT JOIN [Insightly].[dbo].[User.Follow] uf WITH (NOLOCK)
  ON (o.OPPORTUNITY_ID = uf.OPPORTUNITY_ID AND uf.USER_ID = @currentUserId AND uf.INSTANCE_ID = @instanceId)
LEFT OUTER JOIN [Pipeline.Stage] with(nolock) ON o.PIPELINE_ID = [Pipeline.Stage].PIPELINE_ID AND o.STAGE_ID = [Pipeline.Stage].STAGE_ID
LEFT OUTER JOIN [Pipeline] p with(nolock) ON o.PIPELINE_ID = p.PIPELINE_ID AND p.INSTANCE_ID = @instanceId
WHERE o.INSTANCE_ID = @instanceId AND TEMPORARY = 0
AND (@userId IS NULL OR [RESPONSIBLE_USER_ID] =@userId) AND (@categoryId IS NULL OR c.CATEGORY_ID = @categoryId)
AND (@importId IS NULL OR o.IMPORT_ID = @importId)
SELECT * FROM cnts
WHERE intRow BETWEEN @skip AND @take
END

A: You can create a temp table based on the query and then count the rows in it.
CREATE TEMPORARY TABLE my_results
<whatever query you have>;

SELECT COUNT(*) FROM my_results;


text:
Q: Does hosted Kubernetes on GCP suppport pet sets? http://kubernetes.io/docs/user-guide/petset/ states under "Alpha limitations"

[...] most likely will be disabled on hosted offerings of Kubernetes.

Does Google Cloud Platform (GCP) support pet sets in their hosted version of Kubernetes?

A: From the page you linked:

As with all alpha/beta resources, it can be disabled through the --runtime-config option passed to the apiserver, and in fact most likely will be disabled on hosted offerings of Kubernetes.

As of the time of writing they are not supported.


text:
Q: Increased space between items on the website Good day!
I'm making a layout site and I am having the following problem:
There is a page on which some data is dynamically loaded. When the initial page is loaded, the item cannot be displayed accurately.
before ajax update
After updating the data item is displayed as it should.
after ajax update
What needs to be done to the original page looked neat.
Thank you.
HTML:

                Подключено: 26
                Отключено на станции: 10
                Отключено: 20

                Всего: 67
                Ошибки: 15

                На станции: 32
                В депо: 7
                Вне станции: 28

A: Seems to be a problem with white space in the initial markup. The white space is not there in the markup returned by your ajax call.
Executing this
$("#loco-summary tbody").css("white-space", "nowrap");

in the console seems to fix the problem, so id suggest either remove all the white-space in the loco-summary table, or set the white-space using css.

A: you should not use inline styles, but i am adapting to your coding style.
change your table to the following:
i've added a width to your table

                Подключено: 26
                Отключено на станции: 10
                Отключено: 20

                Всего: 67
                Ошибки: 15

                На станции: 32
                В депо: 7
                Вне станции: 28


text:
Q: Avalonia button click event is not working I have a simple Avalonia form:
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
        x:Class="AvaloniaExperiment.MainWindow"
        Title="AvaloniaExperiment">
  <StackPanel>
    <TextBlock>Welcome to Avalonia!</TextBlock>
    <Button Name="btn" Click="btn_OnClick">Fred!</Button>
  </StackPanel>
</Window>

And a method in the code behind (I want to do things this way until I become familiar with Avalonia, then maybe I'll try MVVM):
private void btn_OnClick()
{
    btn.Text = "Ginger";
}

However I get these compile errors:

The name btn does not exist in the current context (in the code behind)
Unable to find suitable setter or adder for property Click of type Avalonia.Controls:Avalonia.Controls.Button for argument System.Private.CoreLib:System.String, available setter parameter lists are:
  System.EventHandler`1[[Avalonia.Interactivity.RoutedEventArgs, Avalonia.Interactivity, Version=0.9.0.0, Culture=neutral, PublicKeyToken=null]] (in the XAML)
Unable to find suitable setter or adder for property Command of type Avalonia.Controls:Avalonia.Controls.Button for argument System.Runtime:System.String, available setter parameter lists are:
  Avalonia.UnsetValueType
  Avalonia.Data.IBinding
  System.Windows.Input.ICommand (also in the XAML)

What could I be doing wrong in hooking up this event handler?

A: The sender is the button you just clicked, so typecast sender to Button and set its Content property (not Text) to whatever you want to.
public void btn_OnClick( object? sender, RoutedEventArgs args )
{
    ( sender as Button )!.Content = "Ginger";
}

No need to look it up in the tree or anything else, this way you can reuse the same code behind for all your buttons, and for instance, depending on which button it is, set different names or styles, or other properties, etc.
More advanced:
public void btn_OnClick( object? sender, RoutedEventArgs args )
{
    var button = ( sender as Button )!;
    switch ( button.Name )
    {
        case "btn":
        {
            button.Content = "Ginger";
        }
        break;
        case "otherBtn":
        {
            button.Content = "Ale";
        }
        break;
        default:
        {
            button.Content = "No clue which Button you are!";
        }
        break;
    }
}

A: have you tried...
public void btn_OnClick(object sender, RoutedEventArgs e)
{
    btn.Text = "Ginger";
}

A: You should add a ControlLink in the Parent Control Constructor
like this:
public class AnyParentControl
{
    Button btn; // for the class
    public AnyParentControl() // constructor
    {
        InitializeComponent(); // necessary method for Avalonia

        btn = this.Find<Button>("The Control Name on XAML File");
        btn.Click += Cbtn_Click; // event link
    }
}

Greetings from Peru :D

A: Button does not have Text property. It does have Content.
btn.Content = "Ginger";


text:
Q: conflicting options errors I have in the preamble:
\documentclass{article}
\usepackage{amssymb,amstext,amsmath,latexsym,mathtools}
\usepackage[italian,british]{babel}
\usepackage{pdfpages}
\usepackage[utf8,latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{csquotes}
\usepackage{cmbright}
\usepackage{setspace}
\usepackage{pdfpages}
\usepackage{hyperref}
\usepackage[style=authoryearcomp,firstinits=true,maxcitenames=2,maxbibnames=99]{biblatex}
\DeclareNameAlias{sortname}{last-first}
\DeclareFieldFormat[article,periodical]{volume}{\mkbibbold{#1}}
\renewcommand*{\multinamedelim}{\addcomma\space}
\renewcommand*{\finalnamedelim}{\addcomma\space}
\renewbibmacro{in:}{}
\addbibresource{trybib.bib}

\nocite{*}

I get these two errors:
conflicting options
'firstinits' conflicts with'uniquename=true'

and
Data encoding is 'latin1'
Use backend=bibtex8 or backend=biber

I need all these packages, how can I fix these errors?

A: I just had to do some sorting and cleaning up,
the following questions are probably relevant for you:

*

*How to use biber

*biber .bcf file extension

*utf8 or latin1 input encoding?

*change encoding of files

*Which packages to load after hyperref?

*What packages do people load by default?

*lmodern vs. cm-super

*font packages
After that, I only had to do what biblatex was suggesting.
The following should compile without warnings/errors.
Please note the comments.
\documentclass{article}
\usepackage{amssymb,amstext,amsmath,latexsym,mathtools}  % do you really need all?
\usepackage{pdfpages}  % you had that package twice
\usepackage{setspace}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}  % use utf8 for all files
\usepackage[italian,british]{babel}
\usepackage{cmbright}  % needs the cm-super package to be installed
% \usepackage{lmodern}  % try this one instead of cm-bright + cm-super

\usepackage[autostyle]{csquotes}
\usepackage[
    backend=biber,  % run biber.exe instead of bibtex.exe
    style=authoryear-comp,
    firstinits=true,
    uniquename=init,  % this option is compatible with firstinits
    maxcitenames=2,
    maxbibnames=99
]{biblatex}
\DeclareNameAlias{sortname}{last-first}
\DeclareFieldFormat[article,periodical]{volume}{\mkbibbold{#1}}
\renewcommand*{\multinamedelim}{\addcomma\space}
\renewcommand*{\finalnamedelim}{\addcomma\space}
\renewbibmacro{in:}{}
\addbibresource{biblatex-examples.bib}

\usepackage{hyperref}  % hyperref should usually be the last package
\hypersetup{
    colorlinks=true
}

\begin{document}
Lorem ipsum, dolor sit amet \cite{kastenholz}.
At vero utilisam \cite{bertram}.
\printbibliography
\end{document}


text:
Q: Java FX Scene Builder How to make event key pressed I'm new in Java and Java FX and I'm trying to make a panel with buttons using scene builder. I want my application to respond only on arrow key pressed. I made the following method in my Controller class:
public void keyPressed(KeyEvent key) {
    switch(key.getCode()) {
        ...some code here
    }
}

After that I selected this method in scene builder, but when I run my application nothing happens when I press an arrow key.
Can somebody help me?

A: Without seeing the rest of your code and FXML it is difficult to tell, here is full example
Possible things you missed

*

*Adding keyPress as an action in the FXML

*Adding the @FXML annotation to the keyPressed() method

Code
public class Main extends Application {

    private class Controller {
        @FXML  // <== perhaps you had this missing??
        void keyPressed(KeyEvent event) {
            switch (event.getCode()) {
            case LEFT:
            case KP_LEFT:
                System.out.println("to the left");
                break;
            case RIGHT:
            case KP_RIGHT:
                System.out.println("to the right");
                break;
            default:
                break;
            }
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/foo.fxml"));
        loader.setController(new Controller());
        primaryStage.setScene(new Scene(loader.load()));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

FXML
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane onKeyPressed="#keyPressed" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
   <columnConstraints>
      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints minHeight="10.0" vgrow="SOMETIMES" />
   </rowConstraints>
   <children>
      <Button mnemonicParsing="false" text="Button" />
   </children>
</GridPane>

A: KeyCode also allows to compare with a specific key
@FXML
private void keyPressed(KeyEvent keyEvent)
    if (keyEvent.getCode() == KeyCode.ENTER) {
        // do some actions
    }
}

You can get all the key code from here. Without using switch it's one of the good way.

A: KeyCode has a method isArrowKey(), so if you're calling your keyPressed method from your event handler, you could do:
public void keyPressed(KeyEvent key){
    if(key.getCode().isArrowKey()){
        ...some code here
    }
}

If you need to do different things based on which arrow key is pressed, make sure your switch cases are comparing to KeyCode.UP/DOWN/LEFT/RIGHT. If they are, it's likely that either you didn't set the event handler properly or your GUI is hung because of a threading problem. Post where your handling the event if you need more help.


text:
Q: no method error "merge" in Rails middleware Hi I am building a Rails/Rack middleware for the Mailgun api, and doing a simple test for connection, which is fine in Postman with exact same params.
It is showing an error in test, Failure/Error: @app.call(env)
 NoMethodError:
   undefined method `merge!' for #<Mailgun::Tracking::MailLogger:0x0000557e6bc8bb50>

on running RSpec, and no merge method is attempted at all, so dont know where its come from. The api_key and endpoint are initialized in config/initialisers folder as per the Mailgun Tracking gem (which is being used) guidelines.
Only two other files used and code below.
MailLogger class under Mailgun::Tracking module, registered as middleware in app.
require 'logger'
require 'mailgun/tracking'
require 'rack/contrib'
require 'rack'
require 'byebug'

module Mailgun::Tracking
  class MailLogger
    def initialize(app, options = {
    "HTTP_X_MAILGUN_API_KEY" => ENV['MAILGUN_API_KEY'],
    "HTTP_X_MAILGUN_ENDPOINT" => ENV['MAILGUN_ENDPOINT']
    })
    @app = app
    @options = options
    end

    def call(env)
    @app.call(env)
    end
  end
end

The RSpec test
require 'logger'
require "json"
require "rails_helper"
Bundler.require(*Rails.groups)
require_relative "../../lib/middleware/mailgun/mailgun_tracking.rb"

RSpec.describe Mailgun::Tracking::MailLogger, type: 'Mailgun Webhook' do
  subject(:response) { app.call(env) }
  # env to pass in middleware, url endpoint & key
  let(:app) { described_class.new(Rails.application) }
  let(:env) { described_class.new(app, options = {
   "HTTP_X_MAILGUN_API_KEY" => ENV['MAILGUN_API_KEY'],
    "HTTP_X_MAILGUN_ENDPOINT" => ENV['MAILGUN_ENDPOINT']
  }) }

 it "returns a 200 status code" do
    expect(response).to eq([200, {}, ["OK"]])
  end
end

Am just looking for a 200, OK on connection, as I already get in Postman with the same header (api_key) and endpoint (events)
but throws this mysterious missing "merge" method error
Not encountered before.
Anyone know why?
Thanks

A: The actual code calling merge! is hidden in rack implementation and as such is filtered out from the error message. Your problem is that env you define in your test is not an instance of Rack::Environment but rather instance of your middleware. You can generate mocked environment instance using, for example, Rack::MockRequest.env_for("/", method: :get)
That being said, your unit test is currently testing the whole of the rack stack, including the routes and other middlewares. You can isolate your test better by using a mock application:
let(:app) { described_class.new(->(env) [200, {}, 'success']) }


text:
Q: VSCode VIM Extension - E488 Trailing Characters I'm trying to insert a range using:
:put =range(11,15)

But the error: E488: trailing characters appears. How can I resolve this issue? I am using the VIM extension for VSCode.


text:
Q: How to render the text of the selected option in template? I have a ModelForm that has a widget of type Select
 class MyModelForm(ModelForm):
    ...
    widgets = {
        'my_field': Select(
            choices=[('1', 'Choice 1')]
        ),
    }

In my view I'm retrieving an already stored model and passing the form as my_form to the template:

{{ my_form.my_field.value }}

As expected, this outputs:
 1

How can I get the text 'Choice 1' instead?

A: While not an exact duplicate, arogachev's duplicate suggestion did help me realize I should be setting the choices attribute in the Model's fields and not the ModelForm's widgets:
class MyModel(Model):
    my_field = models.CharField(max_length=50, choices=[
        ('1', 'Choice 1')
    ])

This way, I can do this:

{{ my_form.instance.get_my_field_display }}

Which outputs
Choice 1

Thanks!


text:
Q: Critical Regex Implementation in SQL Server I am not sure if this can be done in SQL Server. May someone please help me if possible with SQL?
I have a table with data looks like this:
DECLARE @MYTABLE TABLE
(
    ColumnA VARCHAR (50)
)

INSERT INTO @MYTABLE
    SELECT '01268 591558 * 3 Marina' UNION ALL
    SELECT '01322 421980    JULIE  A/P' UNION ALL
    SELECT '01296620096 BR TAKES CARD EOM' UNION ALL
    SELECT '07547 740863/07986 019852' UNION ALL
    SELECT '07754553528 - TIM' UNION ALL
    SELECT '07732418595 sam' UNION ALL
    SELECT '01793 425574- Charlotte' UNION ALL
    SELECT '01268 591558 * 3 Marina' UNION ALL
    SELECT '07967 967404 CELIA' UNION ALL
    SELECT '0208 361 1213 / 1433      /8899 ' UNION ALL
    SELECT '0208 361 1213 / 1433 '  UNION ALL
    SELECT '0208 361 1213 / 1433'  UNION ALL
    SELECT '01206 578671 / 564272' UNION ALL
    SELECT '01206735561/07748116152' UNION ALL
    SELECT '0208 361 1213 / 1433  '  UNION ALL
    SELECT '01234 754047   SUE' UNION ALL
    SELECT '01206735561/07748116152/0156589'

and I am expecting output like

May someone please help me with this?
Thanks

A: Works with the sample data, but there are some potential pitfalls.
Currently the XML will split up to 9 positions (easy to expand or contract).
Clearly you could add more ColumnX if needed.  Just follow the pattern
Example
Select A.*
      ,Column1 = left(Pos1,11)
      ,Column2 = case when Try_Convert(float,Pos2) is null then null else Left(Pos1,11-Len(Pos2))+Pos2 end
      ,Column3 = case when Try_Convert(float,Pos3) is null then null else Left(Pos1,11-Len(Pos3))+Pos3 end
From @MYTABLE A
Cross Apply (
                Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                      ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                      ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                      ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                      ,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
                      ,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
                      ,Pos7 = ltrim(rtrim(xDim.value('/x[7]','varchar(max)')))
                      ,Pos8 = ltrim(rtrim(xDim.value('/x[8]','varchar(max)')))
                      ,Pos9 = ltrim(rtrim(xDim.value('/x[9]','varchar(max)')))
                From  (Select Cast('<x>' + replace((Select replace(replace(A.ColumnA,' ',''),'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as C
            ) B

Returns


text:
Q: Is it possible to set a Request Header in a Squid Request to respond with a 404 if not found in Cache? I have tried to look at the documentation, but have not found any info on this yet.

A: You could do this with two squids (or a squid and an apache instance with mod_proxy)...
Configure squid1 to use squid2 as its parent cache_peer. Configure the second squid as a proxy only with no caching enabled.
With this configuration in place, populate whatever content you need into squid1's cache by making requests for the needed content.
When you're ready to "close the door", so to speak, make a url_rewriter helper for squid2 that simply returns a single string containing known-invalid URL. Restart squid2 with the url_rewriter in place.
When this config is in place, cached content will be served normally, while squid1 will go to squid2 for uncached content, which will return a 404 for all URLs.


text:
Q: Numerical regularities in the classification of cellular automata This is a question about elementary cellular automata (ECA) and their classification into uniform (class I), periodic (class II), chaotic (class III), complex (class IV) due to Wolfram.
Maybe I missed something and this is folklore, but is there a good explanation

*

*why three out of eight class I rules (upto equivalence) are powers of $2$?
$8\equiv 64, 32, 128$

*why the other powers are class II?$1, 2 \equiv \textbf{16}, 4$

*why six out of eleven class III rules are multiples of $15 = \textbf{16} - 1$?$30\equiv 135,45\equiv 75,60\equiv 195,90\equiv 165,105,150$

*why rules $15\equiv 240$ and $180\equiv 210$ are exceptional and in class II?

*why rule $120\equiv 225$ is exceptional and in class IV?
It comes as no surprise that rule $0\equiv 255$ is class I.
Maybe it's possible to see "patterns" here:

The scheme on top indicates the position of the $i$-th bit in the binary representation of the rule numbers.
Choosing another, more natural representation gives different rule patterns:

With equivalence class representatives only:

Note that all multiples of $15$ (except for $0\equiv 255$) have two bits in the upper row (the subrules for black pixels) and two bits in the lower row (the subrules for white pixels), i.e. are "doubly balanced" in a sense. In turn, there are only four doubly balanced class II rules ($15, 46, 154\equiv 180, 184$), one doubly balanced class IV rule ($120$), and no doubly balanced class I rule. So being a multiple of $15$, i.e. being doubly balanced, somehow strongly correlates with being class III. While being a power of $2$, i.e. having exactly one bit, strongly correlates – more or less obviously – with being class I.
The question remains open why doubly balanced rules – even the most symmetric one, $90$ – tend to be class III, i.e. to produce chaotic patterns. And why rule $120$ produces complex patterns.

A: First of all, the general reason why powers of two come up so frequently when looking at the Wolfram numbering of elementary CA rules is because the natural representation of the rules is actually the 8-bit rule string, not the number obtained by interpreting this string as a binary number and converting it to decimal.
From that viewpoint, I think all of your observations can be seen as arising from a single general one: rules that map most local configurations to the same state tend to have simpler dynamics than those whose rule strings are more or less evenly split between zeros and ones, and which are thus roughly equally likely to map a randomly chosen configuration to either state.
Of course, there are plenty of counterexamples to this general rule of thumb, but on average, it's still a pretty decent guideline.
In particular, let $H(n)$ be the Hamming weight of the rule number $n$ written in binary, i.e. the number of bits in the rule string that are ones.
(Note: $H(n)$ is closely related to e.g. the "activity" parameter $\lambda$ as defined by Langton (1990), although Langton's $\lambda$ is only defined for rules with a designated "quiescent state" that is stable in a homogeneous configuration.  Indeed, for ECA rules with quiescent state 0, $\lambda(n) = \frac{H(n)}{7}$, where the division by the number of non-quiescent input patterns simply rescales the activity parameter to $0 ≤ \lambda(n) ≤ 1$.)
Considering $H(n)$ for various rules, we observe the following:

*

*If $n$ is a power of two, then $H(n) = 1$.  All such rules have very simple dynamics (Wolfram class I or II), since there's only one local input pattern (out of the eight possible ones) that will produce a state-1 cell in the next generation.  (The same is true, of course, also for the equivalent rules with $H(n) = 7$, where there's only one pattern that will yield state 0.)

*For a rule to be in Wolfram class I, all initial configurations containing cells in both states must evolve to a stable homogeneous configuration consisting of one "dominant" state.  (Thus, there rules come in equivalent pairs related by state inversion.)  For an ECA rule to be Wolfram class I with dominant state 0, it turns out that:

*

*the local input pattern 000 must yield state 0, otherwise the all-zero configuration would not be stable;

*the patterns 001, 010 and 100 must also yield state 0, otherwise isolated state 1 cells would persist forever; and

*at least one of the patterns 011 and 110 must also yield state 0, otherwise pairs of adjacent state 1 cells would persist forever.

That means that the only patterns that can yield state 1 for a class I rule with dominant state 0 are 101, 111 and at most one of 011 and 110, and so $H(n) ≤ 3$ for any such rule.  In fact, exactly four of these 12 rules have $H(n) = 1$ (and a fifth, rule 0, has $H(n) = 0$).
(Also taking mirror symmetry into account, it turns out that four of these 12 rules — including rules 0, 32 and 128 — are amphichiral, i.e. invariant under mirroring, while the rest come in four mirror pairs, one of those pairs being rules 8 and 64.)

*Rules whose Wolfram number is of the form $15k$ for $1 ≤ k ≤ 16$, on the other hand, have $H(n) = 4$, i.e. exactly half the bits of their rule string are 1 and half are 0:

dec
bin
dec
bin
dec
bin
dec
bin

15
0000 1111
30
0001 1110
45
0010 1101
60
0011 1100

75
0100 1011
90
0101 1010
105
0110 1001
120
0111 1000

135
1000 0111
150
1001 0110
165
1010 0101
180
10110100

195
1100 0011
210
1101 0010
225
11100 001
240
11110000

In fact, these are exactly the 16 ECA rules that are linear in their leftmost input, such that inverting this input cell always inverts the output cell.  This is reflected in their (binary) Wolfram rule code by the high four bits (which encode the outputs when the leftmost input is 1) being the ones' complement of the low four bits (which encode the outputs when the leftmost input is 0).  (The fact that all multiples of 15 up to 240 have this property in binary is a somewhat remarkable consequence of how binary multiplication works.)
Of course, not all of these rules actually give rise to complex dynamics.  For example, rule 240 (binary 11110000) is a simple shift map where the output state is equal to that of the leftmost cell of the input pattern, and none of the other input cells matter at all!  Rule 15 (binary 00001111) is the same, except that the output is inverted.  Wolfram, reasonably enough, classifies both of these rules in class II.
Rules 180 and 210, meanwhile, are a bit more complex, and arguably close to the boundary between classes II and III.  Let's look at the rule table for rule 210 (and the closely related rule 90, which Wolfram puts in class III) more closely:

input:
111
110
101
100
011
010
001
000

rule 90
0
1
0
1
1
0
1
0

rule 210
1
1
0
1
0
0
1
0

We can see that when the middle input cell is 0, then the output of both rules is equal to the binary XOR of the other two inputs.  However, whereas this is always the case for rule 90, regardless of the value of the middle cell, for rule 210 the output when the middle cell is 1 is equal to the left input cell.
Indeed, if started from a single state 1 cell on a state 0 background (or, more generally, from a configuration where all even-numbered or all odd-numbered cells are in state 0), rule 210 behaves exactly like rule 90 and produces the same distinctive linear superposition of discrete Sierpinski triangles.  In particular, under both rules, such a starting configuration guarantees there there will never be two adjacent state 1 cells, and thus the differences between the rule tables will never come into play.  (The same is true for rules 18, 26, 82, 90, 146, 154, 210 and 218, i.e. all rules with Wolfram codes of the form $2 + 8a + 16 + 64b + 128c$ for $a,b,c \in \{0,1\}$.)
What puts rule 210 in class II (at least according to Wolfram, presumably) however is the fact that, when two Sierpinski patterns offset by an odd number of cells collide, they do not pass through each other without interference (as they would under rule 90), but rather the left pattern overrides the right one.
In particular, this means that, when started from a random initial configuration (which tend to contain a large number of state 1 cells an odd number of steps apart), rule 210 tends to produce diagonal stripes with fairly low-period partial Sierpinski patterns within them, whereas rule 90 displays apparently chaotic (although actually linear and thus quite easily predictable) dynamics consisting of freely growing and overlapping Sierpinski triangles.

Figure 1: Evolution of Wolfram elementary cellular automaton rules 90 (top) and 210 (bottom) from a random initial configuration (left) and from two state-1 cells placed an odd number of positions apart (right)

Figure 2: Evolution of Wolfram elementary cellular automaton rule 210 / rule 90 from an initial configuration where all even-numbered cells have state 0 and odd-numbered cells (within a small section of the grid) have random states.  Rule 210 behaves identically to rule 90 on such initial conditions, exhibiting apparent chaos that is actually just a linear superposition of shifted Sierpinski triangle patterns.
Of course, Wolfram's classification is to some extent subjective and could be argued with.  For example, do linear ECA rules like rule 90 really belong in class III, or should they be in class II, or should they perhaps be put in a separate class entirely?  Certainly they're not "chaotic" in the same sense as, say, rule 30, even if they may look that way when started from a random initial condition.  And does the fact that rule 210 may exhibit exactly the same kind of dynamics as rule 90, but only when the initial configuration satisfies a special condition (one of the two checkerboard sublattices is empty), mean that it too should be in class III? Maybe. Or maybe not.


text:
Q: How to fix integration issue Magento store with POS system after site migration? We migrated our Magento site (Magento 1.8.1.0) from old server to a new server.
But, we can't use the Winepos integration extension any more.
Our site is connected with Winepos system, and this Magento extension had been operated before migrating work.
This is Winepos API manual.
At this time, we think some PHP modules were not installed on our new server.
But, we don't know which PHP modules were not installed. It seems all PHP modules were installed on our new server.
The Magento extension to integrate with Winepos are as follow. This extension is consisted with two files.
Config.xml
<config>
 <global>
   <events>
     <checkout_onepage_controller_success_action>
       <observers>
         <igor_winepos_order_success_observer>
           <type>singleton</type>
           <class>igor_Winepos_Model_Wineposobserver</class>
           <method>checkoutSuccessObserve</method>
         </igor_winepos_order_success_observer>
       </observers>
     </checkout_onepage_controller_success_action>
    </events>
   </global>
  </config>

wineposobserver.php
class igor_Winepos_Model_Wineposobserver extends Varien_Event_Observer {

  function customlog($obj) {
    ob_start();
    var_dump($obj);
    $out1 = ob_get_contents();
    ob_end_clean();
    $f = fopen('/tmp/log.txt', 'ab');
    fwrite($f, $out1);
    fclose($f);
  }

  public function __construct() {
  }

  public function checkoutSuccessObserve($observer) {
    // $event = $observer->getEvent();
    $order_ids = $observer->getData('order_ids');
    if(gettype($order_ids) == 'array' && count($order_ids) == 1) {
       $the_order = Mage::getModel('sales/order')->load($order_ids[0]);
       Mage::helper('globalfunc')->registerOrderWithWinePOSAsynchronousWithTimeout($the_order);
    }
 }
}

I am getting the following in the Apache log:

PHP Warning: PHP Startup: apc.shm_segments setting ignored in MMAP mode in Unknown on line 0 [Sun Apr 30 06:32:30 2017] [notice] Apache/2.2.22 (Ubuntu) mod_ssl/2.2.22 OpenSSL/1.0.1 configured -- resuming normal operations

 285:   function registerOrderWithWinePOSAsynchronousWithTimeout($the_order) {
 286      try {
 287        $items = $the_order->getAllItems();
 ...
 426          $ordered_raw_item = $ordered_products_raw_items[$ordered_product_id];
 428:         $product_winepos_id = trim(strval($product->getResource()->getAttribute('winepos_id')->getFrontend()->getValue($product)));
 429
 430          $item_element = $doc->createElement('item');
 432          $item_num_element = $doc->createElement('item-num');
 433:         $item_num_element->appendChild($doc->createTextNode(strval($product_winepos_id)));
 434          $item_element->appendChild($item_num_element);
 ...
 466        $the_xml = $doc->saveXML();
 468:       // $post_result = Mage::helper('globalfunc')->post_to_api_winepos('https://wines-in-november.vznlink.com/orders', $the_xml, 'admin276975', '8dc670fb943dc2c0a1415405cdf00e3ec579c4e6', 8, 10);
 470:       return Mage::helper('globalfunc')->delayed_post_to_winepos($the_xml);
 471      } catch(Exception $e) {
 472        $this->customlog($e);
 ...
 475    }

A: I created a new module to integrate with POS system and implemented inventory synchronization successfully.
This work should be done by cron job. To do it, I created three individual script files.
Also, POS provider should provide ordered product information including inventory information as txt file via ftp in every time interval.
lftp -u [username],[password] -e'set ftp:passive-mode false; cd files; put data.txt; quit' [folder name]

The cron job operating blocks are as follow.
cron_file_mover.php
  $start = microtime(true);
  shell_exec('cp /home/files/data.txt /var/www/vhosts/magento/');
  shell_exec('chown -R www-data:www-data /var/www/vhosts/magento/');
  $end = microtime(true);
  echo 'Run time: '.round($end-$start, 4).'s';

cron_pos_post_script.php
Utils::initMagento(); $MAX_RETRIES = 5;
$delayed_jobs = Utils::mageGetRows("select * from delayed_jobs where job_type = 'pos_order' and status = 'todo' order by created_at DESC");
$current_index = 0;
foreach($delayed_jobs as $delayed_job) {
  $current_index += 1;
  $retry_count = intval($delayed_job['retry_count']);
  $retry_count += 1;
  $post_result = Mage::helper('globalfunc')->post_to_api_pos('https://vznlink.com/orders', $delayed_job['job_details'], 'admin', 'fd93d2de58ab', 8, 10);
   Utils::mageSqlExecute("update delayed_jobs set status = 'done' where id = " . $delayed_job['id']);

Utils::mageSqlExecute("update delayed_jobs set status = '" . $new_status . "', retry_count = " . $retry_count . " where id = " . $delayed_job['id']);
}

cron_pos_update_script.php
$PATH_TO_FILE = '/var/www/vhosts/magento/data.txt';

function read_pos_file($path_to_file) {
  $min_count_required_for_product = 12;
  $f = fopen($path_to_file, 'rb');
  $text = trim(fread($f, 100000000));
  fclose($f);
  $lines = preg_split('/\r\n|\r|\n/i', $text);
  $products = array();
  foreach($lines as $line) {
  $product = preg_split('/\t/i', trim($line));
  if(count($product) >= $min_count_required_for_product) {
      $product[0] = strval(trim($product[0]));
      $product[1] = strval(trim($product[1]));
      $product[2] = strval(trim($product[2]));
      $product[11] = intval(strval(trim($product[11])));
      $products []= $product;
  }
}
  return $products;
}

function update_stock_for_stock_item($product_id, $new_stock) {
   $stock_item = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product_id);
   $stock_item->setData('qty', $new_stock);
   if($new_stock > 0) {
      $stock_item->setData('is_in_stock', 1);
   }
   $stock_item->save();
}
   $products = read_pos_file($PATH_TO_FILE);
   $total_count = 0; $processed_count = 0;
   foreach($products as $product) {
     $total_count += 1;
     $item_number = $product[0];
     $new_stock = $product[11];
     if($new_stock < 0) {
        $new_stock = 0;
     }
   $products_matching_item_number = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('pos_id')->addFieldToFilter('pos_id', $item_number)->getItems();
   if(count($products_matching_item_number) == 1) {
      $products_matching_item_number = array_values($products_matching_item_number);
      $matching_product = $products_matching_item_number[0];
      $matching_product_id = $matching_product->getId();
      update_stock_for_stock_item($matching_product_id, $new_stock);
      $processed_count += 1;
   }
}

The cron job settings are as follows.
10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_post_script.php &> /dev/null
10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_update_script.php &> /dev/null
20 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_pos_file_mover.php &> /dev/null

Keep in mind, checking POS data provided from POS system, cron job setting, checking update script operations.


text:
Q: calling a function in a shared object, without header file I have a .so lib, that holds 1 function i want to call from my own code.
I have decompiled a function that uses the same function, with IDA and it looks like :
ns::fw::SessionIf *v6
ns::fw::SessionIf::Send(v6, 0x1813u, 8u, &v15, 1, 0);

How can i make this same call from my code?

A: As long as you compile your program so that shared data structures are binary-equivalent in both the .so lib and your executable, then it should be rather straightforward.
The tutorial linked by Odysseus shows how to do it in Windows.
It seems like you want to initialize an object in your program using the .so lib, with no shared header file.
This is no problem as long as you define the same data structure in the exact same way in your .cpp file. I don't have a Linux machine handy, but I can give you a working example in Windows:
#include <Windows.h>
#include <iostream>
#include <string>

struct ComplexStruct {
    std::string m_str;
    int m_int;
};

typedef ComplexStruct* (__stdcall* func_complex_ptr)(void);
typedef void(__stdcall* func_complex_ptr2)(ComplexStruct&);

int main() {
    HINSTANCE procDll = LoadLibrary(L"C:/temp/test/DllTest.dll");

    func_complex_ptr dllComplexFunc = (func_complex_ptr)GetProcAddress(procDll, "getComplex");
    ComplexStruct* pComplex = dllComplexFunc();
    std::cout << "output1: " << pComplex->m_str << std::endl;

    func_complex_ptr2 dllComplexFunc2 = (func_complex_ptr2)GetProcAddress(procDll, "initComplex");
    ComplexStruct complexInst;
    dllComplexFunc2(complexInst);
    std::cout << "output2: " << complexInst.m_str << std::endl;

    return 0;
}

(I didn't include the code for the DLL file but I can if you want.)
The only situations that can be problematic are if the object has a complex destructor, depending on what exactly it does, or if the object interacts with hidden state inside of the .so library. You might wish to avoid deleting the object in your program and instead call some form of specialized free function in the .so if it has one. Or if you're dealing with simple objects, then there's no problem.
If you want an example that works on Linux, with .so files, I can craft one as well.


text:
Q: Android viewpager actual default offscreen page limit I have implemented simple ViewPager with its pager adapter.PagerAdapter takes list of views to displaye in ViewPager.I have not called setOffscreenPageLimit for ViewPager to set limit.
So by default 1 limit is selected.(1 page should be retained to either side of the current page in an idle state).But in actual there are 2 pages retained to either side.
0 | 1 | 2(current visible) | 3 | 4

Could you please confirm why it is happening?

A: I tried to reproduce this behavior, but with the following code I see container.getChildCount() always 3 or lower:
MainActivity.java
public class MainActivity extends AppCompatActivity {

    SectionsPagerAdapter mSectionsPagerAdapter;

    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        private String TAG = SectionsPagerAdapter.class.getSimpleName();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Log.v(TAG, "container.getChildCount:" + container.getChildCount());
            return super.instantiateItem(container, position);
        }

        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            return String.format(l, "Section %d", position);
        }
    }

    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            ListView listView = (ListView) rootView.findViewById(R.id.listView);
            ArrayAdapter<String> listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
            listAdapter.add("Fragment Body " + getArguments().getInt(ARG_SECTION_NUMBER));
            listAdapter.add("one");
            listAdapter.add("two");
            listAdapter.add("three");
            listView.setAdapter(listAdapter);
            return rootView;
        }
    }

}

activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>

fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            tools:context=".MainActivity$PlaceholderFragment">

<ListView
    android:id="@+id/listView"
    android:layout_height="match_parent"
    android:layout_width="wrap_content" />

A: I faced the same behaviour, and finally found it will only occur when ViewPager's horizontal padding has been set to none zero value.
In this case, offscreenPageLimit is 1, which means ViewPager should fill content area (which width is ViewPager's width multiplied 3) with child pager views (each pager's width is ViewPager's width minus horizontal paddings), so the finally needed page count is
3 * ViewPager.getWidth() / (ViewPager.getWidth() - ViewPager.getPaddingLeft() - ViewPager.getPaddingRight()) > 3

Then ViewPager's current implementation may think it need 5 page to fill the content area.
This should a bug of ViewPager because it can optimize the above logic as 3 page is enough to fill the content area.


text:
Q: How to use casting in elasticsearch? I have a long field which it's name is pan. I want to have a query which casts this field to string, so that I can find all the pans starting with 6273 or end with 7985 or containing 8110.

A: I just got the answer, just use :
{
   "query": {
      "bool": {
         "must": {
            "filtered": {
               "query": {
                  "match_all": {}
               },
               "filter": {
                  "script": {
                     "script": "doc['pan'].value.toString().matches('.*88.*');"
                  }
               }
            }
         }
      }
   }
}


text:
Q: What are the alternatives for radio buttons? I haven't seen any radio buttons for a long time. Are they really used anymore, and if so where are they used and who used them?
What are the best alternatives for radio button? What can you use instead of radio buttons?

A: I only had to look as far as the "Settings" page on my GMail account before I found a radio button on the web.
The only other widget that provides a simple "Pick one choice from many" option in an HTML document is a <select> element.
You can also use multiple submit buttons for the same effect — but you submit the form at the same time, so it isn't always appropriate (although good for "Preview" or "Save" decisions).

A: Radio buttons are still commonly used on websites.
There simply is no alternative to them, that have the same functionality with the same ease of use.

A: The alternatives to radio buttons are checkboxes and drop down boxes. Use them over the alternatives when:

*

*One answer must be selected

*There are three or fewer (4 at a stretch)
possible answers

Or to give a clearer distinction for yes/no fields than a single checkbox

A: You can use jquery ui for example:
http://jqueryui.com/demos/button/#radio
It's a nice alternative if your tired of plain old radio buttons ;)

A: Directly there are no alternative for radio button. [As per my knowledge].
But You can use images to supplant the radio buttons. You can make them function in the same manner as the radio buttons inmost cases, and you can make them any size you want.

If I have a choice i surely go with using simple radio buttons rather than implementing its alternative. Radio button is very much compatible in all browser so i also suggest you to don't try for any alternative just go with what you get by default.

A: as Karpie sad : "Radio buttons are still commonly used on websites" !
look at https://protect.login.yahoo.com/login/set_pref for example.
the radio buttons are standard in XHTML and HTML5.
but today, the modern design is more excepted to use checkboxes or drop down boxes.


text:
Q: Using JSON, passing variable from php to javascript I wonder why is it not working?
check_login.php
<?php
session_start();
$data = array("username" => "true");
echo json_encode($data);
?>

my js file
var linkName;
$.ajax({
    type: "POST",
    url: "check_login.php",
    dataType: "json",
    success: function(json){
    if(json.username != "true")
    {
      //do something
    }
    }
});

I am trying to get the username after checking whether or not the user has signed in yet in the php file, something like passing a session variable. But currently passing a string seems to already have a problem. Any know what I did wrong here?
Still not working the code above. Anyone want to help me out here?

A: You have an error in your PHP code. The square bracket ] is not needed in line 3.
And, of course you should use echo json_encode($data);

A:     `if(json.data.username != "true")` is wrong you do not have data object

    `if(json.username != "true")` try this

A: You should echo the json data so that the page you get using ajax contains the string data.
<?php
session_start();
$data = array("username" => "true");
echo(json_encode($data));
?>

$.ajax({
    type: "POST",
    url: "check_login.php",
    dataType: "json",
    success: function(json){
       console.log(json)
    }
});

Also some times you might need to set the content type of the header in php to json.

A: try to send the header
header("Content-Type: application/json", true);
print json_encode($data);

A:  return json_encode($data);

I think you have to return the data rather than just json encoding it!


text:
Q: Разбить текст по предложениям с сохранением разделителя Можно ограничиться тем, что предложение кончается:
"строчная буква" - ". или ! или ?" - "пробел" - "заглавная буква"
Например:
"Привет! Я простой текст. Ты сможешь разделить меня?"
['Привет!','Я простой текст.','Ты сможешь разделить меня?']
Была попытка, но неудачная:
re.split(r'\w[.!?]+\s+[А-Я]', "Hello! I'm John. Are you OK? fine... and so")

A: Делим по пробелу, но используем позитивный просмотр назад чтобы удостоверится, что перед пробелом идет буква и (точка или ! или ?):
import re

result = re.split(r'(?<=\w[.!?]) ', "Hello! I'm John. Are you OK? fine... and so")
print (result)

result = re.split(r'(?<=\w[.!?]) ', "Привет! Я простой текст. Ты сможешь разделить меня?")
print (result)

Результат:
 ['Hello!', "I'm John.", 'Are you OK?', 'fine... and so']
 ['Привет!', 'Я простой текст.', 'Ты сможешь разделить меня?']

P.S. На Юникоде не проверял. Тестировал на https://repl.it/languages/python3
UPD \w возможно стоит заменить на перечисление допустимых символов, так как это могут быть буквы, цифры и знак подчеркивания.

A: (.+?[.!?]) - разбивает по  . ! ?


text:
Q: SQLServer CLR with parameters I try to make a CLR in C# to use in SQLServer Management Studio 2014. Everything's working fine right now, unless I start to insert parameters.
How do you insert a parameter in the CLR and use it in a PROC?
I tried to put the parameters in the function parentheses:
public static void InsertInto(SqlString street, SqlInt32 number)
    {
        using(SqlConnection conn = new SqlConnection("context connection = true"))
        {
            SqlCommand comm = new SqlCommand();
            comm.CommandText = "INSERT INTO TABLE_CLRTEST (COLRW_STREET, COLRW_NUMBER) VALUES("+street+","+number+")";

I cannot seem to concatenate the SqlString, and it won't let me use a String either.
And in C# and I tried like this:
comm.CommandText = "INSERT INTO TABLE_CLRTEST (COLRW_STREET, COLRW_NUMBER) VALUES(@street,@number)";

            comm.Parameters.Add("@street", SqlDbType.VarChar,50);
            comm.Parameters.Add("@number", SqlDbType.Int);

When I use this is get the following error: CREATE PROCEDURE failed because parameter counts do not match. So still nothing.
Do you guys/girls know what is going on? If you need clarification, just ask.
Thanks in advance
EDIT:
The code snippet provided below is working. It seems that Strings just won't work.
public static void updateTest(SqlInt32 lo, SqlInt32 la)
    {
        using (SqlConnection conn = new SqlConnection("context connection = true"))
        {
conn.Open();
                SqlCommand update = new SqlCommand();
                update.CommandText = "UPDATE TABLE_CLRTEST SET COLRW_LONGITUDE = " + lo + ", COLRW_LATITUDE = " + la + "";
                update.Connection = conn;
                update.ExecuteNonQuery();
                conn.Close();
}
}

A: comm.CommandText = "INSERT INTO TABLE_CLRTEST (COLRW_STREET    , COLRW_NUMBER)
                                        VALUES('" + street + "'," + number +" )";

In your parameters you are not assigning a value.
comm.Parameters.Add(
   "@street", SqlDbType.VarChar,50).Value = street;

A: I forgot the Add statement.
Final code:
SqlCommand command = new SqlCommand();
SqlParameter pstreet = new SqlParameter("@street", SqlDbType.VarChar, 150);
command.CommandText = "INSERT INTO CHIEF_TEST.dbo.TABLE_CLRTEST(COLRW_STREET) VALUES(@street)";
command.Parameters.Add(pstreet);


text:
Q: How many users are connecting from North Korea? According to this article in Wikipedia:

North Korea is almost completely isolated from the rest of the world
and, while there is a public telephone network, there is no broadband
data network. According to one report released in 2009, many North
Koreans had never heard of the Internet.

Is there any data available indicating whether anyone is connecting to one of the Stack Exchange sites with an IP address from North Korea?
(Using this query I could find two users who claim that they are from North Korea, but that's not very conclusive.)

A: Quantcast says, for Stack Overflow: about 432 per month (out of 14.9 million in total).
For SE wide details, you'll need to add the country code KP to the URL manually, as it's not listed otherwise.

A: According to Google Analytics we had a couple dozen daily visits between July and October 2011, but then the number dropped to zero and we haven't had a visit from that country since October 25th.


text:
Q: AJAX y Query Wordpress, ¿como unir AJAX con una consulta Query Wordpress? Estoy intentando hacer un buscador para una tabla que se genera a través de una consulta Query Wordpress, logro hacer AJAX pero no se como unir la respuesta de AJAX  con una variable en php para unirla al Query de WordPress, sé que es posible, pero estoy algo embotado y llevo horas con esto
Este el fichero
buscadorProfesiones.php
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <input type="text" id="idioma" placeholder="Idioma a buscar">

    <input type="button" name="enviar" value="Enviar" href="javascript:;"
        onclick="searchIdioma($('#idioma').val());">

<?php

require_once("../wp-load.php");
switch_to_blog(5);
// QUERY WP
$args = array(
    'post_type'              => array( 'profesiones' ),
    'posts_per_page'         => -1,
    'post_status'            => array( 'publish' ),
    'meta_key'               => 'nombre_profesion',
    'meta_query'             => array(
        array(
                'relation'  => 'AND',
                array(
                    'key'     =>  'organizaciones',
                    'value'   =>  $busquedaIdioma,
                    'compare' => 'LIKE'
                )
            )
    ),
    'orderby'    => 'meta_value',
    'order'     => 'ASC',
);

$query = new WP_Query( $args );
if ( $query->have_posts() ) :
    echo '

            Nombre de la profesion

';
    while ( $query->have_posts() ) :
        $query->the_post();
        echo '

                '.get_field('plural').'

';
    endwhile;
    echo '

';
endif;
wp_reset_query();
restore_current_blog();
?>

Este es el fichero que devuelve el dato
procesoAjax.php
<?php
echo $_POST["BusquedaIdioma"];
?>


text:
Q: Workaround for - Hibernate is not supporting batch insertion when using IDENTITY Workaround  for - Hibernate is not supporting batch insertion when using IDENTITY

For my app, I am using SpringBoot and SQL Server. I am having a big number of data that I need to insert to the database.
Both corresponding entities (Many-To-One relationship) for the insert defined with GenerationType.IDENTITY
@Entity
public class DailyExportContent {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "Id")
 private Integer id;
 @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
 @JoinColumn(name = "DailyExportContent2DailyExport", foreignKey = @ForeignKey(name =
 "FK_DailyExportContent_DailyExport"))
 private DailyExport dailyExport;

@Entity
public class DailyExport {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "Id")
 private Integer id;

Per my understanding, Hibernate is not supporting batch insertion when using IDENTITY.

Hibernate disables insert batching at the JDBC level transparently if
you use an identity identifier generator.

Are there any generic workaround beside of removing the IDENTITY?


text:
Q: SQL query to compare between 2 reports timestamp and show increase/decrease trend I am using below query to get Input_MB and Output_MB for current timestamp.
However i need to compare with previous 1 hour data  how the input and out put value was there for the same rows. Based on that i need to put increase/decrease trend.
Query i used for getting 9:30 and 10:30 report is:
SELECT
  A.last_updated,
  B.SERVER AS Server,
  D.STREAM_NAME AS Stream,
  A.INPUT AS Input,
  A.OUTPUT AS Output
FROM table1 A,
     table2 B,
     table3 C,
     table4 D
WHERE A.ALARM_BACKLOG = '1'
AND C.MONIT_STATUS = 'ACTIVE'
AND A.NODE_MAN_ID = B.NODE_MAN_ID
AND A.NODE_ID = C.NODE_ID
AND B.STR_ID = D.STR_ID
AND B.NODE_MAN_ID = C.NODE_MAN_ID
ORDER BY NM.HOST_SERVER_NAME, S.STREAM_NAME DESC

Suppose 9:30 AM report is:
Last_updated    Server  stream  input   output
9:30 AM A   1   80  0
9:30 AM EFH 7   8   20
9:30 AM D   5   60  0
9:30 AM E   8   25  100

and 10:30 AM report supposed to be:
Last_updated    Server  stream  input   output
10:30 AM    A   1   40  0
10:30 AM    C   7   0   8
10:30 AM    D   5   72  0
10:30 AM    B   3   0   0
10:30 AM    E   8   25  115

However i want 10:30 report should come as below.
Last_updated    Server  stream  input   "Input
Trend"  output  "Output
 Trend"
10:30 AM    A   1   40  50%-Down    0   No change
10:30 AM    C   7   0   New 8   New
10:30 AM    D   5   72  20%- Up 0   New
10:30 AM    B   3   0   New 0   New
10:30 AM    E   8   25  No change   15%-Up  New

A: Maybe try this (i wrote without test)
  Select A.last_updated, A.SERVER, B.Stream,A.INPUT,
Case
    When B.INPUT is Null Then 'New'
    When A.INPUT=B.INPUT Then 'No change'
    When A.INPUT<B.INPUT Then Cast((B.INPUT-A.INPUT)/B.INPUT*100 as Varchar(10))+'%-Down'
    When A.INPUT>B.INPUT Then Cast((A.INPUT-B.INPUT)/B.INPUT*100 as Varchar(10))+'%-Up'
End INPUT_TREND,
A.OUTPUT,
Case
    When B.OUTPUT is Null Then 'New'
    When A.OUTPUT=B.OUTPUT Then 'No change'
    When A.OUTPUT<B.OUTPUT Then Cast((B.OUTPUT-A.OUTPUT)/B.OUTPUT*100 as Varchar(10))+'%-Down'
    When A.OUTPUT>B.OUTPUT Then Cast((A.OUTPUT-B.OUTPUT)/B.OUTPUT*100 as Varchar(10))+'%-Up'
End INPUT_TREND

From
(
 Select A.last_updated, B.SERVER, D.STREAM_NAME as Stream, A.INPUT, A.OUTPUT ,RANK() OVER (ORDER BY A.last_updated Desc) Row_id
 From table1 A
 Join table2 B on A.NODE_MAN_ID = B.NODE_MAN_ID
 Join table3 C on A.NODE_ID = C.NODE_ID and  B.NODE_MAN_ID= C.NODE_MAN_ID
 Join table4 D on B.STR_ID = D.STR_ID
 Where A.ALARM_BACKLOG = '1' and C.MONIT_STATUS = 'ACTIVE') A
Left join
(
 Select A.last_updated, B.SERVER, D.STREAM_NAME as Stream, A.INPUT, A.OUTPUT,RANK() OVER (ORDER BY A.last_updated Desc) Row_id
 From table1 A
 Join table2 B on A.NODE_MAN_ID = B.NODE_MAN_ID
 Join table3 C on A.NODE_ID = C.NODE_ID and  B.NODE_MAN_ID= C.NODE_MAN_ID
 Join table4 D on B.STR_ID = D.STR_ID
 Where A.ALARM_BACKLOG = '1' and C.MONIT_STATUS = 'ACTIVE') B on B.Row_id=A.Row_id+1 and A.SERVER=B.SERVER and A.Stream=B.Stream
Where A.last_updated='10:30 AM'


text:
Q: If a BroadCastReceiver running in a non-default starts a Service, in what process will that Service run? Trying to get my mind around how processes work in Android.
Let's say that I have a PendingService called FancyService and an Alarm Receiver:
<receiver
  android:name=".FancyAlarmReceiver"
  android:process=":remote" />
<service
  android:name=".FancyService"
  android:exported="false" />

Notice that the receiver is process=remote, but the service is not.
Now, let's imagine that the AlarmReceiver just kicks off FancyService...
public class FancyAlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyTestService.class);
        i.setAction(intent.getAction());
        context.startService(i);
    }
}

... then in what process will the service run in? The default process, or the :remote process?

A: Answering my own question here: The service will run on the default thread, not the remote thread.
I just did an experiment, putting Log.i in the onReceive of the AlarmReceiver, and in the onHandleIntent of the FancyService, and looked in the Android Monitor which process the logs appeared in. The FancyService does indeed log on the main, default process even though it's started by the AlarmReceiver from the :remote thread (and that does indeed log on the remote thread).


text:
Q: Using Windows Forms in powershell class I'm trying to make my current Powershell code a little cleaner by using classes. I'm trying to make a Window class using Windows.Forms but I seem to be having trouble with it. This is what I currently have so far:
Window.psm1
using assembly System.Windows.Forms;

class Window {
    [System.Windows.Forms.Form]$Form;

    Window() {
        $this.Form = New-Object System.Windows.Forms.Form;
    }

    [void]BuildWindow() {
        $this.Form.ClientSize                            = New-Object System.Drawing.Point(600, 400)
        $this.Form.Text                                  = "Orion"
        $this.Form.TopMost                               = $false
        $this.Form.FormBorderStyle                       = "Fixed3D"
        $this.Form.MaximizeBox                           = $false
    }

    [void]ShowWindow() {
        $this.Form.ShowDialog();
    }
}

I'm then instantiating it in my start.ps1:
using module ".\Window.psm1";

$WindowObject = New-Object Window;

$WindowObject.BuildWindow();
$WindowObject.ShowWindow();

However, I'm getting the following error:
At C:\Orion\scripts\Window.psm1:4 char:6
+     [System.Windows.Forms.Form]$Form;
+      ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
    + CategoryInfo          : InvalidOperation: (C:\Orion\scripts\Window.psm1:String) [], ParentContainsErrorRecordExc
   eption
    + FullyQualifiedErrorId : TypeNotFound

I'm new to Powershell scripting and classes especially, so I'm not sure what is going wrong here.

A: To clarify, your code as-is, works perfectly fine in a newer version of PowerShell (tested on the latest, 7.2.3). The issue is exclusively on Windows PowerShell, and to be honest, it's hard to explain why the error occurs however I can provide you what worked for me on that version.
using assembly System.Windows.Forms

class Window {
    [System.Windows.Forms.Form] $Form = [System.Windows.Forms.Form]::new()

    Window() { } # Removing the instantiation of the form from the ctor

    [void] BuildWindow() {
        $this.Form.ClientSize      = [System.Drawing.Point]::new(600, 400)
        $this.Form.Text            = "Orion"
        $this.Form.TopMost         = $false
        $this.Form.FormBorderStyle = "Fixed3D"
        $this.Form.MaximizeBox     = $false
    }

    [void] ShowWindow() {
        $this.Form.ShowDialog();
    }
}

On a personal note, I don't think having classes is a good idea when working with Windows Forms, it will make your code harder to read and by the looks of it, each form control will have their own hard-coded values which will be very hard to maintain and very hard to debug.
# would make more sense:
$form = [System.Windows.Forms.Form]@{
    ClientSize      = [System.Drawing.Point]::new(600, 400)
    Text            = "Orion"
    TopMost         = $false
    FormBorderStyle = "Fixed3D"
    MaximizeBox     = $false
}
$form.ShowDialog()


text:
Q: Example showing that $\mathbb{P}^1$ does not preserve monics Is there an injective homomorphism of commutative rings $A \to B$ such that the induced map $\mathbb{P}^1(A) \to \mathbb{P}^1(B)$ is not injective? Here, $\mathbb{P}^1(A) = \mathrm{Hom}(\mathrm{Spec}(A),\mathbb{P}^1)$ is the set of equivalence classes of invertible quotients of $A^2$.
It is easy to check that the map is injective on the subset of free quotients of $A^2$, i.e. points which can be defined by homogeneous coordinates. In particular, the whole map is injective if $\mathrm{Pic}(A)$ is trivial.
Edit. Sorry now I realize that this is a rather stupid question. If $X$ is any separated scheme and $f : A \to B$ is injective, then $X(A) \to X(B)$ is injective as well.

A: There is no such injective ring homomorphism.  For every pair of rank $1$, locally free quotient $A$-modules, $$q_i:A^{\oplus 2}\twoheadrightarrow Q_i,\ i=1,2,$$ there exists a finite set of elements of $A$, say $(a_j)_{j=1,\dots,n}$, generating the unit ideal and trivializations $$h_{i,j}:Q_i[1/a_j]\xrightarrow{\cong} A[1/a_j].$$  Consider the compositions, $$h_{i,j}\circ q_i: A[1/a_j]^{\oplus 2}\twoheadrightarrow A[1/a_j].$$  If the induced morphisms $g_{B,i}:B^{\oplus 2}\twoheadrightarrow B\otimes_A Q_i$ are equal as morphisms from $\text{Spec}(B)$ to $\mathbb{P}^1$, then there exists an elements $\beta_{(1,2),j}$ and $\beta_{(2,1),j}$ of $B[1/a_j]$ such that the composition $h_{2,j,B}$ equals the scalar product of $\beta_{(1,2),j}$ and the composition $h_{1,j,B}$, and similarly $h_{1,j,B}$ equals the scalar product of $\beta_{(2,1),j}$ and $h_{2,j,B}$.  By surjectivity of $h_{i,j,B}$, also $\beta_{(2,1),j}\cdot \beta_{(1,2),j}$ equals $1$.
Since $h_{i,j}$ is surjective, there exists an element $u_{i,j}$ that maps to $1$.  Thus, $\beta_{(1,2),j}$ equals the image in $B[1/a_j]$ of $\alpha_{(1,2),j}:=h_{2,j}(u_{1,j})$, and $\beta_{(2,1),j}$ equals the image of $\alpha_{(2,1),j}:=h_{1,j}(u_{2,j})$.
Since $A[1/a_j]$ is a flat $A$-module, also $A[1/a_j]\to B[1/a_j]$ is injective.  Since the composition $h_{2,j}$ equals the scalar multiple of $\alpha_{(1,2),j}$ with $h_{1,j}$ after base change to $B[1/a_j]$, these $A[1/a_j]$-module homomorphisms are equal.  Similarly, $h_{1,j}$ equals the scalar multiple of $\alpha_{(2,1),j}$ and $h_{2,j}$.  Since the base change to $B[1/a_j]$ of $\alpha_{(1,2),j}\cdot \alpha_{(2,1),j}$ equals the base change of $1$, also $\alpha_{(1,2),j}\cdot \alpha_{(2,1),j}$ equals $1$.  Thus, the morphisms $f_1$ and $f_2$ are equal.


text:
Q: Android app user login activity I have an internal-use Android app which requires users to always login. My app consists of a dashboard which will have 4 available actions on it to perform.
What is the best practice? Set LoginActivity to be the main activity, or use the DashboardActivity as the main and on startup show login screen if user is not logged?
Thanks!

A: I would recommend using the login activity and use SharedPreferences to pass on the username once the user logs in correctly to the app for the first time. The user would remain logged in until he logs out of it (either manually or by deleting the app data from the phone settings).
The function of the SharedPrefences is to keep the user details in the app, even after the user goes to a different app. The credentials are kept when he/she uses them again once the user uses the app again. If you have developed for web applications beforehand, it is somewhat similar to the function of cookies, only more secure, since these credentials are kept hidden in the app.
A very good tutorial on how to implement this.
You can use the first loginActivitiy for the first time a user logs in. Then once the user returns to the app, he/she would be taken to the main page of the app (the next activity after a login is successful). This can be achieved though a few lines of code as in this post.