text:
Q: USE RIGHT with CHARINDEX using string with multiple characters fails I have a a text filed which I need to get just a part of the string from the left.
select top 100 Description, right(Description,
charindex('', reverse(Description))-1)
as CleanedDesc
from MyDB.dbo.MyTable_output

when rung the query if tails with the following error:
Invalid length parameter passed to the RIGHT function.
This is actually correct as I specified charindex(''
which is not right, it has to be a single character, but unfortunately but text value "separator is exactly  .
Below is the sample of string data which you can use for testing:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">      <title></title>      Added: <input type="hidden" name="dnf_class_values[procurement_notice][description][0][added_on]" value="2017-06-19 10:32:17">Jun 19, 2017 10:32 am This solicitation will contain NSN 1d2323, OIL. A Request for Proposal (RFP) will be issued for award .....ed item and must be acquired from an approved manufacturer. The approved sources are:
  SEYER INDUSTRIES, INC. 19494 P/N 74A150625-1006

A: I kind of found workaround. That is to replace '' using CTE with a character that I make sure is not present in the Description column. I scanned my table using this code
 select * from  MyDB.dbo.MyTable_output where Description like '%~%'.

But I do have some records that do have this values "~". So it's not an option.
But even if I would not found any that does not seem to be practical solution in the long run
;with cte as (
select top 100 RowNo, replace(Description, '','~') as ReplacedDesc from InputTemp.dbo.SearchFBO_output
)
select
RowNo = ROW_NUMBER() OVER (ORDER BY EntityPKID),
Project,
[Title],

RIGHT(cte.ReplacedDesc, charindex('~', reverse(cte.ReplacedDesc))-1) as Description,

FROM
 MyDB.dbo.MyTable_output o
INNER JOIN cte ON cte.RowNo = o.RowNo

A: Not 100% sure if this is what you are looking for, but you can play with the delimiters.
If open to a Table-Valued Function, consider the following:
Tired of extracting data ... left, right, charindex, reverse, ... I modified a parse function to accept two non like delimiters (up to 100 characters not one).
Example or dbFiddle
Declare @YourTable table ([ID] int,[Description] varchar(max))
Insert Into @YourTable values
(1,'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">      <title></title>      Added: <input type="hidden" name="dnf_class_values[procurement_notice][description][0][added_on]" value="2017-06-19 10:32:17">Jun 19, 2017 10:32 am This solicitation will contain NSN 1d2323, OIL. A Request for Proposal (RFP) will be issued for award .....ed item and must be acquired from an approved manufacturer. The approved sources are:
  SEYER INDUSTRIES, INC. 19494 P/N 74A150625-1006
')

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply [dbo].[tvf-Str-Extract]([Description],'>','''

Returns
ID  RetSeq  RetPos  RetVal
1   1       262     Jun 19, 2017 10:32 am

Now, if the delimeters were > and <, the following would be returned
ID  RetSeq  RetPos  RetVal
1   7   136 Added:
1   8   262 Jun 19, 2017 10:32 am
1   9   290  This solicitation will contain NSN 1d2323, OIL. A Request for Proposal (RFP) will be issued for award .....ed item and must be acquired from an approved manufacturer. The approved sources are:
1   10  487   SEYER INDUSTRIES, INC. 19494 P/N 74A150625-1006

The UDF if Interested
CREATE FUNCTION [dbo].[tvf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table
As
Return (

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
 From  (
        Select *,RetVal = Substring(@String, N, L)
         From  cte4
       ) A
 Where charindex(@Delimiter2,RetVal)>1

)
/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[tvf-Str-Extract] (@String,'[[',']]')
*/

EDIT - Regarding Comment

You may notice I added a silly ending delimiter of |||
Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply [dbo].[tvf-Str-Extract]([Description]+'|||','','|||') B
 Where RetVal>''


text:
Q: Back-quote identifier within interpolated string Say I use an arbitrary identifier as field name:
object A { val `type` = "x" }

How can I refer to it in an interpolated string?
I tried
object A {
  val `type` = "x"
  override def toString() = s"$type"
}

but got a compiler error:
error: error in interpolated string: identifier or block expected
    override def toString() = s"$type"

and if I try
object A {
  val `type` = "x"
  override def toString() = s"$`type`"
}

I get
error: invalid string interpolation: `$$', `$'ident or `$'BlockExpr expected
    override def toString() = s"$`type`"

A: I think I found the solution, have to put the back-quote identifier in braces:
object A {
  val `type` = "x"
  override def toString() = s"${`type`}"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Friction fire lighting Having watched a few youtube guides on making a fire by friction, namely the spindle and fireboard method, I've heard many of the instructors talk about how the shape of the spindle at its ends should be point-like at the top and blunt/round at the bottom. They then go attribute this to the idea that one would want as little friction at the top and most friction at the bottom. Whilst this seems to be intuitively correct, my very basic knowledge of physics tells me that idealised friction is independent of apparent surface area and just proportional to the normal force (also proportional to actual contact area?). I tried thinking about this in terms of energy but still couldn't get my head around it. I also find it difficult to believe that the consensus of many, especially those with years of experience find this to be the case. It seems unlikely,though not impossible, that they have all come to wrong conclusion. So, my question is this: Is a blunt end for a spindle better than a sharp point, or is the shape irrelevant and if so how might you reconcile these 2 ideas (are they all wrong?)? Also if you have any empirical evidence to back this, or links to, that would be greatly appreciated.

A: You want a point at top and a flat area at bottom.  You want most of the friction torque to be at the bottom where you are trying to create embers.
Given the same material, ideally the friction force is proportional to the normal force and the speed.  However, the friction torque of a rotating shaft is proportional to these times the radius.  It is this torque times the rotational speed that makes power, which causes the heat to make the embers.  Added to that, the friction is probably not that ideal and viscous.
What spins better on your table, a top or a coffee cup of the same weight?  Obviously the coffee cup stops spining much faster than the top.  Intuitively you can see that the coffee cup has much more friction against spinning than the top does.  This friction times rotation rate causes power to be dissipated as heat at the interface.

A: Well, I'm not sure if you can use the ideal friction for this case. But the surface area does matter, if you want to light something up.
Given the same normal force over 2 different surface areas, you would experience the same resistive force right? So given the same moving velocity (simplification), the power dissipation should be the same.
The question then simplifies to: Is it easier to set the material on fire to concentrate this power in a small area or let it spread over a larger area? I think the answer is obvious at this stage.


text:
Q: While Loop is not getting entered which I have in my one of the step as part of stepdefinition file Logic provided in the while loop is not running even though the condition is met. This is the step definition file  for  selenium using cucumber.
@Then("checks for the title of the page")
public void checks_for_the_title_of_the_page() {

        String password1 = "";
        String title = driver.getTitle();
        System.out.println("Title of current page: " +title );
        System.out.println("I am right before control statement now" );
        while (title == "Amazon Sign In") {
            System.out.println("Contol is in while loop");
            lg.getpassword().sendKeys(password1);
            String captchaVal1 = JOptionPane.showInputDialog("Please enter the captcha value:");
            driver.findElement(By.id("auth-captcha-guess")).sendKeys(captchaVal1);
            driver.findElement(By.id("signInSubmit")).click();
        }
    }


text:
Q: Проверка наличия COM порта Как проверить подключён COM-порт или нет?
Например, пользователь выбрал COM 3, но во время работы этот порт был отключён.
Как грамотно выполнить проверку присутствует ли COM-порт и возможно ли его открыть?
На данный момент делаю вот так(пример):
SerialPort port = new SerialPort("COM 8");
string[] allport = SerialPort.GetPortNames();
bool stat = false;
for (int i = 0; i < allport.Length; i++)
{
    if (allport[i] == port.PortName)
    {
        stat = true;
        break;
    }
}
if (stat)
    port.Open();
else
    Console.WriteLine("{0} отключен.", port.PortName);

Но уверен, что данною операцию можно реализовать грамотней.

A: Ваш код можно немного изменить используя метод Any(...). Можно создать вот такой метод, который принимает имя порта, проверяет, содержится ли это имя в списке имен последовательных портов текущего компьютера, а затем уже попытаемся открыть порт:
static void OpenPort(string portName)
{
   if (SerialPort.GetPortNames().Any(x => x == portName))
   {
       // если такой порт есть, то попробуем открыть его и сделать что-то еще...
       var port = new SerialPort(portName);
       try
       {
          port.Open();
          // здесь может быть код еще...
       }
       catch (Exception ex)
       {
          // что-то пошло не так и упало исключение... Выведем сообщение исключения
          Console.WriteLine(string.Format("Port:'{0}' Error:'{1}'", portName, ex.Message));
       }
   }
}

А затем просто вызывать этот метод, передавая туда имя интересующего вас порта.

Метод SerialPort.GetPortNames() - возвращает массив имен
  последовательных портов для текущего компьютера.

A: Насколько я понимаю, порт может быть отключён в любой момент. Поэтому я бы делал так: работал с портом как обычно, а при приходе IOException говорил бы пользователю о проблемах при коммуникации с портом.
Проверять можно через
using System.IO.Ports;

var port = new SerialPort("COM99");
port.Open(); // бросает исключение, если порта нет

или
SerialPort.GetPortNames().Contains("COM99")

(как делаете это вы).
Но отлова исключений всё равно не избежать, т. к. порт может появиться или исчезнуть сразу после проверки.


text:
Q: How to invoke function call if it is defined as var? I'm getting data from server using JQuery and JSON. I defined getBooksDoneFunc
as variable because I need to be able to call this function not only once (when getBooks is done) . Unfortunately, I cannot call getBooksDoneFunc from inside of signInOK as window["getBooksDoneFunc"]();. Why? What is the best way to call this function?
function getBooks(){     return $.getJSON( "bookstore.json" );             }

var getBooksDoneFunc = function(json) {
         $.each(json.books, function(i, json){ .......... });

}

getBooks().done(getBooksDoneFunc);

function signInOK(){
         window["getBooksDoneFunc"]();
}

PS. The idea for window["getBooksDoneFunc"](); was taken from SO answer
UPDATE:
var booksJSON = {};
window["getBooksDoneFunc"](booksJSON);

getBooksDoneFunc must be called with parameters nevertheless the call to getBooksDoneFunc fails. signInOK is defined outside of $(document).ready(function(){ }); but called inside of it.

A: Try:
function getBooks(){
  return $.getJSON( "bookstore.json" );
}

window.getBooksDoneFunc = function(json) {
  $.each(json.books, function(i, json){ .......... });
}

getBooks().done(getBooksDoneFunc);

$(document)ready(function() {
  function signInOK(){
    var booksJSON = {};
    window.getBooksDoneFunc(booksJSON);
  }
});

A: If window["getBooksDoneFunc"](); works, then does getBooksDoneFunc(), the idea of using window is when you want to access a global function but you don't know the function name which is stored in a variable.
In your case, put a hardcoding string is mean less, just do getBooksDoneFunc() is the same, because you already store the function self (not the string of function name) in the variable.
The thing that won't work is that if  the variable is not global, please check the scope.

A: I would do this a bit differently, although I do not really understand the signInOK() function. How will it receive the "json" data. I would reconstruct the getBooks function and rethink the signInOk function. Here's a start:
function getBooks() {
    $.getJSON("bookstore.json").done(function (json) {
        getBooksDoneFunc(json);
    });
}

var getBooksDoneFunc = function(json) {
     $.each(json.books, function(i, json){ .......... });

};

...

getBooks();

function signInOK(){
     getBooksDoneFunc("some json data");
}


text:
Q: How do you rectify a 3D planar polygon? I have a 3D planar (all vertices lie in some plane) polygon with vertices: [(x1, y1, z1) ... (x1, y1, z1)].

I would like to transform this polygon so that I'm viewing it orthographically (as if I'm looking at it straight on).

How can this be done in Python?

A: I assume you have no information except for vertex coordinates.
Take three non-collinear (perhaps consequent) vertices C, A, B. Calculate normalized vector (divide by vector length)
b = (B - A) / |B - A|

then normal vector (using vector/cross multiplication)
N = b.cross.(A-C) and normalize it
un = N / |N|

and another unit vector in polygon plane
v = b.cross.n

Now we want find such matrix of affine transformations, that transforms vertex A into point (0,0,0), edge AB will be collinear with OX axis, normal will be collinear with OZ axis, vector q will be collinear with OY axis. This all means that rotated polygon will lie in OXY plane.
Mathematically: points A, u=A+b, v=A+q, n=A+un should be transformed in quadruplet (0,0,0), (1,0,0), (0,1,0), (0,0,1). In matrix form
      [Ax ux vx nx]   [0 1 0 0]
 M *  [Ay uy vy ny] = [0 0 1 0]
      [Az uz vz nz]   [0 0 0 1]
      [1  1  1  1 ]   [1 1 1 1]

or
  M * S = D

Using matrix inverse
  M * S * Sinv = D * Sinv

and finally
  M = D * Sinv

So calculate matrix M and multiply it with every vertex coordinates. New coordinates should have zero Z-component (or very small due to numerical errors).
You can perform all described operations with numpy library with a little code
Example with specific data
Quick-made implementation in plain Python for reference
import math
def calcMatrix(ax, bx, cx, ay, by, cy, az, bz, cz):
    ux, uy, uz = bx - ax, by - ay, bz - az
    mag = math.sqrt(ux*ux+uy*uy +uz*uz)
    ux, uy, uz = ux / mag, uy / mag, uz / mag
    Cx, Cy, Cz = ax - cx, ay - cy, az - cz
    nx, ny, nz = uy * Cz - uz * Cy, uz * Cx - ux * Cz, ux * Cy - uy * Cx
    mag = math.sqrt(nx*nx+ny*ny+nz*nz)
    nx, ny, nz = nx / mag, ny / mag, nz / mag
    vx, vy, vz = uy * nz - uz * ny, uz * nx - ux * nz, ux * ny - uy * nx
    denom = 1.0 / (ux*ux+uy*uy + uz*uz)
    M = [[0.0]*4 for _ in range(4)]
    M[3][3] = 1.0

    M[0][0] = denom*(ux)
    M[0][1] = denom*(uy)
    M[0][2] = denom*(uz)
    M[0][3] = denom*(-ax*ux-ay*uy+az*uz)

    M[1][0] = denom*(vx)
    M[1][1] = denom*(vy)
    M[1][2] = denom*(vz)
    M[1][3] = -denom*(ax*vx-ay*vy+az*vz)

    M[2][0] = denom*(nx)
    M[2][1] = denom*(ny)
    M[2][2] = denom*(nz)
    M[2][3] = denom*(-ax*nx-ay*ny+az*nz)

    return M

def mult(M, vec):
    res = [0]*4
    for k in range(4):
        for i in range(4):
            res[k] += M[k][i] * vec[i]
    return res

#test corners and middle point
M = calcMatrix(1, 0, 0, 0, 1, 0, 0, 0, 1)
#print(M)
p = [1, 0, 0, 1]
print(mult(M, p))
p = [0, 1, 0, 1]
print(mult(M, p))
p = [0, 0, 1, 1]
print(mult(M, p))
p = [1/3, 1/3, 1/3, 1]
print(mult(M, p))

test results:
[0.0, 0.0, 0.0, 1.0]
[1.4142135623730951, 0.0, 0.0, 1.0]
[0.7071067811865476, 1.2247448713915892, 0.0, 1.0]
[0.7071067811865476, 0.4082482904638631, 1.1102230246251565e-16, 1.0]

A: Find a normal n to the polygon, by means of a cross-product between two non-parallel sides. Take the cross-product of n with a vertical vector, to get an horizontal vector u. Then take the cross product of n and u to get v, and normalize the vectors. u and v are parallel to the plane of the polygon and orthogonal to each other.
Finally, for every vertex p compute the 2D coordinates (p.u, p.v) which show you the polygon in its plane.
numpy supplies the cross and dot vector functions. Also linalg.norm (or sqrt(dot(v, v))).

A: Here's a robust approach using NumPy (project(); the rest is test code).
import numpy
import scipy.spatial

def project(x):
    # Center the plane on the origin
    x = x - numpy.mean(x, axis=0)
    # Compute the Singular Value Decomposition
    u, s, v = numpy.linalg.svd(x)
    # Return the top two principal components
    return u[:, :2] @ numpy.diag(s[:2])

def test():
    n = 10
    x = (numpy.random.rand(n, 2) @ numpy.random.rand(2, 3)) + numpy.random.rand(3)
    y = project(x)
    print(x.shape, y.shape)
    print(
        numpy.max(
            numpy.abs(
                scipy.spatial.distance_matrix(x, x)
                - scipy.spatial.distance_matrix(y, y)
            )
        )
    )

if __name__ == "__main__":
    test()

Sample output:
(10, 3) (10, 2)
5.551115123125783e-16


text:
Q: When to use .NET Settings vs config ? Are there any recommendations on when to use Application settings (not per user settings) vs. .config file <appsettings>?
Update
Looking to understand some of the finer and important differences  because they're both effectively key/value stores.
For example, I know modifying appsettings in web.config will recycle the web application.
Settings have been in .NET for a while now and I haven't bothered to look at them - maybe one is somewhat redundant, or using both at the same time doesn't make sense... that's the kind of detail I'm looking to understand and the reasons.

A: One point that seems to be overlooked from the answers so far is that .config files can be transformed using Transformation files.  These are available for Web.config files by default (in Visual Studio) and are enabled for arbitrary .config files with the SlowCheetah - XML Transforms add-in for Visual Studio (SlowCheetah also adds a previewer and applies transformations on build rather than just on deploy.

A: Application settings and config file appSettings sections are limited to key value pairs, which are good for simple settings, but if you need a data persistence that is more robust you might look at creating a custom configuration section for your application.  Here is stackoverflow article on creating a custom config section
Enjoy!

A: Application settings can be typed, which is a plus compared to appsettings.
And the way you can access them is a little more neat (property) then getting a value from an array.
And you can use the interface to implement a settings class that stores you settings in a database.

A: The question is a bit old but I stumbled upon it and thought to add some clarity in case someone else also stumbles upon it...
The settings option (as opposed to the raw <appSettings> section) has strong support in the framework:

*

*Settings are strongly typed (i.e. bool, int, ConnectionString, etc) instead of all being returned as string to be parsed by your code if needs be.

*Settings can be scoped to be a) Internal or Public, and b) Per User or Per Application (the latter essentially meaning Per Machine).

*Your application would need to supply its own interface for changing the settings, but that's fairly trivial as the setting properties are read/write in code, and the generated class supplies functionality for saving the changes.

*The app.config (or web.config) file that is deployed, only stores the default values (see below for how runtime changes are handled) - which means that changing settings and saving them at runtime doesn't change the .config file - and by extension doesn't cause a restart of your application.

*Changes at runtime are saved to a local location (somewhere in either c:\ProgramData.. or c:\Users\MyUser\AppData\Local..) depending on the scope chosen. As such, subsequent releases of your application can safely introduce new settings without fear of trashing previously customized values, as they are safely stored away.
Hope that helps to clear things up a bit.

A: One thing to be aware of is, if you're deploying via ClickOnce despite the fact that config files are now writable they are not in a ClickOnce deployed app since that'll stuff with it's file hashes.
Therefore, the rule of thumb is that anything that's environment configuration goes in app.config. Anything that's user configuration goes in Settings.
Sometimes the line is a little fuzzy so for those fuzzy ones I would wrap in a static accessor method so that you can move them around at will.

A: Something I've done before is to create a class that contains properties appropriate to the settings to be persisted. A class instance is then XML serialized to a file, and can later be deserialized to get back the same object, property values intact. And the application will not need to be recycled, which it would if you write to the web.config/app.config file.
You can get strongly-typed application settings this way, and don't have to worry about keys and values. This has worked fairly well for me when I wanted to provide user-settable options within the application.

A: Application Settings do not get compiled into the assembly.
I'm not sure but I think that the Application Settings default values are compiled into the assembly, but these can be overridden in the config file.
I think Application Settings was created as a more friendly way of doing it, especially from VB.Net, but I don't think there's any huge differences. At least for simple settings I prefer Application Settings for the reasons in LeonG's answer.

A: I created a test app to explore as I've never bothered to look at Settings either.  Here are some random findings.

*

*Settings gives you an explicit property/name to reference in your code, but if you disassemble the compiled application, the getter is just looking up the value in its internal dictionary.

*Settings get spat back out into your .config file in their own section.  It would appear that you could just edit the .config file to change the value, but this isn't the case, kind of explained by the follwing point.

*According to the documentation linked above, it seems the only way to get to the value is to use Properties.Settings.Default.myColor = Color.AliceBlue; but this always gives you the default value, which is compiled into your code as an attribute for the property.  (I verified this using Reflector.  The getter is tagged with the following: [ApplicationScopedSetting, DefaultSettingValue("asdf"), DebuggerNonUserCode]).

*Settings are strongly typed.  The compiler will take care of serialization of the objects automatically (this is only a few lines of code, though).

Overall, they seem EXTREMELY similar.  The Settings dialog will give you a designer-y way to configure the values at design time, for what that's worth.  It will also handle serialization for your as well.  I'm sure there's some way to get the actual value instead of the default value, which would be a nice way to undo any user customizations if that's what you're storing (IE, instead of using the current value, just reference the Default value.)  I don't currently know how to reference the current value, though.


text:
Q: BULK API Status Not Found A simple bulk API which I am trying to create a JOB, and I am getting the status "NOT FOUND" and code: 400.
The same request working in the Workbench. Not sure what I am missing.
bulkApiController.createJob('POST');

System.HttpResponse[Status=Not Found, StatusCode=404]

private static final string RESOURCE_URI = '/services/data/46.0/jobs/ingest';

    public static HTTPResponse createJob(String method){
        String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
        String endpoint = baseURL+RESOURCE_URI;

        String reqBody ='{"operation" : "insert","object" : "Account","contentType" : "CSV","lineEnding" : "CRLF"}';

        HttpRequest req = new HttpRequest();
        req.setMethod(method);
        req.setEndpoint(endpoint);
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');
        req.setHeader('Accept', 'application/json');
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        req.setBody(reqBody);

        Http httpReq = new Http();
        HTTPResponse res = new HttpResponse();
        try{
            res = httpReq.send(req);
            System.debug('endpoint: '+res.toString());
        }catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            System.debug(res.toString());
        }
        return res;

    }

A: We have to add v to the version to work.
/services/data/v46.0/jobs/ingest


text:
Q: Proof that a certain combination of $I_{\nu}(z)$ Bessel functions is equal to exactly $1$ Consider the function for $x>0$ and $y>0$
$$
f(x,y) := \frac{\pi x^2}{2y} \mathrm{csch}\left( \frac{\pi y}{2} \right) \left( I_{-1-i y/2}(x) I_{-1+iy/2}(x) - I_{1-i y/2}(x) I_{1+i y/2}(x)  \right)
$$
where $I_{\nu}(z)$ is a modified Bessel function. It turns out that
$$
f(x,y) = 1
$$
which I have confirmed numerically.
How do you prove this? I have tried checking known cross-products of Bessel functions and cannot figure this out.

A: Take the Wronskian product
$$ I_{\nu}(z) I_{-1-\nu}(z) - I_{1+\nu}(z) I_{-\nu}(z) = -\frac{2\sin \nu\pi}{\pi z} $$
and apply the recurrence relation
$$ I_{\pm \nu}(z) = \pm \frac{2\nu}{z} ( I_{-1 \pm \nu}(z) + I_{1 \pm \nu}(z) ). $$
This gives, after some cancellation,
$$ -\frac{2\sin \nu\pi}{\pi z} = \frac{z}{2\nu} ( -I_{-1+\nu}(z) I_{-1-\nu}(z) - I_{1+\nu}(z) I_{-1-\nu}(z) ) , $$
which rearranges itself into your formula.


text:
Q: While remote debugging how are the pdb located (VS 2008) When the debugger is attached to a process on remote server -
What locations are searched for the pdb?
In what order?
(e.g. is it searched on the remote server (debuggee) or on the local client (debugger))
When I use the debugger to manually load pdb file from specific location - is the debugger looking for the file locally or is it the remote debugger monitor looking for the file on the?
Is there any article that describes that process?

A: The machine the debugger is running on loads the symbols (not the remote).
This article explains the basics of setting up where VS looks for symbols:

*

*http://msdn.microsoft.com/en-us/library/x54fht41(VS.90).aspx?ppud=4
This one explains how to set up a symbol server in the search path (which is particularly useful for Windows symbols):

*

*http://msdn.microsoft.com/en-us/library/b8ttk8zy(VS.90).aspx
There are a lot of pitfalls for remote debugging (mainly having to do with connectivity and permissions/authentication).  See the following page for a list of links that you'll want to read up for details:

*

*http://msdn.microsoft.com/en-us/library/y7f5zaaa(VS.90).aspx

A: Is there any article that describes that process?
As you know, when the debugger starts a session, it begins to search for the location where the appropriate PDB are located. The following article describes the mechanism and the search order of the process.


text:
Q: parse-server / Node.js / Heroku I am having these warnings:
npm WARN deprecated parse-server-fs-adapter@1.0.1: use @parse/fs-files-adapter
npm WARN deprecated parse-server-push-adapter@2.0.2: use @parse/push-adapter
npm WARN deprecated parse-server-s3-adapter@1.2.0: use @parse/s3-files-adapter
npm WARN deprecated parse-server-simple-mailgun-adapter@1.0.1: use @parse/simple-mailgun-adapter

when I run this command:
npm install

For information here are the version of npm and node I have:
$ npm --version
3.10.10
$ node --version
v6.11.2

Does anyone know what the way to get rid of the above warnings is?

A: It's actually because we moved our official adapters into @parse organization on NPM!
You can safely ignore those for now, parse-server will have those dependencies updates on the next release


text:
Q: ITTM busy beaver function VS Rayo's function It is known that both functions surpass the Busy Beaver function and $\Xi(n)$, but how do they compare with each other?
It seems that people thought I was confused with the definedness of Rayo's Function.
Edit: The whole of the problem comes because ITTM BB's grow faster than a theoretical ordinal that is the INFINITE SEQUENCE OF COMBINATIONS OF ORDINALS, each can have infinite size, that ordinal's ordinality is larger than $\beth_1$ (translated to ordinals), while Rayo's function can only take in a finite number of different symbols, each with finite length. Assuming this definition, $\mathrm{Rayo}(n) \lt \Sigma_\omega(n)$
But somehow this can be computed with infinite symbols or args.
Plus, in the Googology Wiki, it is unknown how they compare with each.

A: The Busy Beaver function for ITTMs is definable in $V$ (the universe of sets), whereas Rayo's function dominates every $V$-definable function. So Rayo's function is unspeakably larger.
OK, there is a subtlety here. When we define Rayo's function, we use a truth predicate for the whole universe of sets. This isn't something we can define unless we're working in a richer theoretical framework than mere set theory - some appropriate class theory is needed. So the precise statement of the above fact is that such an appropriate class theory proves that Rayo's function dominates every $V$-definable function, and in particular is much faster than the ITTM-Busy Beaver function.
(Specifically, if memory serves the class theory $\mathsf{MK}$ is the right theory to work with: it's the natural class theory which proves that Rayo's function actually exists. Meanwhile the weaker class theory $\mathsf{NBG}$ can't prove that Rayo's function exists, but can prove that if it exists it dominates the ITTM-Busy Beaver function.)


text:
Q: Interpretation of a three-level contrast in a linear mixed-effect model in R I have a linear mixed effect model in R where my fixed effect consists of three levels: Yes, No and Maybe
I have two research questions regarding these levels and my dependent variable:

*

*Is Yes smaller than No ?

*Where does Maybe stand in relation to Yes and No (closer to which)?

I specified centered contrast for my levels:
        -Yes+No  -Maybe+Yes&No
Maybe     0.0    -0.6666667
No        0.5     0.3333333
yes      -0.5     0.3333333

The output of the linear mixed effect model (the fixed effects part) is:
Fixed effects:
                           Estimate Std.  Error   t value
(Intercept)                  -2.24393    0.09051 -24.791
Grammaticallity-Yes+No       -0.82596    0.17168  -4.811
Grammaticallity-Maybe+Yes&No -0.73459    0.11753  -6.250

From this I can clearly see that the response to Yes is less negative than the response to No by -0.8 in the scale of my dependent variable.
My doubt is how to interpret the second contrast. I know by looking at bar graphs that the response to Maybe is the less negative of the three responses:

However, from the output I would interpret the response to Maybe is 0.7 more negative in the scale of my dependent variable than the average of the responses to Yes and No. However, this is clearly not the case, as the response to Maybe is more positive (less negative) than the responses to Yes and No.
I would appreciate any help to interpret and properly report the estimate of the second contrast comparing Maybe to the average of Yes and No.
Thanks in advance.


text:
Q: Mapping child classes with parent injected in the constructor using AutoMapper I have a following class structure:
class SrcChild
{
    public bool SomeProperty { get; set; }
}

class SrcParent
{
    public IEnumerable<SrcChild> Children { get; set; }
}

so the SrcParent has a collection of SrcChild objects.
Now I want to map an instance of SrcParent to DstParent. Here are the destination classes:
class DstChild
{
    public bool SomeProperty { get; set; }

    public DstChild(DstParent parent)
    {
        if (parent == null)
            throw new ArgumentNullException();
    }
}

class DstParent
{
    public IEnumerable<DstChild> Children { get; set; }
}

The DstParent has a collection of DstChild objects, that use constructor injection to keep a reference to their parent.
Using AutoMapper, I tried the following:
class Program
{
    static void Main(string[] args)
    {
        /* mapping configuration */
        Mapper.CreateMap<SrcChild, DstChild>()
            .ConstructUsing(
                resolutionContext => new DstChild((DstParent)resolutionContext.Parent.DestinationValue));
        Mapper.CreateMap<SrcParent, DstParent>();

        /* source parent object with two children */
        var srcParent = new SrcParent
        {
            Children = new[] { new SrcChild(), new SrcChild() }
        };

        /* throws an exception */
        var dstParent = Mapper.Map<DstParent>(srcParent);

        Console.ReadKey();
    }
}

The main part here is the AutoMapper configuration where I am trying to extract reference to the produced DstParent from mapping context. This doesn't work (the (DstParent)resolutionContext.Parent.DestinationValue is null), but maybe I'm completely missing a point here?
Another idea I had was to use a function to create the child values, something like this:
class Program
{
    /* Should produce value for DstParent.Children */
    private static IEnumerable<DstChild> MakeChildren(SrcParent src /*, DstParent dstParent */)
    {
        var result = new List<DstChild>();
        // result.Add(new DstChild(dstParent));
        return result;
    }

    static void Main(string[] args)
    {
        /* mapping configuration */
        Mapper.CreateMap<SrcChild, DstChild>();
        Mapper.CreateMap<SrcParent, DstParent>()
            .ForMember(dst => dst.Children,
                opt => opt.MapFrom(src => MakeChildren(src /*, How to obtain a reference to the destination here? */)));

        /* source parent object with two children */
        var srcParent = new SrcParent
        {
            Children = new[] { new SrcChild(), new SrcChild() }
        };

        var dstParent = Mapper.Map<DstParent>(srcParent);

        Console.ReadKey();
    }
}

but I don't know how (if even possible at all) to get reference to the DstParent object produced by the Mapper.
Does anyone have an idea how to do this or should I rather think of dropping this design altogether and get rid of the parent reference? Thanks in advance.

A: Ok, a solution that I found is not pretty, but it works:
class Program
{
    static IEnumerable<DstChild> MakeChildren(IEnumerable<SrcChild> srcChildren, DstParent dstParent)
    {
        var dstChildren = new List<DstChild>();
        foreach (SrcChild child in srcChildren)
        {
            var dstChild = new DstChild(dstParent);
            Mapper.Map(child, dstChild);
            dstChildren.Add(dstChild);
        }
        return dstChildren;
    }

    static void Main(string[] args)
    {
        Mapper.CreateMap<SrcChild, DstChild>();
        Mapper.CreateMap<SrcParent, DstParent>()
            /* Ignore Children property when creating DstParent*/
            .ForMember(dst => dst.Children, opt => opt.Ignore())
            /* After mapping is complete, populate the Children property */
            .AfterMap((srcParent, dstParent) =>
            {
                dstParent.Children = MakeChildren(srcParent.Children, dstParent);
            });

        var source = new SrcParent
        {
            Children = new[]
            {
                new SrcChild() {SomeProperty = true},
                new SrcChild() {SomeProperty = false}
            }
        };

        var destination = Mapper.Map<DstParent>(source);

        Console.ReadKey();
    }
}

The destination has children initialized, with SomeProperty properly assigned by AutoMapper. Please let me know if you find a better looking solution.


text:
Q: Best way to associate or group properties within a class? I'm new to creating objects, so I have question on the properties here. I'm creating a public class with a few sets of properties like the snippet below:
Public Class Template

    'General properties
Property ID As Integer
Property Name As String
Property Description As String
Property SupportedBrand As String

End class

Is there a way to "associate" properties with one another?  Say this group of properties is "general", these values are for "audio" and these for "video"? My inital reaction is to make a property that is a custom struct or list of these as enums but that doesn't seem to be right. Any suggestions?
I know that doing say Template.General.ID wouldn't be the right either since that is a separate module. My goal is being able to loop later to say "for each x property in generalProperties of this Template object".

A: You can add this attribute to your properties:
<Category("General")>

All properties with the same category name will be grouped together in the property window if grouping by category.  You can use reflection to get the attributes on the properties.  See this for an example on how to do that:
How to filter or find properties based on attributes


text:
Q: preRenderView-Event triggered before an action (commandbutton) I am in a little bit of trouble with my preRenderView-Event. My page also uses a commandbutton to submit data but unfortunately the preRenderView-Event is always called before the buttons action is invoked.
The preRenderView-Event is responsible for loading data from a service. Since the page is simple and doesnt have to store any data I dont need any Session or ViewScoped-Beans.
As far as I understood the event is called in the Render-Response-Phase and the action in the button should happen somewhat earlier.
<h:body>
    <f:metadata>
        <f:viewParam name="id" value="#{bean.id}" converter="converter.SetOfLongConverter"/>
        <f:event type="preRenderView" listener="#{bean.initializeData}" />
    </f:metadata>

    <ui:composition template="/META-INF/templates/myTemplate.xhtml">
        <ui:param name="title" value="#{bean.title}"/>
        <ui:define name="content">
            <h:outputText value="#{bean.description}" />
            <h:form>
                    <h:panelGrid columns="2">
                        <h:outputLabel value="Model" for="model" />
                        <h:inputText id="model" value="#{bean.model}" />
                        <h:outputLabel value="Manufacturer" for="manufacturer" />
                        <h:inputText id="manufacturer"
                            value="#{bean.manufacturer}" />
                        <h:outputLabel value="Year" for="year" />
                        <h:inputText id="year" value="#{bean.year}" />
                    </h:panelGrid>
                    <h:commandButton value="Create" type="submit"  action="#{bean.create}" rendered="#{bean.createMode}"/>
                    <h:commandButton value="Save" type="submit" action="#{bean.save}" rendered="#{!bean.createMode}" />
                </h:form>
        </ui:define>
    </ui:composition>
</h:body>

I added some Console-Messages to verify when the method in the bean is called and when I have the preRenderView-event it never happens.
Any advice what I am doing wrong here?

A: The <f:metadata> has to go inside <ui:define> of an <ui:composition>.
See also <f:metadata> tag documentation (emphasis mine):

Declare the metadata facet for this view. This must be a child of the <f:view>. This tag must reside within the top level XHTML file for the given viewId, or in a template client, but not in a template. The implementation must insure that the direct child of the facet is a UIPanel, even if there is only one child of the facet. The implementation must set the id of the UIPanel to be the value of the UIViewRoot.METADATA_FACET_NAME symbolic constant.

The simple reason is because the metadata is supposed to be view-specific, not template-specific.

Update: it turns out that the action method is not invoked at all. You've there a rendered attribute on the command button which seems according the symptoms to be dependent on a request based variable instead of a view based variable. Putting the managed bean in the view scope should fix this problem. See also commandButton/commandLink/ajax action/listener method not invoked or input value not updated


text:
Q: Filter a List of objects during debugging in Visual Studio 2013 I have a List<Student> that contains lets say 500 students. When I enter debug mode on a breakpoint is there a way to filter/search for a student?
I don't want to write code for this check as below:
List<Student> students = data.GetStudents();
//break here and filter for student in debug mode
var myStudent = students.Where(k=>k.StudentNumber=="S12312");

Is it is not possible in Visual Studio 2013 to do this, I think it would be a great feature to add...

A: Read this post debugging feature is now supported by visual studio 2015: http://blogs.msdn.com/b/visualstudioalm/archive/2014/11/12/support-for-debugging-lambda-expressions-with-visual-studio-2015.aspx
Check debugging option as per this image : http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-45-92-metablogapi/0882.image_5F00_thumb_5F00_13C96B25.png

A: You must install VS 2015
http://blogs.msdn.com/b/visualstudioalm/archive/2014/11/12/support-for-debugging-lambda-expressions-with-visual-studio-2015.aspx
Old versions does not support this.

A: You can use a 3rd party debugging tool called OzCode (disclaimer: I work for the company that makes it, though I don't work on the product myself).
It extends the QuickWatch debug window to allow searching within the object, looking for strings and values in all the object's properties. It's not a full lambda, but it lets you run a search several levels deep to find a value:


text:
Q: Boost of massless particle (eq 2.5.44) from Weinberg QFT In volume 1 of Weinberg QFT, equation (2.5.44), the general boost of one-particle state L(p) from standard momentum vector $K^\mu=(0,0,k,k)$ to $p^\mu$ is expressed as $$L(p)=R(\hat{p})B(\frac{|p|}{k}),$$ where $B$ means pure boost in $z$-direction and R represents pure rotation of $z$-axis into $\hat{p}$ direction.
I thought the right form should be $$L(p)= R(\hat{p})B(\frac{|p|}{k}) R^{-1}(\hat{p}).$$ Why isn't this correct? Could some one explain the eqn(2.5.44)?

A: Originally a comment, since I haven't read the chapter in a while, but it got too long -
Conceptually it seems like the first expression makes sense as long as $B(|p|/k)$ boosts in the direction given by $K^\mu$. The $B$ operator corrects the magnitude of $k$ to that of $|p|$, and then the rotation $R$ corrects the direction. I think the expression you gave would be if one wanted to only change the magnitude of the vector without rotating it, e.g. rotate it to the orientation along which the boost acts, then boost it, and then rotate back.

A: The point of defining $L(p)= R(\hat{p})B(\frac{|p|}{k}) R^{-1}(\hat{p})$ for massive particles was only that, first, $R^{-1}(\hat{p})$ doesn't make any difference to standard momentum of the massive particle, second, using this definition only, we recover the Wigner rotation that matches just the ordinary rotation. And, you could just use the whole non-relativistic QM formalism. Weinberg makes it a point to prove this starting under equation 2.5.24.


text:
Q: Rail switch for minecart station I've built a minecart station and have everything built but I can't seem to find a way to have a splitter so passenger carts go one way and storage carts go another way every time. I'm trying to create a system where pez dispensers have specific minecarts.

A: I have built a small redstone contraption that will determine if a mincart has an item in it or not, and sort it accordingly. Here you can see an overview of the machine:

Now step-by-step I will show you each part of the machine, and explain what it does. Please note I will be using redstone terminology.
Segment 1:

This section's job is to determine if the minecart going over it has an item in it or not. When any minecart goes over a detector rail, it will activate any redstone connected to it. What this detector rail does is deactivates the redstone torch next to the top hopper so that said hopper can accept an item from the minecart (if the minecart contains an item.) After that, the item stays in the hopper for just enough time to activate Segment 2, then passes to the bottom chest, where (if you would like) you can collect it. If there is no item, the machine is ignored, and the minecart will follow the normal path. This will be where players go.
Segment 2:

Segment 2's Job is to change the rail position if Segment 1 detects items present. A comparator will read if an item is in a hopper or not, so if an item passes into the top hopper, the comparator will turn on, deactivating the redstone torch seen to the left, making the curved rail in Segment 3 change positions. If no item is detected, the curved rail will keep the same position.
Segment 3:

Segment 3's job is to decide which path the minecart will go down depending on the info decided in Segments 1 + 2. The way the rail starts as (When the redstone torch is on [The right in this case]) will be where players go, and the other rail [The left in this case] will be where minecarts with items go.

Notes for building:
   - Although this was built on PC, all aspects remain the same in xbox-360 mode
   - Everything to the right of the right detector rail (in the overview) can be changed accordingly, and you do not have to use stone, but you must use a block redstone can pass through, AKA any solid block (if you need clarification on that, ask.)
   - Except for that ^, copy build EXACTLY including tick of redstone comparators.


text:
Q: Incrementing an unsigned char array I have a program that takes in an unsigned char ctr[24]. This is going to be used many times and I would like to have a new ctr for each operation. So I would need to either generate a random value each time, or I could initialize it to 0 and increment. I am after performance so generating a new value each time is probably going to be slow versus just incrementing. Is it possible to increment a unsigned char array?
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
Increment it by one...
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01
etc..
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02

A: You are vanishingly unlikely to really need to....
I mean if you just took the first 8 bytes and treated them as an uint64_t that would run a long, long, time before wrapping around.
Seems to me that some pointer casty stuff and that is job done for any likely use case.
Note that you might need to use some bytes in the middle of your 24 to ensure your memory is aligned suitably for a 64 bit access, but that is a triviality.

A: Treating unsigned char ctr[24] = {0}; as a counter initialized to 0, the 24 elements can be treated as digits of a base UCHAR_MAX+1 number. Based on the question, the "units" digit is to be stored in ctr[23], the "base1" digit in ctr[22], the "base2" digit in ctr[21], etc. When a digit with value UCHAR_MAX is incremented it will become 0 and a "carry bit" value of 1 needs to be added to the next digit position.
void increment(unsigned char ctr[static 24])
{
    unsigned int pos = 24;
    while (pos-- && ++ctr[pos] == 0)
        ;
}

The above function increments an unsigned char[24] in place. It first increments ctr[23] and if it has wrapped around to 0, increments ctr[22], and so forth until one of the digits has not wrapped around to 0, or all of the digits have wrapped around to 0.

A: void *inc(void *buff, size_t size)
{
    unsigned char *cbuff = buff;
    for(size_t index = 0; index < size; index++)
    {
        if(cbuff[index] == 255)
        {
            cbuff[index] = 0;
        }
        else
        {
            cbuff[index]++;
            break;
        }
    }
    return buff;
}

A:
I have a program that takes in a unsigned char ctr[24]. This is going to be used many times and I would like to have a new ctr for each operation. So I would need to either generate a random value each time, or I could initialize it to 0 and increment. I am after performance so generating a new value each time is probably going to be slow versus just incrementing. Is it possible to increment a unsigned char array?

Just don't.
Use a simple unsigned long long.  It's more than big enough.
At 3 billion increment operations per second, it would take 97 years to roll over a 64-bit value.
unsigned long long is big enough.

A: Something like this? untested
void add1_recur(unsigned char *x, int lo) {
    if (lo < 0) /* 192 bit overflow! */ exit(EXIT_FAILURE);
    if (x[lo] == 255) {
        x[lo] = 0;
        add1_recur(x, lo - 1;)
    } else {
        x[lo] += 1;
    }
}

// add 1 to x; assume x[0] is high order bit
void add1_inplace(unsigned char x[static 24]) {
    add1_recur(x, 23);
}

A: As far as I understand you just need a new pattern each time. Not necessarily a counter.
So would a union do?
Like:
typedef union
{
    uint64_t d64[3];
    unsigned char d8[24];
} ctr_t;

void p(unsigned char ca[])
{
    for (int i=0; i<24; ++i) printf("0x%02X ", ca[i]);
    puts("");
}

void change(ctr_t* ctr)
{
    // Do some change to each of the three uint64
    ++ctr->d64[0];
    --ctr->d64[1];
    ++ctr->d64[2];
}

int main(void) {
    ctr_t ctr = {{0, 0, 0xff00ff00ff}};  // Just some initialization
    p(ctr.d8);
    change(&ctr);
    p(ctr.d8);
    change(&ctr);
    p(ctr.d8);
    change(&ctr);
    p(ctr.d8);
    return 0;
}

Output
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFF 0x00 0xFF 0x00 0xFF 0x00 0x00 0x00
0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x00 0x01 0xFF 0x00 0xFF 0x00 0x00 0x00
0x02 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFE 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x01 0x01 0xFF 0x00 0xFF 0x00 0x00 0x00
0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFD 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x02 0x01 0xFF 0x00 0xFF 0x00 0x00 0x00


text:
Q: Help creating a simple function Can someone help me to create a function. The truth I'm new in Mathematica and I don't understand well the way functions work in I. I need a function that animate some rectangles according to a curve that I introduce as a vector depending on time. I already did this, but I don't want to do for every curve. The animation that I have is the next:
{Animate[Graphics[  {{Red,
     Polygon[{{0 , 0}, {1, 0}, {Flatten[a[t]][[1]] + 1,
        1}, {Flatten[a[t]][[1]], 1}}]}, {Blue,
     Polygon[{{Flatten[a[t]][[1]] + 1, 1}, {Flatten[a[t]][[1]],
        1}, {Flatten[a[t]][[2]], 2}, {Flatten[a[t]][[2]] + 1, 2}}]},
    {Green,
     Polygon[{{Flatten[a[t]][[2]] + 1, 2}, {Flatten[a[t]][[2]],
        2}, {Flatten[a[t]][[3]], 3}, {Flatten[a[t]][[3]] + 1, 3}}]},
    {Black,
     Polygon[{{Flatten[a[t]][[3]] + 1, 3}, {Flatten[a[t]][[3]],
        3}, {Flatten[a[t]][[4]], 4}, {Flatten[a[t]][[4]] + 1, 4}}]},
    {Orange,
     Polygon[{{Flatten[a[t]][[4]] + 1, 4}, {Flatten[a[t]][[4]],
        4}, {Flatten[a[t]][[5]], 5}, {Flatten[a[t]][[5]] + 1, 5}}]},
    {Blue,
     Polygon[{{Flatten[a[t]][[5]] + 1, 5}, {Flatten[a[t]][[5]],
        5}, {Flatten[a[t]][[6]], 6}, {Flatten[a[t]][[6]] + 1, 6}}]},
    {Pink,
     Polygon[{{Flatten[a[t]][[6]], 6}, {Flatten[a[t]][[6]] + 1,
        6}, {Flatten[a[t]][[7]] + 1, 7}, {Flatten[a[t]][[7]], 7}}]}},
   PlotRange -> {{-2, 2}, {0, 8}}]   , {t , 0, 2 Pi} ,
  AnimationRunning -> False]}

I was wondering if there is a way to transform this code into a function so I just call the function with a different vector and get the animation?

A: Perhaps something like
colors = {Red, Blue, Green, Black, Orange, Blue, Pink};
aA = Sin[t] RandomInteger[{1, 7}, {7}];

table = Table[{{aA[[k]] + 1, k}, {aA[[k]], k},
               {aA[[k + 1]], k + 1}, {aA[[k + 1]] + 1, k + 1}}, {k, 1, 6}];
polygons = Polygon /@ Prepend[table, Join[{{0, 0}, {1, 0}}, table[[1, ;; 2]]]];

Animate[Evaluate@ Graphics[Thread[{colors, polygons}], PlotRange -> {{-8, 8}, {0, 8}}],
       {t, 0, 2 Pi}, AnimationRunning -> False]

Change aC to
aC = Cos[t^2/2] RandomInteger[{1, 7}, {7}];

and {t, 0, 2 Pi} to {t, -2 Pi, 2 Pi} to get


text:
Q: Can create / edit groups file but can't change permission my scenario is:
2 users : firstUser and  secondUser in developers group.
This user connect to server with sftp;
if firstUser  create a file, this file was 775 , ownered by firstUser, group developers;
with secondUser i can edit and write this file but if i try:
 chmod 777 testfile.txt

I can't do that!

A: Could you provide the results of 'ls -l testfile.txt'.  There are two ways you can try to resolve this.  I am unsure if they would be the best approach but here they are.  Add a sudo prior to the chmod, e.g., 'sudo chmod 777 testfile.txt' and supply the root password.  Or you could change the owner, e.g., 'chown secondUser:developersgroup testfile.txt' then chmod.

A: only root or the owner can do that.


text:
Q: Changing Flex-Basis on different screen size I wonder why this doesn't work.

#parent {
  display: flex !important;
 flex-flow: row wrap;
  width: 100% !important;
 justify-content: flex-start;
}
.item{
 flex: 1 !important;
 flex-basis: calc(100% / 4);
 box-sizing: border-box ;
 border: solid 1px #000000;
 margin-bottom: 30px !important;
 max-width: 24%;
  height: 50px;
}

@media screen and (max-width: 767px) {
/* start of medium tablet styles */
 .item{
  flex-basis: calc(100% / 3) !important;
 }
}

@media screen and (max-width: 479px) {
/* start of phone styles */
 .item{
  flex-basis: calc(100% / 2) !important;
 }
}

I wanted to change the flex-basis of the flex items on the mobile and tablet screen. Normally, the row items should be 4 and in the tablet, it should be 3 then on mobile it should be 2.

A: You only need to remove max-width: 24%

#parent {
  display: flex !important;
 flex-flow: row wrap;
  width: 100% !important;
 justify-content: flex-start;
}
.item{
 flex: 1 !important;
 flex-basis: calc(100% / 4);
 box-sizing: border-box ;
 border: solid 1px #000000;
 margin-bottom: 30px !important;
  height: 50px;
}

@media screen and (max-width: 767px) {
/* start of medium tablet styles */
 .item{
  flex-basis: calc(100% / 3) !important;
 }
}

@media screen and (max-width: 479px) {
 .item{
  flex-basis: calc(100% / 2) !important;
 }
}

A: You got it wrong mate. I assumed you needed the max-width to make it not fully wide if the item is only 1.
Remove the max-width and the flex:1 and you should be good.
The flex: 1 is redundant of flex-basis: calc(100% / 4);.
The flex: 1 will make the item fully wide 100% while your telling it to divide the items into 4 groups/3 groups/2 groups using the flex-basis: calc(100% / 4);, so the max-width and flex: 1 is doesn't make any sense anymore.

#parent {
 display: flex !important;
 flex-flow: row wrap;
 width: 100% !important;
 justify-content: flex-start;
}
.item{
 flex-basis: calc(100% / 4);
 box-sizing: border-box ;
 border: solid 1px #000000;
 margin-bottom: 30px !important;
 height: 50px;
}

/* For tablet */
@media screen and (max-width: 767px) {
 .item{
  flex-basis: calc(100% / 3) !important;
 }
}

/* For mobile */
@media screen and (max-width: 479px) {
 .item{
  flex-basis: calc(100% / 2) !important;
 }
}


text:
Q: загрузка заказов (товары с модификациями) с сайта на МойСклад commerceML Возникла проблемка. Гугл не помог. Документация битрикса тоже(
https://dev.1c-bitrix.ru/api_help/sale/xml/documents.php
При загрузке заказов с сайта на МойСклад, товары сохраняются без модификации и обрезается часть названия в фигурных скобках.
<Товар>
    <Ид>u286hhMpg7B6L0aAvnriN3#GlZu3MTNi8aSN9MYIrH9V2</Ид>
    <Наименование>Big boy "Cookie" (120 мл, 0 мг)</Наименование>
    <ЦенаЗаЕдиницу>160.0000</ЦенаЗаЕдиницу>
    <Количество>1</Количество>
    <Сумма>160.0000</Сумма>
    <Скидки>
    <Скидка>
    <УчтеноВСумме>false</УчтеноВСумме>
    <Сумма>0</Сумма>
    </Скидка>
    </Скидки>
    <ЗначенияРеквизитов>
        <ЗначениеРеквизита>
            <Наименование>ТипНоменклатуры</Наименование>
            <Значение>Товар</Значение>
        </ЗначениеРеквизита>
    </ЗначенияРеквизитов>
</Товар>

в результате получается аналогично загрузке товара без модификации
<Ид>u286hhMpg7B6L0aAvnriN3</Ид>
<Наименование>Big boy "Cookie"</Наименование>

Внешние ключи правильные 100%, иначе создается новый товар.
Может кто сталкивался с подобной проблемой, или есть идеи.
РЕШЕНИЕ
В настройках синхронизации МойСклад есть чекбокс "Создавать модификации товаров"


text:
Q: Angular instantiate factories I'm a bit confused with Angular. I have two factories, with code looks almost the same, because they performs CRUD operations on two different objects in db, and I want to make them DRY.
So I have idea to move common logic to separate service, and I want it to works something like that :
angular.module('app').factory('first',['commonService',function(commonService){
    return new commonService('someSpecificVariable');
}])

and service :
angular.module('app').service('commonService',['someDep1',function(someDep1,someSpecificVariable){
    var something = someSpecificVariable;
}]);

I looked at providers, but i need something to instantiate. How can I achieve this?
In another words I want create factory responsible for all crud operation requests for all app modules, because writing many factories just to handle http/crud don't looks ok for me.
Ok i descriped it quite bad.
SOLUTION Is it possible and in good form to reuse the same data factory in Angular?

A: Factories
They let you share code between controllers as well as making http calls to your API. They are really about making some reusable code that you can instantiate in your controllers to make your life easier and your controllers cleaner.
Simple Example
.factory('FindFriend', function ($http, $rootScope) {
  return {
    find: function (phone) {
        return $http.get('http://130.211.90.249:3000/findFriend', { params: {phone:phone}})
    },
    add: function (id) {
        return $http.get('http://130.211.90.249:3000/addFriend', { params: {friendid:id, user_id: $rootScope.session} })
    },
    deleteFriend: function (id) {
        return $http.get('http://130.211.90.249:3000/deleteFriend', {params:{idfriends: id}})
    }
  }
})

Explanation
So above we can see a factory called FindFriend. The factory has 3 methods find add and delete. these are different http calls (in your code they shouldn't be all get methods but this is some old code I wrote).
They can be instantiated by adding them into the top of the controller and then calling there functions like FindFriend.add
Hope this sheds some light on factories for you.

A: I know how factories works, but i dont want to add bunch of functions responsible for each module. I wish to make service, which will replace patches to $http calls based of provided module name in constructor. ex 'orders' will make request :
$http.post('/api'+'orders'+'/lazy')...


text:
Q: Testing a csv file import/upload in rspec I am really just starting using ruby on rails and rspec, and I have to test that a file is able to be uploaded and displayed on the web page through automation.  The user should hit the choose file button and be able to get a .csv file and upload it, so I am looking to either generate a file or just use one of the example ones I have and have that done automatically.
As I said, I am really new to this whole thing and I am working as part of a QA team, so any help is appreciated.  I dont know what code I need to supply, and I really dont have an idea of what to do.  Ive searched google and cannot make sense of most of the results, so I don't really have any useful code written so far.
Tell me any code which I would need to supply, as I assume something is necessary.  I am using rails 4

A: Looks like the cucumber + capybara (yes, they use rspec) combination would be perfect for what you need. Here is a quick tutorial on how it's done: http://cassiomarques.wordpress.com/2009/01/23/how-to-test-file-uploads-with-cucumber/.


text:
Q: Kentico forms authentication cookie not persisting when sharing claims-based authenticated user with child application I'm working on an sso between our CMS (Kentico 11, portal engine) and a new AMS that uses Auth0 for authentication.  After no success with numerous different approaches to integrate custom external authentication directly, I made significant progress with this approach:

*

*Create a standalone MVC application based on the Auth0 ASP.NET(OWIN) quick start here: https://auth0.com/docs/quickstart/webapp/aspnet-owin - the sso works correctly here

*Configure this application as a child application of the Kentico site - this required adding some location tags in the Kentico web config so the MVC app wouldn't inherit most of the settings

*Configure the Kentico app to be able to recognize the authenticated user from the child app - this required adding the same machine key to the web config for both applications, and adding a Startup.Auth.cs class to the Kentico application with the same cookie authentication code as the MVC app
Eventually the proper redirects will be wired up to the correct global authentication events, but for now I'm mostly working in the context of a test page with the following flow:

*

*When you load the page, if the user is not logged in, they're redirected to the login action in the MVC app (which then redirects to Auth0).

*After successfully logging in to Auth0, the user is redirected back to the native callback in the MVC app which handles the token exchange and setting the claims, and then finally redirected back to the test page on the Kentico site.  Everything is good so far, as the Kentico site correctly recognizes the authenticated user and claims from the child MVC app at this point.

*Check for an existing Kentico user by username (we'll be using the external AMS ID as username).  If the user exists, update name and email; otherwise, create a new user and set the info accordingly.  Then programmatically log the user in to the Kentico site using AuthenticationHelper.AuthenticateUser("username", true);
This seemed to work at first - if I do a check for the current Kentico user on the same page right after logging them in, they're recognized correctly.  However, if I navigate to another page, the Kentico user is lost, and it appears that's because the .ASPXFORMSAUTH cookie set by the AuthenticationHelper.AuthenticateUser method is not persisting.
This is the code I currently have in the Kentico Startup.Auth.cs file:
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                LoginPath = new PathString(MVCLoginURL),
                CookieSameSite = SameSiteMode.Lax
            });

When I comment that out and try programmatically logging a specific user in on my test page instead, that works as expected - the .ASPXFORMSAUTH cookie persists, and the Kentico user continues to be recognized on other pages.
Any help identifying the conflict or how to make these two sets of cookies play nicely together is much appreciated.  I'm very new to Auth0, OWIN, and OpenID, and I realize the Kentico Portal Engine is becoming obsolete and we won't be supporting it for too much longer, but for now I need to make this work with our existing sites.  Thanks!


text:
Q: Timeline that uses a longtable environment I am struggling in using longtable environment for the answer posted in following thread.
How can you create a vertical timeline?
\documentclass[a4paper, twoside, 11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}
\usepackage{graphicx}
\usepackage[x11names]{xcolor}
\usepackage{colortbl}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}

\begin{document}

\begin{table}
\renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
\captionsetup{singlelinecheck=false, font=blue, labelfont=sc, labelsep=quad}
\caption{Timeline}\vskip -1.5ex
\begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
\toprule
\addlinespace[1.5ex]
1947 & AT and T Bell Labs develop the idea of cellular phones\\
1968 & Xerox Palo Alto Research Centre envisage the 'Dynabook\\
1971 & Busicom 'Handy-LE' Calculator\\
1973 & First mobile handset invented by Martin Cooper\\
1978 & Parker Bros. Merlin Computer Toy\\
1981 & Osborne 1 Portable Computer\\
1982 & Grid Compass 1100 Clamshell Laptop\\
1983 & TRS-80 Model 100 Portable PC\\
1984 & Psion Organiser Handheld Computer\\
1991 & Psion Series 3 Minicomputer\\
\end{tabular}
\end{table}

\end{document}

A: Something like this?

\documentclass[a4paper, twoside, 11pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs, longtable}
\usepackage{graphicx}
\usepackage[x11names,table]{xcolor}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}

\begin{document}

\begingroup
\renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
\captionsetup{font=blue, labelfont=sc, labelsep=quad,
              skip=0.5\baselineskip}

\begin{longtable}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}

% header and footer information
\caption{Timeline}\\
\toprule
\addlinespace[1.5ex]
\endhead

\addlinespace[1.5ex]
\bottomrule
\endlastfoot

% body of table
1947 & AT\&T Bell Labs develop the idea of cellular phones\\
1968 & Xerox Palo Alto Research Centre envisage the `Dynabook'\\
1971 & Busicom `Handy-LE' Calculator\\
1973 & First mobile handset invented by Martin Cooper\\
1978 & Parker Bros.\ Merlin Computer Toy\\
1981 & Osborne 1 Portable Computer\\
1982 & Grid Compass 1100 Clamshell Laptop\\
1983 & TRS-80 Model 100 Portable PC\\
1984 & Psion Organiser Handheld Computer\\
1991 & Psion Series 3 Minicomputer\\
\end{longtable}
\endgroup
\end{document}


text:
Q: Is there any open source or paid alternate to selenium for automating ext js application I am looking to automate extjs application, we all know selenium does not support extjs applications. Kindly suggest me if you have faced the same and come up with a solution for the above.
Thanks,

A: Sencha offers their testing tool sencha.com/products/test or you could use bryntum.com/products/siesta or you can still use Selenium and just write your own API functions for clicking on buttons and such - it can be done quite easily using Ext.query
I can share just a piece of our API code we used to test very specific ExtJS project where we could not use Test/Siesta. The code is written in Python.
def ext_component_query_return(self, query, question, target='AppManager'):
    script = 'Ext.ComponentQuery.query("{0}")[0]{1}'.format(query, question)
    return self.ext_script(script, target=target)

def ext_component_id(self, query, target='AppManager'):
    return self.ext_component_query_return(query, '.getId()', target=target)

def ext_component_isVisible(self, query, target='AppManager'):
    return self.ext_component_query_return(query, '.isVisible(true)', target=target)

def ext_component_isDisabled(self, query, target='AppManager'):
    return self.ext_component_query_return(query, '.isDisabled()', target=target)

Here is for example clicking on the button:
s_button_id = self.ext_component_id('#activation-success-card button')
s_button = self.ins.app_manager.find_element_by_id(s_button_id)
s_button.click()


text:
Q: GC Cloud Build access to Compute Engine through internal IP I try to deploy my Python app on AppEngine. During deploy, I have to download dependency from a private repository on the GC Compute Engine instance. I've added all needed row into requirements.txt and it works when I use external IP of my private repository. But it much better to use internal IP. In the GC IAM system, I've changed permissions for Cloud Build account and AppEngine account, but it still doesn't work and show connection timeout. Maybe you can help with it.
Thanks in advance!

A: In order for your build to access your Compute Engine instance via internal IP, they'd have to run in the same network.
By default, a build runs in a tenant project, so a separate network. One option to overcome this limitation is to use the remote-builder Cloud Builder. It allows you to execute your build step on a configurable Compute Engine VM in your project. You can use the complete list of flags available when creating a Compute Engine instance so you can configure it to run on the same network via the --network parameter.


text:
Q: Why is a cloned HSSFCellStyle not equal to the style it was cloned from? I am using one HSSF Workbook as a template for another.  Because of how that works, as you probably know if you're reading this, I cannot simply take a cell from workbook 1 and set its style to the CellStyle from workbook 2.  The way this is supposed to be done is to cloneStyleFrom the second style.
However, there is a maximum of 4000 styles in a worksheet so I am trying to avoid cloning an unlimited number of styles.  So, I am checking to see if a the style I am about to clone is equal to any style that already exists in my workbook.  If it is, I just use the style that already exists.  If it isn't, I clone the style from the template workbook.
I'm using the equals method defined below, which doesn't seem to care what workbook the style comes from.
http://www.java2s.com/Open-Source/Java-Document/Collaboration/poi-3.6/org/apache/poi/hssf/usermodel/HSSFCellStyle.java.htm#equalsObject
However, when at the end of all this I check:

        if ( !getCellStyle().equals(cell.getCellStyle()) ) {
            System.out.println("Not equal to cloned style!");
        } else {
            System.out.println("Equal to cloned style.");
        }

... the output indicates that the styles are not equal.
Why is this?
Note: Verified that both objects are type HSSFCellStyle using instanceof.

A: I had a look into the equals method.
If everything is equal the _index variable will be checked.
It seems, that the index is dependend on the position in a list of ExtendedFormat objects (s. Javadoc below).
If the the HSSFCellStyle contains information about a position and serves as a wrapper for ExtendedFormatRecord, maybe you could reuse the ExtendedFormatRecord object to conserve space.
/**
         * get the index within the HSSFWorkbook (sequence within the collection of ExtnededFormat objects)
         * @return unique index number of the underlying record this style represents (probably you don't care
         *  unless you're comparing which one is which)
         */
        public short getIndex() {
            return _index;
        }


text:
Q: invalid json response body error, while deploying Next.js app to Vercel App builds fine locally and works on local production server + development server.
The api used to fetch data is working fine.
Code which is producing the error
export const getStaticProps = async () => {
    const resp = await fetch(
        'https://cdn-api.co-vin.in/api/v2/admin/location/states',
        {
            headers: {
                'User-Agent': '*',
            }, //this is required by api provider
        }
    );
    const data = await resp.json();
    //console.log('states in getStaticProps : ', data);

    return { props: { data: JSON.parse(JSON.stringify(data)) } };
};

const Ninjas = ({ data: { states } }) => {
    console.log('Ninjas : ', states);
    return (
        <>

                <title> Listing</title>

                {states.map((ei) => (

{ei.state_name}

                ))}

        </>
    );
};

export default Ninjas;

Following is the vercel log.
20:17:40.644    Cloning github.com/user-name/co2-app (Branch: main, Commit: 8ab0e48)
20:17:41.349    Cloning completed: 704.592ms
20:17:41.374    Analyzing source code...
20:17:42.573    Installing build runtime...
20:17:45.235    Build runtime installed: 2.662s
20:17:48.104    Looking up build cache...
20:17:48.453    Build cache not found
20:17:49.697    Installing dependencies...
20:18:04.559    > ejs@2.7.4 postinstall /vercel/path0/node_modules/ejs
20:18:04.559    > node ./postinstall.js
20:18:05.113    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
20:18:05.113    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
20:18:05.116    added 600 packages from 352 contributors in 14.87s
20:18:05.426    64 packages are looking for funding
20:18:05.426      run `npm fund` for details
20:18:05.492    Detected Next.js version: 10.2.0
20:18:05.492    Running "npm run build"
20:18:05.756    > we2-cowax@0.1.0 build /vercel/path0
20:18:05.757    > next build
20:18:07.292    info  - Using webpack 4. Reason: custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
20:18:08.224    info  - Checking validity of types...
20:18:08.244    Attention: Next.js now collects completely anonymous telemetry regarding usage.
20:18:08.245    This information is used to shape Next.js' roadmap and prioritize features.
20:18:08.245    You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
20:18:08.245    https://nextjs.org/telemetry
20:18:08.326    info  - Creating an optimized production build...
20:18:08.748    > [PWA] Compile client (static)
20:18:08.748    > [PWA] Auto register service worker with: /vercel/path0/node_modules/next-pwa/register.js
20:18:08.750    > [PWA] Service worker: /vercel/path0/public/service-worker.js
20:18:08.750    > [PWA]   url: /service-worker.js
20:18:08.750    > [PWA]   scope: /
20:18:08.860    > [PWA] Compile server
20:18:25.603    info  - Compiled successfully
20:18:25.604    info  - Collecting page data...
20:18:26.366    info  - Generating static pages (0/3)
20:18:26.918    error :  invalid json response body at https://cdn-api.co-vin.in/api/v2/admin/location/states reason: Unexpected token < in JSON at position 0
20:18:26.919    Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
20:18:26.919    Error: Error serializing props returned from `getStaticProps` in "/".
20:18:26.919    Reason: Props must be returned as a plain object from getStaticProps: `{ props: { ... } }`.
20:18:26.919        at isSerializableProps (/vercel/path0/node_modules/next/dist/lib/is-serializable-props.js:1:462)
20:18:26.919        at renderToHTML (/vercel/path0/node_modules/next/dist/next-server/server/render.js:30:1730)
20:18:26.919        at processTicksAndRejections (internal/process/task_queues.js:93:5)
20:18:26.919        at async /vercel/path0/node_modules/next/dist/export/worker.js:26:6
20:18:26.919        at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.920    info  - Generating static pages (3/3)
20:18:26.921    > Build error occurred
20:18:26.926    Error: Export encountered errors on following paths:
20:18:26.926        /
20:18:26.926        at /vercel/path0/node_modules/next/dist/export/index.js:31:1106
20:18:26.926        at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.927        at async /vercel/path0/node_modules/next/dist/build/index.js:43:49
20:18:26.927        at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.927        at async /vercel/path0/node_modules/next/dist/build/index.js:25:1475
20:18:26.927        at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.954    npm ERR! code ELIFECYCLE
20:18:26.954    npm ERR! errno 1
20:18:26.958    npm ERR! co2-app@0.1.0 build: `next build`
20:18:26.958    npm ERR! Exit status 1
20:18:26.958    npm ERR!
20:18:26.959    npm ERR! Failed at the we2-cowax@0.1.0 build script.
20:18:26.959    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
20:18:26.968    npm ERR! A complete log of this run can be found in:
20:18:26.968    npm ERR!     /vercel/.npm/_logs/2021-05-17T14_48_26_959Z-debug.log
20:18:26.982    Error: Command "npm run build" exited with 1

I am using next-pwa for PWA functionality and hence custom webpack version
Have  delete the app at Vercel and re-deploy, even removed the cache build but still can't resolve the error

A: Problem
The API is returning a 403 forbidden error:
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
    <TITLE>ERROR: The request could not be satisfied</TITLE>

403 ERROR

The request could not be satisfied.

    Request blocked.
    We can't connect to the server for this app or website at this time. There might be too much traffic or a
    configuration error. Try again later, or contact the app or website owner.

If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

Generated by cloudfront (CloudFront)
Request ID: BqNxi8x1nTA3YKM_N3JSCyjGVDYnMUDNFvS_HgJGB8glTFr1uVh6Ug==

    <ADDRESS>
    </ADDRESS>

which is not then being handled correctly by your getStaticProps function (in this case, an invalid response can't be turned into JSON; also, your User-Agent is not valid):
export const getStaticProps = async () => {
    const resp = await fetch(
        'https://cdn-api.co-vin.in/api/v2/admin/location/states',
        {
            headers: {
                'User-Agent': '*',
            }, //this is required by api provider
        }
    );

    // this throws an error because you can't turn
    // the invalid server response into JSON
    const data = await resp.json();

    return { props: { data: JSON.parse(JSON.stringify(data)) } };
};

which is also not being handled correctly by your Ninjas component -- states would be undefined because the server doesn't respond with valid data and you can't map an undefined variable. Instead you should check that states is a non-empty Array before mapping over it by either using lodash's isEmpty: !isEmpty(states) && states.map(...) or by checking that it's defined and has length: Array.isArray(states) && states.length > 0 && states.map(...).
Solution
import Head from "next/head";
import isEmpty from "lodash.isempty";

export const getStaticProps = async () => {
  let data = [];
  let error = "";
  try {
    const res = await fetch(
      "https://cdn-api.co-vin.in/api/v2/admin/location/states",
      {
        method: "GET",
        headers: {
          // update with your user-agent
          "User-Agent":
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
          Accept: "application/json; charset=UTF-8",
        },
      }
    );

    if (res.status !== 200)
      throw String(`Invalid server response: ${res.status} ${res.statusText}`);

    data = await res.json();

    if (isEmpty(data)) throw String("No data was found!");

    data = JSON.parse(JSON.stringify(data));
  } catch (e) {
    error = e.toString();
  }

  return {
    props: {
      data,
      error,
    },
  };
};

const Ninjas = ({ data, error }) => (
  <>

      <title> Listing</title>

      {error &&
{error}
}
      {!isEmpty(data) && !isEmpty(data.states) &&
        data.states.map((ei) => (

{ei.state_name}

        ))}

  </>
);

export default Ninjas;


text:
Q: Which data in cached in yii after enable Yii I checking out the Schema Cache part of Yii. Then I found the way for enabled via CFileCache and schemaCachingDuration. It is done without any problems. Now I am thinking as I did not specified which components should be cached. So Which part of application, Yii cached after enabled caching (In the way when we did not set any of other cache settings ).  It just schema or more ?

A: By default Yii only caches:

*

*Global state

*Translated messages

*WSDL files of Web Services
All other cache features (schema caching, data caching, fragment caching, page caching) are only used on demand (i.e. if explicitely enable/use them).


text:
Q: Frequent Complete Freezes On 20.04 Over the last few days, for no reason I can tell (no recent big updates), I've been experiencing frequent instances of complete system freezes. The mouse won't move, no key combinations trigger, and cannot reboot with Alt+SyReq either. The only way to do anything is to hold down the power button until it powers off. After rebooting it freezes again, sometimes after many hours, sometimes after only a few minutes. It is never linked to me running a program, happens inexplicably while i'm just browsing websites.
free -h gives:
 total        used        free      shared  buff/cache   available
Mem:           11Gi       1.0Gi       9.0Gi       134Mi       1.4Gi       9.9Gi
Swap:         2.0Gi          0B       2.0Gi

sysctl vm.swappiness gives:
vm.swappiness = 60

swapon -s gives:
Filename                Type        Size    Used    Priority
/swapfile                               file        2097148 0   -2

A: System "freezes" are often caused by running too many, too large programs and running out of available memory. Use free to see if you have swap space, read man mkswap swapon fstab fallocate to create some. Swap space must be contiguous. use mkswap or fallocate, not dd. Traditionally, swap space of 1.5 × RAM has been recommended,  but YMMV. If you don't plan to hibernate your system, you can have less than 1.0 × RAM.

A: With 12G RAM, your /swapfile may be a little small, and causing your freezes. Let's bump it from 2G to 4G and see if it helps.
Note: Incorrect use of the rm and dd commands can cause data loss. Suggest copy/paste.
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 12G RAM and 4G swap

Edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.
Confirm this /swapfile line in /etc/fstab... and confirm no other "swap" lines... use SPACES in this line... confirm NO TABS...
/swapfile  none  swap  sw  0  0

reboot                    # reboot and verify operation


text:
Q: Display sqlite3 database in datagridview c++/CLI I'm trying to populate a table in a datagridview from a SQL database.
I have seen a lot of code in C# but not in C++, and I'm using SQLite3.
So far I can print out to console using the example from Tutorialspoint
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
    int i;

    for (i = 0; i<argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }

    printf("\n");
    return 0;
}

The question: is it possible in C++ to add rows like the example code prints out?
I saw this guy do something like it but he uses another sql lib and I can't figure out how to make this work for SQLite(3).


text:
Q: Attribute to generate compilerwarning for a method in class I have a class, where I use the singleton-pattern. The class looks like
public class MessageAccess
{
    private static MessageAccess instance;
    public static MessageAccess Instance
    {
        get { return instance ?? (instance = new MessageAccess()); }
    }

    private MessageAccess()
    {

    }

    public void Initialize(string data)
    {
        //...
        isInitialized = true;
    }

    private bool isInitialized;

    public void ReadData1()
    {
        // This Method can always be called
    }

    public void ReadData2()
    {
        // This Method can only be called, if Initialize was called. Otherwise an exception will be thrown
    }
}

Is it possible to generate a compiler-warning if the Method Initialize is never called

A: While I understand your point of view, I don't think such warning would be as handy as you think. I'm afraid .NET framework doesn't cater for this type of warnings for a couple of well defined reasons (please refer to this link: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/19/why-doesn-t-c-warn-about-unused-methods.aspx).
One might think that the lack of this feature is a missed opportunity, but it's not quite the case. Your class, MessageAccess, is public and will be compiled into (let's say) a dll. Even if you had this warning while compiling your dll, you wouldn't want it to appear while compiling some external code using that dll's Initialize method (which is also public). You basically can't guarantee that no other code will ever use that method, and this is one of the better reasons not to have this warning.

A: If the class is not used from outside the assembly, you can make it internal. In this case, Code Analysis will generate a warning "Avoid uncalled private code", if the method is not called.


text:
Q: how to update a tag column based on multiple values against an ID column WOuld like to check on how I can query the following scenario?

In this scenario, customer CU_001 has multiple products and statuses. I need to tag CU_001 as active if one of the products has "Paying" Status or "Paying-Installment". However, if the customer has other status except the two, it will be tag as Inactive. Like CU_002, its has only one product and should be tagged as inactive.

A: so you could use a query like below to give you all customers which need to be tagged
Select CustomerID
from customertable
where status in ('paying', 'paying-installment')

if the tag column is in the same table then
update ct
set tag=case when c.customerid is not null then 'active' else 'inactive' end
from
customertable ct
left join
(
Select CustomerID
    from customertable
    where status in ('paying', 'paying-installment')
) c
on ct.CustomerID=c.CustomerID

if this is another table then simple replace
from
customertable ct

with
from
<othertablename> ct

A: If this is just something you want to view, adhoc, then the below will work, as it does not set anything in the tables:
This code will add a column with the status for every line:
SELECT
    [Customer ID],
    Product,
    Status,
    CASE Status
        WHEN 'Paying'
                THEN
                    'Active'
        WHEN 'Paying-Installment'
                THEN
                    'Active'
        ELSE
            'Inactive'
        END AS Active
FROM customerTable

This code will add a column with the status but only show the customer and the status:
SELECT DISTINCT
    [Customer ID],
    CASE Status
        WHEN 'Paying'
                THEN
                    'Active'
        WHEN 'Paying-Installment'
                THEN
                    'Active'
        ELSE
            'Inactive'
        END AS Active
FROM customerTable

The difference between the two is what columns are shown, and the DISTINCT command.


text:
Q: Deploying Django application with SQL Database to Azure I've built a simple Django application on my local Windows machine that connects to a SQL Server hosted on Azure by leveraging the Django-Pyodbc-Azure back end.  I'm able to connect to the database fine on my local machine and my app runs without issue.
However, I'm not in the process of deploying the application to Azure's app service and I'm running into problems.  The deployment itself runs without issue, however the following error message shows up in my logs:
Traceback (most recent call last): File "/home/site/wwwroot/antenv3.6/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 15, in <module>
import pyodbc as Database
ImportError: libodbc.so.2: cannot open shared object file: No such file or directory

File "/home/site/wwwroot/antenv3.6/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 17, in <module>
raise ImproperlyConfigured("Error loading pyodbc module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: libodbc.so.2: cannot open shared object file: No such file or directory

My requirements.txt file looks as such:
Django==2.1.4
django-pyodbc-azure==2.1.0.0
pyodbc==4.0.25
pytz==2018.7

And again... this runs fine locally on my Windows machine.  But I get this error when I deploy to Azure.
I suspect this has something to do with the Pyodbc backend not being installed correctly on Azure's LINUX based app service?  Does anybody have experience resolving this?

A: I was running into this same issue with the pyodbc package when using the Linux version. I was using the Windows based web-app but had to rebuild from scratch and accidentally selected the Linux version.
Once switching back to the Windows version I used python 3.6 and followed these steps, (based on this blog for deploying a flask app, https://blogs.msdn.microsoft.com/pythonengineering/2016/08/04/upgrading-python-on-azure-app-service/):
Deploy a Django web-app to Azure

*

*In the portal click on "Web App">"New"

*Give the web app a name: <webappname>

*Set the resource group to be the same as the database

*Select the OS to be Windows

*Click, deploy - This will take few minutes to deploy

*Once deployed you can click on the URL https://<webappname>.azurewebsites.net to see a default azure web page

*In your Django project go to settings.py and in the "ALLOWED_HOSTS" add ".azurewebsites.net".

*In the Azure portal>webapp, go to Extensions and install python3.6 x64

*In Portal > webapp > Application settings, select "Always on".

*In settings.py set:

*

*DEBUG = os.getenv('DJANGO_DEBUG') != 'FALSE'

*also set other private variables as environment variables (these should then be added as key-value pairs (e.g. DJANGO_DEBUG = FALSE) in Portal>webapp>Application settings>Application settings.

*Also, to connect to the SQL database set the database settings to be:

*

*OPTIONS[driver] = 'SQL Server Native Client 11.0'

*OPTIONS[MARS_Connection] = 'True'

*Make sure you have the following files in the base directory of your django project:

*

*ptvs_virtual_proxy.py

*.SkipPythonDeployment

*web.config make sure you have key="DJANGO_SETTINGS_MODULE" value "<django-project-name>.settings" (see below)

*In your local project, Run pip freeze and put the contents into requirements.txt (see below)

*Check that all migration files have been added to git by running git status

*Commit and push the changes to your git repo

*In the portal, in your new web-app go to "Deployment options"

*"Choose Source" -> Follow the steps and click "Finish/Ok" to see the deployment progress and view the logs

*Once deployment says "Success", Go to Kudu (http://<webappname>.scm.azurewebsites.net)>Powershell, and run D:\home\python364x64\python.exe -m pip install --upgrade -r D:\home\site\wwwroot\requirements.txt, This should hopefully be successful and only needs to be rerun when you update a package.

*Then go back to "Deployment Center" and click on the logs button, and click redeploy, you may also need to restart the web-app to update the environment variables (go to webapp>overview>restart).

*For static files, either commit all the admin files after running locally python manage.py collectstatic or you can setup static files like this, then run D:\home\python364x64\python.exe D:\home\site\wwwroot\manage.py collectstatic in Kudu)
web.config file:
<configuration>
<appSettings>
    <add key="WSGI_HANDLER" value="<django-project-name>.wsgi.application"/>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot"/>
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
    <add key="PYTHONPATH" value="D:\home\site\wwwroot" />
    <add key="DJANGO_SETTINGS_MODULE" value="<django-project-name>.settings" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpErrors errorMode="Detailed"></httpErrors>
    <handlers>
      <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python364x64\python.exe|D:\home\python364x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/>
    </handlers>
    <rewrite>
      <rules>
        <rule name="Static Files" stopProcessing="true">
          <conditions>
            <add input="true" pattern="false" />
          </conditions>
        </rule>
        <rule name="Configure Python" stopProcessing="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

requirements.txt file:
cycler==0.10.0
Django==1.11.15
django-pyodbc-azure==1.11.15.0
djangorestframework==3.6.3
djangorestframework-jsonp==1.0.2
pyodbc==4.0.25

A: please go to the scm site of your web app, then try to manually install the modules which throw the error.
For detailed steps, please refer to this article.


text:
Q: SQL Server Unexpected Results from Data Type Change I am working with acoustic data that shows decibel levels broken down between frequencies (1/3 octave bands). These values were imported from a flat text file and all have 1 decimal (e.g., 74.1 or -8.0).
I need to perform a series of calculations on the table in order to obtain other acoustic measures (calculated minute-level data by applying acoustic formulas to my given second-level data.) I am attempting to do this with a series of nested select statements. First, I needed to get the decibel values divided by 10. I did fine with that. Now I'd like to feed the generated fields output from this select statement into another that raises 10 to the power of my generated values.
So, if the 20000_Hz field had a value of 16.3, my generated table would have a value of 1.63 for that record, and I'd like to nest that into another select statement that generates 10^1.63 for that field and record.
To do this, I've been experimenting with the POWER() function. I tried POWER(10,my_generated_field) and got all zeros. I realized that the format of the base determines the format of the output, meaning that if I did something like POWER(10.0000000000000000000,my_generated_field) I'd start to see actual numbers like 0.0000000000032151321. Also, I tried altering my table to change the data type for decibel values to decimal(38,35) to see what effect this would have. I believe I initially set the data type as float using the flat file import tool.
To my surprise, numbers that were imported from the flat text file did not simply have more zeros tacked on the end, but had other numbers. For instance, a number like 46.8 now might read something like 46.8246546546843543210058 rather than 46.8000000000000000 as I'd expect.
So my two questions are:
1) Why did changing data types not create the results I expected, and where is SQL getting these other numbers?
2) How should I handle data types for my decibel values so that I don't loose accuracy when doing the 10^field_value thing?
I've spent some time reading about data types, the POWER() function, etc., but still don't feel like I'm going to understand this on my own.