text:
Q: COM SAFEARRAY memory from C++ to VBA I would like to create a SAFEARRAY of user defined type (UDT) in an UDT.
I have one structure Data which contains the S structure. S is composed with S1 and S2.
I need to create in c++ the array S of my Data object with the COM function.
When I call my function from the VBA to create the array, the VBA crashes at the end of the function.
If I remove s7 from S, it works perfectly.
I aligned my struct with 4 bytes.
I don't find any help on this problem on the web.
You can see the code here:

*

*VBA code:
#If VBA7 Then
    Private Declare PtrSafe Function Cpp_Test2 Lib "MYLIB.dll" (i As Data) As Long
#Else
    Private Declare Function Cpp_Test2 Lib "MYLIB.dll" (i As Data) As Long
#End If

Public Type S1
    d1 As Double
    S1 As String
    S2 As String
    d2 As Double
    d3 As Double
    i1 As Long
    i2 As Long
    d4 As Double
    d5 As Double
    s3 As String
    s4 As String
    s5 As String
    s6 As String
    d6 As Double
    d7 As Double
    d8 As Double
    s7 As String
End Type

Type S2
    n As Long
    x() As Double
    y() As Double
End Type

Type S
    ms1 As S1
    ms2 As S2
End Type

Type Data
    d As Double
    n As Long
    ms() As S
End Type

Sub TestFunction()
    Dim d As Data
    MsgBox Cpp_Test2(d)
    Stop
End Sub

*C++ code:

*idl file:
    typedef [uuid(C8166034-DF8D-460A-B38E-F9342694AABA)] struct S1
    {
        double d1;
        BSTR s1;
        BSTR s2;
        double d2;
        double d3;
        int i1;
        int i2;
        double d4;
        double d5;
        BSTR s3;
        BSTR s4;
        BSTR s5;
        BSTR s6;
        double d6;
        double d7;
        double d8;
        BSTR s7;
    } S1;

    typedef [uuid(539CF724-616E-46B6-8990-AD14F8190737)] struct S2
    {
        int n;
        SAFEARRAY(double) x; //dbl
        SAFEARRAY(double) y; //dbl
    } S2;

    typedef [uuid(0B689485-F347-4414-BF86-07926AC2526C)] struct S
    {
        S1 s1;
        S2 s2;
    } S;

*cpp file:
const IID IID_S = { 0x0B689485, 0xF347,     0x4414{0xBF,0x86,0x07,0x92,0x6A,0xC2,0x52,0x6C
                                      }
};

struct Data
{
    double d;
    int n;
    SAFEARRAY *S;
};

__declspec(dllexport) int __stdcall  Cpp_Test2(Data *d)
{
    SAFEARRAYBOUND rgsabound[1];
    rgsabound[0].lLbound = 0;
    rgsabound[0].cElements = 5;
    IRecordInfo* pRecInfo = NULL;
    HRESULT hr = GetRecordInfoFromGuids(LIBID_MYLIB, 9, 9, 0, IID_S, &pRecInfo);

    if (pRecInfo)
    {
        d->S = SafeArrayCreateEx(VT_RECORD, 1, rgsabound, pRecInfo);
        return 1;
    }

    return 0;
}

I don't understand why it doesn't work.
I have already used SafeArrayCreateEx without problem but here it seems there a memory problem.


text:
Q: android dictionary using trie i want to build a android dictionary app using trie. so m i new to this platform, how could i possibly start things... plz anyone can help me.....

A: The android developer site is a great place to start from: http://developer.android.com/guide/basics/what-is-android.html
After you read the basics, start with a tutorial: http://developer.android.com/resources/browser.html?tag=tutorial
If you have any specific question after that, when you start implementing your application, you are welcome to ask.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JDBC Can't Find class even after setting classpath I am having a lot of trouble using the JDBC library to work for me.
I am getting a "java.lang.ClassNotFoundException: org.sqlite.JDBC" error when my class tries to load the JDBC class at the Class.forName() call.
public static void main(String[] args) {

    try {
        Class.forName("org.sqlite.JDBC");   //<--- Throws error
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

I followed the instructions given on the JDBC page, which states that I must ensure that the sqlite-jdbc JAR file is in the classpath.  I did this by copying the sqlite-jdbc file into the same directory as my application's compiled JAR file, and then calling my applications using
java -cp .:sqlite-jdbc-3.21.0.1.jar -jar myapplication.jar

This seems like it should be quite straightforward, but it still gives the error indicating that it can't find the class.  I've confirmed that the sqlite-jdbc-3.21.0.1.jar contains class "JDBC" in package "com.sqlite".
unzip -l sqlite-jdbc-3.21.0.1.jar  | grep JDBC.class
2499  2017-12-07 12:10   org/sqlite/JDBC.class

The directory listing where my application runs looks like this:
myapplication.jar  sqlite-jdbc-3.21.0.1.jar

It seems to me that since the current directory is in the default classpath, and I've copied the sqlite-jdbc-3.21.0.1.jar into the same directory as my application's jar, then shouldn't java be able to find the class even if I don't set the classpath?  And it seems even more strange that when I call out the sqlite-jdbc-3.21.0.1.jar directly in the classpath that java still can't find the class.  what gives?
Finally, I'd appreciate an explanation as why this dependency is different than other dependencies.  I'm used to finding a library, adding a line in gradle to list it as a dependency using compile <dependency>, and voila, it can find the path when compiling and when deploying.  OTOH, I'm used to developing for Android (not a stand-alone application, as this is), where I'm guessing that all system libraries are always in the classpath and any non-Android dependencies are included in my application's JAR file.  But why is the JDBC not included in my applications JAR, while other dependencies are?
I've read and implemented the answer to this question, so I don't believe that simply setting the classpath is the problem - unless I've somehow set it improperly.


text:
Q: Speed up 10x copying a workbook's worksheet which has 100k rows to the current workbook I know this might have been asked a hundred of times but is there a way to really speed up my code below even faster, maybe 10 times faster? I am open to like Python-Excel codes, etc.
This could be a more different question because I am not just limiting myself with plain VBA.
Code:
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlManual

    Dim wb_raw As Workbook
    Set wb_raw = Workbooks.Open("C:\Projects\Raw.xlsx")

    wb_raw.Worksheets(1).Copy Before:=ThisWorkbook.Worksheets(2)
    ' the worksheet being copied has 100k rows

    wb_raw.Close

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlAutomatic

I am also open to the PowerQuery then refresh route.

A: There are a few potential pathways through this, depending on the resources you choose to use.
You have not mentioned whether you want values copied, formulas or both. I assume values only.
If you can do the copy while the workbook is closed, maybe pyopenxl or xlrd and xlwrt could do the trick. Both of these can copy values and formulas but neither of these solutions can evaluate formulas but that sounds OK from your description.
If you need the workbook to be open while you're doing the copy or move, there are some great solutions which integrate Python and Excel using COM. xlwings, PyXll , FlyingKoala and DataNitro. With these solutions you can write some Python code that does a copy. If you just want values, you can use dataframes to move the data around.
I have only used xlwings (and [FlyingKoala] - which uses xlwings). xlwings facilitates a two-way communication between Python and Excel so you can call Python from Excel and you can call Excel (including VBA) from Python. This technique can be great for speeding up operations, especially in reporting and modelling.
PyXll and FlyingKoala have an added advantage where they can read Excel formulas and convert them into Python code then execute (evaluate) the dynamically generated Python code.
An example using xlwings to copy values only. I used this to copy 100,000 rows with 26 columns (A through Z) and it took 17 seconds;
import xlwings as xw
import numpy as np

@xw.func
@xw.arg('range_to_copy', np.array, doc='')
@xw.ret(index=False, header=False, expand='table')
def copy_values(range_to_copy):

    return range_to_copy


text:
Q: How to remove a trailing space in my regex? I've got the following regex:
tag-((?:\w+ )+)

It's intended for a string like this:

entry tag-free images tag-creative tag-design tag-inspiration
  tag-stock photos tag-stock images tag-free photos tag-free stock
  images tag-stock photography tag-authentic tag-live authentic
  tag-natural tag-nature tag-macro tag-closeup tag-dandelion tag-wet
  tag-moist tag-white tag-soft tag-green tag-close tag-snapwire
  tag-snapwiresnaps tag-week 24 photo-post

It's great accept it captures a trailing space at the end of each group like so:
'free images ', 'week 24 ', 'moist ', etc..

how can I stop it from only capturing the last space?

A: You can use this negative lookahead based regex:
\btag-((?:\w+ )*(?!\btag\b)\w+\b)

RegEx Demo

A: Why you don't want to post-process your result:
tags = [x.strip() for x in re.findall("tag-((?:\w+ )+)", s)]


text:
Q: Rewriting function in TypeScript I have the following (working) function in JavaScript:
function solve(strArr) {
  return strArr.reduce(function ([x, y], curr) {
    switch (curr) {
      case 'up':    return [x, y + 1]
      case 'down':  return [x, y - 1]
      case 'left':  return [x - 1, y]
      case 'right': return [x + 1, y]
    }
  }, [0, 0])
}

I'm trying to rewrite it using TypeScript as:
function solve(strArr: string[]): number[] {
  return strArr.reduce(([x, y]: number[], curr: string) =>  {
    switch (curr) {
      case 'up': return [x, y + 1]
      case 'down': return [x, y - 1]
      case 'left': return [x - 1, y]
      case 'right': return [x + 1, y]
    }
  }, [0,0])
}

but I'm getting the Type 'string' is not assignable to type 'number[]'. error, which I know refers to the accumulator, but don't know how to solve.
As per Rajesh's suggestion, changing the type of strArr to any solves the issue, but giving it the specific type I'm using with the function doesn't work; why?

A: You can add a default case for your switch as others have suggested.
I would advise a second solution, which is to create a type for your input parameter to narrow the type:
type Direction = 'up' | 'down' | 'left' | 'right'

function solve(strArr: Direction[]) {
  return strArr.reduce(([x, y], curr) =>  {
    switch (curr) {
      case 'up': return [x, y + 1]
      case 'down': return [x, y - 1]
      case 'left': return [x - 1, y]
      case 'right': return [x + 1, y]
    }
  }, [0,0])
}

Play

A: You should explicitly handle the default case in your switch:
function solve(strArr:string[]) {
  return strArr.reduce(([x, y], curr) =>  {
    switch (curr) {
      case 'up': return [x, y + 1]
      case 'down': return [x, y - 1]
      case 'left': return [x - 1, y]
      case 'right': return [x + 1, y]
      // maybe throw an error instead
      default: return [x, y];
    }
  }, [0,0])
}

Playground example
without the default case your reducer function returns the type: number[] | undefined

A: You can improve params and return types.
For the code's readability, you should avoid array.reduce().
type Direction = 'up' | 'down' | 'left' | 'right'
function solve(directions: Direction[]): [number, number] {
  let x = 0
  let y = 0
  for (const direction of directions) {
    switch (direction) {
      case 'up': y++; break
      case 'down': y--; break
      case 'left': x--; break
      case 'right': x++; break
    }
  }
  return [x, y]
}

A: Because you are not covering all cases.
Add the default case to the switch
default : return []


text:
Q: Encoding in Streamreader in my silverlight application Having trouble geting the encoding right in my silverlight application.
I need support for western europe letters like æ,ø,å,â and so(Latin1??).
But I can't get it right. What should be instead of SOMEENCODINGHERE? did try
Encoding enc = Encoding.GetEncoding("Latin1"); but no names I used as param was recognized =( .
If I use Encoding.Unicode tr.ReadLine() reads the whole file and convert it to Chinese for some reason.
    private Dictionary<int, string> InitDictionary()
    {
        var d = new Dictionary<int, string>();
        var sri = App.GetResourceStream(new Uri(fileDic, UriKind.Relative));
        using (TextReader tr = new StreamReader(sri.Stream, Encoding.SOMEENCODINGHERE))
        {
            int i = 0;
            string line;
            while ((line = tr.ReadLine()) != null)
            {
                d.Add(i++, line);
            }
        }
        return d;
    }

A: If you really want ISO-Latin-1, you can use
Encoding.GetEncoding(28591);

But the normal Windows Western Europe code page is 1252:
Encoding.GetEncoding(1252);

Are you absolutely sure that's the encoding for your stream though? These days it's more common to use UTF-8. What's generating your text resource?

A: Silverlight (1-4, don't known about 5) doesn't support ANSI Encodings (codepages). It supports only Unicode encodings: UTF8 and UTF16.
See http://msdn.microsoft.com/en-us/library/system.text.encoding%28VS.95%29.aspx for details.
So suggested Encoding.GetEncoding(1252) and any other codepage numbers do not work.
You have to implement your Encoding class for needed codepage.
If you have found an appropriate implementation please share it, i'd be interesting.


text:
Q: Can't change terminal size on pty/N (works on ttyN) I use the next to change terminal size:

rc = ioctl(fd, TIOCSWINSZ, &ws);

When I run this under linux text terminal (switching by Alt-Ctrl-F1), the result is that I expect to see. The whole my input and output within ranges given by ioctl syscall.
But when I connect to localhost by SSH, and run the same program, it works only partly. I mean that I can't input command wider than terminal size set by ioctl, but the output can cross the borders of terminal given by ioctl, and input can take more rows that set by ioctl. Also there is no auto carriage return and new line after that.
The only difference that I see when I run program directly it run on the terminal /dev/ttyN, and it's major number is 5, and when I run program via SSH it use /dev/pts/N as terminal, with major number 136.
So, as I understood, it happens due the difference in terminals.
My questions:
1. Is that correct? Is the reason in terminal drivers?
2. How do I fix it? I need the same behaviour via SSH like in local tty terminal.

Thanks!

A: Usually TIOCSWINSZ is used by the tty master (such as xterm, the Linux console itself, etc...) to tell the kernel driver how big the terminal actually is. The program running on the tty slave (i.e. the application itself) uses TIOCGWINSZ to query the size of the terminal. Most tty drivers don't support pushing it the other way; you can't in general call TIOCSWINSZ on the tty slave from the application and get the master to change its size.
Some terminals, such as xterm do support escape sequences to request them to resize, but this is just a byte escape sequence, and not an ioctl() command.
If you want the application to force the size of the terminal, then portably there is no way to do this. Unportably, you can apply a few special tricks like attempting TIOCSWINSZ or sending the xterm escape sequence.


text:
Q: Rationale behind portType and binding in WSDL In a WSDL we define the operation name, input and output in the portType element; later on in binding we define operation, input and output again. What is the rationale behind this? why define them twice? I understand in binding we define the encodingStyle and other attributes, so what is the need of portType?

A: You are talking about WSDL 1.1. In WSDL 2.0, you define operations only once, in an interface tag.
You should read more about Java libraries' support for WSDL 2.0, for instance: Axis2 with WSDL 2.0 Tutorial


text:
Q: Infinite loop in Prolog. How do I prevent this? I am writing a program in Prolog that represents the rules of a card game. However, I am running into an infinite loop with the following code.
succ(seven_of_hearts,eight_of_hearts).
succ(eight_of_hearts,nine_of_hearts).
succ(nine_of_hearts,ten_of_hearts).
succ(ten_of_hearts,jack_of_hearts).
succ(jack_of_hearts,queen_of_hearts).
succ(queen_of_hearts,king_of_hearts).
succ(king_of_hearts,ace_of_hearts).
succ(X,Y) :-
   succ(X,Z),
   succ(Z,Y),
   !.

beats(X,Y) :-
   succ(Y,X).

Basically, my attempt with these few lines is to set up a system for determining if one card beats another according to the succ (or succession) relationships I have established. So the query I am running is beats(X,Y), where X and Y and atoms corresponding to cards. This query terminates successfully if it is true. For example, if I query beats(jack_of_hearts,seven_of_hearts), it returns true and terminates.
However, the query enters an infinite loop if it is false. For example, when I query beats(seven_of_hearts,jack_of_hearts). I traced the query and found that due to the recursive nature of the last succ statement, the query follows the chain of succ statements all the way down to the seven_of_hearts, or all the way up to the ace_of_hearts, and then continuously tries to evaluate succ(seven_of_hearts,X) or succ(ace_of_hearts,X) instead of returning false.
I have two questions: using this current structure, how could I prevent this? Or, if that's not possible, what is an alternative structure I could use to accomplish my goal?
EDIT:
Here is a screenshot of my trace for one of the failing queries:
    Call: (267) beats(seven_of_hearts, jack_of_hearts) ? creep
Call: (268) succ(jack_of_hearts, seven_of_hearts) ? creep
   Call: (269) succ(jack_of_hearts, _G7104) ? creep
   Exit: (269) succ(jack_of_hearts, queen_of_hearts) ? creep
   Call: (269) succ(queen_of_hearts, seven_of_hearts) ? creep
   Call: (270) succ(queen_of_hearts, _G7104) ? creep
   Exit: (270) succ(queen_of_hearts, king_of_hearts) ? creep
   Call: (270) succ(king_of_hearts, seven_of_hearts) ? creep
   Call: (271) succ(king_of_hearts, _G7104) ? creep
   Exit: (271) succ(king_of_hearts, ace_of_hearts) ? creep
   Call: (271) succ(ace_of_hearts, seven_of_hearts) ? creep
   Call: (272) false ? creep
   Fail: (272) false ? creep
   Redo: (271) succ(ace_of_hearts, seven_of_hearts) ? creep
   Call: (272) succ(ace_of_hearts, _G7104) ? creep
   Call: (273) false ? creep
   Fail: (273) false ? creep
   Redo: (272) succ(ace_of_hearts, _G7104) ? creep
   Call: (273) succ(ace_of_hearts, _G7104) ? creep
   Call: (274) false ? creep
   Fail: (274) false ? creep
   Redo: (273) succ(ace_of_hearts, _G7104) ? creep
   Call: (274) succ(ace_of_hearts, _G7104) ? creep
   Call: (275) false ? creep

A: Your predicate obviously keeps calling itself: succ(X, Y) :- succ(Y, X), .... A simple solution is not to use the same name for your predicate as you do your facts. Get rid of your succ/2 predicate (leaving the facts) in favor of:
successor(X, Y) :- succ(X, Y).
successor(X, Y) :- succ(X, Z), succ(Z, Y).

beats(X, Y) :- successor(Y, X).


text:
Q: SQL query executed through Windows batch: missing table I execute a SQL query (for PostgreSQL) via psql.exe inside a Windows batch. I get an error I can't explain, saying that a FROM clause is missing for a table that is not called within the query (see below). When I search in the batch file for geo_c3_0_3_mo table, the string is not found...
Any idea on this kind of issue?

EDIT :
If I copy-paste the query from the batch file into a pgAdminIII SQL query window, the query runs perfectly and no error message is returned.
When I remove one of the subqueries, the error either disappear or mention another badly written table name (for instance: missing FROM-clause for table "geoc__0_3_mo")... It seems more and more that the issue comes from the length of the line (19,413 characters!). To me, it is not possible to write the query on several lines within a batch file, like inside a pgAdminIII SQL query window. The solution would be to keep the query inside a *.sql file and to call that file from the batch file.

A: Write the query to a tempfile in your batch, then execute it with psql -f. This will bypass command-line length issues.


text:
Q: Drawing longer arrows in TikZ I have the following diagram:
\begin{tikzcd}[font=\large]

A \rightarrow & B  & C \leftarrow & D\\

E \arrow[hookrightarrow]{u} \rightarrow   & F  \arrow{ru} & G \leftarrow \arrow{ru}

\end{tikzcd}

Is there a way of "drawing" a longer arrow in the 2nd row such that F is below C and G is below D?

A: Do you want this? Your question is not very clear.
% arara: pdflatex

\documentclass{article}
\usepackage{tikz-cd}

\begin{document}
\begin{tikzcd}[font=\large]
    A \arrow{r} & B  & C \arrow{l} & D\\
    E \arrow[hook]{u} \arrow{rr} & & F  \arrow{u} & G \arrow{l} \arrow{u}
\end{tikzcd}
\end{document}


text:
Q: Plots of prior and posterior distributions for different models Consider the code shown below that displays graphically the prior and posterior of the Beta-Binomial Model using different parameters in the prior.
colors = c("red","blue","green","orange","purple")

n = 10
N = 10
theta = .2

x = rbinom(n,N,theta)
grid = seq(0,2,.01)

alpha = c(.5,5,1,2,2)
beta = c(.5,1,3,2,5)

plot(grid,grid,type="n",xlim=c(0,1),ylim=c(0,4),xlab="",ylab="Prior Density",
     main="Prior Distributions", las=1)
for(i in 1:length(alpha)){
    prior = dbeta(grid,alpha[i],beta[i])
    lines(grid,prior,col=colors[i],lwd=2)
}

legend("topleft", legend=c("Beta(0.5,0.5)", "Beta(5,1)", "Beta(1,3)", "Beta(2,2)", "Beta(2,5)"),
       lwd=rep(2,5), col=colors, bty="n", ncol=3)

for(i in 1:length(alpha)){
    dev.new()
    plot(grid,grid,type="n",xlim=c(0,1),ylim=c(0,10),xlab="",ylab="Density",xaxs="i",yaxs="i",
    main="Prior and Posterior Distribution")

    alpha.star = alpha[i] + sum(x)
    beta.star = beta[i] + n*N - sum(x)
    prior = dbeta(grid,alpha[i],beta[i])
    post = dbeta(grid,alpha.star,beta.star)

    lines(grid,post,lwd=2)
    lines(grid,prior,col=colors[i],lwd=2)
    legend("topright",c("Prior","Posterior"),col=c(colors[i],"black"),lwd=2)

}

Some of the plots

How to have similar codes to the one above for the Poisson-Gamma model and inverse chi squared-Normal model?
What I've tried for the Poisson-Gamma is first to change the x=rpois(n,lambda), and to change Beta by Gamma because here the prior has Gamma distribution. For the inverse chi squared-Normal model, would be x=rinvgamma(alpha,beta), here the prior and posterior both have Inverse Gamma distribution.
Where I am having more difficulties is in this part
alpha.star = alpha[i] + sum(x)
    beta.star = beta[i] + n*N - sum(x)
    prior = dbeta(grid,alpha[i],beta[i])
    post = dbeta(grid,alpha.star,beta.star)

I don't know how to change it so that fits for this new model. I have the same issue for the inverse chi squared-Normal model.
Could someone please help?
I would really appreciate any help you're willing to provide.
Any suggestion in the code is welcome.

The code can be founded here https://stats.stackexchange.com/questions/70661/how-does-the-beta-prior-affect-the-posterior-under-a-binomial-likelihood


text:
Q: Invariance of the number of holes Suppose that $\Omega$ is an open subset of $\mathbb{R}^2$. What conditions on $\Omega$ ensure that $\Omega_k$ homeomorphic to $\Omega_l$ implies $k=l$, where $\Omega_k$ denotes $\Omega$ with any $k$ points removed. I know it to be true for $\Omega=\mathbb{R}^2$ (consider the first betti number), but what about the more general situation? In the end this will give a good reason why one should think of the first Betti number as being the number of holes of thst space.

A: One thing you'll want to assume is that $\Omega$ is connected.  Two disjoint disks, each with one point removed, is not homeomorphic to two disks where one has two points removed.


text:
Q: Critical Information In REST URI I am developing a Spring MVC web service. I am trying to use best practices of REST URI design.
For example for getting an account the URI will be
GET   http://blablabla.com/api/accounts/123

My question is what if the account number/id is critical information and must not be in URI. What is the best approach of URI design if the id that defines the resource is a critical information of a system. Should web service get the id in request header or body? Or hash the id and contain it in URI?
Thanks in advance.

A: If by "critical" you mean sensitive/secure, I'd keep URI design AS IS, and put whole session under HTTPS, that way it would be much harder for someone to eavesdrop on the URL itself. See for instance this question
If you mean that information is so sensitive that you don't even trust access logs in your own datacenter, then you have no choice other than put it into the body of the request. Headers are not for useful payload.

A: Use TLS and authentication and your pain will go away.


text:
Q: Google colab not opening suddenly
Hi, I am trying to load the colab. It was working perfectly suddenly it stopped loading.
I tried to clear cookies, reinstalled chrome and opened it in incognito mode. But nothing works.
Can anyone suggest what to do?

A: This looks like a bug. Discussion is at:
https://github.com/googlecolab/colabtools/issues/2251
I'd recommend following up there to help with diagnosis.

A: I just deleted the colab folder from drive. On uploading it again, it worked. I don't know how this happened but I am sharing this as someone might find it useful.


text:
Q: How to create demo for mobile app I know that i can use a screen cast software to capture my display as well as my emulator. But how can i replace my mouse icon with a circle like in this video
http://www.peterfriese.de/save-a-tree-put-eclipsecon-2011-in-your-pocket/
Thanks

A: I use SimFinger for my iPhone promotional videos

A: This feature is entirely dependent on the screencasting software you choose. I believe Camtasia Studio does it (commercial software). There is also CamStudio which is free and claims to support mouse highlighting, but I've never used it.

A: I used iSimulate for this purpose. I think that is what they used in your example, too.

A: If you are looking to create a demo of your app for promotion, sharing, or feedback a couple of good options are available for iOS and Android.
For android you have appsurfer.com (I'm part of the team). For iOs users, you have pieceable.com and app.io
You can create embedable widgets of your apps and put them on blogs, product pages etc.


text:
Q: Generic hash codes in Java I am somewhat new to Java. Is there is a hashcode utility class that can generate a good hash code for a generic object with members of arbitrary types inside the class? Can I recursively step through the instance of a generic java object and accumulate a hash code that guarantees two equal objects of this class will always compute the same hash code? The context of this question is Android and the Objects.hashCode() etc is not available to me in the Java version I am using (and I have no option to migrate to a newer version).
I am guessing the answer is no based on what I have seen so far.

A: You could try the HashCodeBuilder from Apache Commons Lang. It's able to generate a hash code reflectively as follows:
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

A: Since Java 7, you have Objects.hash()
return Objects.hash(this.foo, this.bar, this.baz);

it also helps implementing equals:
return Objects.equals(this.foo, o.foo)
       && Objects.equals(this.bar, o.baz)
       && Objects.equals(this.baz, o.baz)

A: There's a helper class from Apache Commons-Lang project, named HashCodeBuilder. You can use it in each and every hashCode you need, or you could play with reflection (maybe with the help of some other library if you follow some pattern, like Java Bean) to iterate the fields recursively - but must be very careful to define when to stop and avoid endless loops.

A: I recommend to use Guava on a daily basis. What you need is Hasher


text:
Q: Angular and .Net Core Project VS 2022: An unhandled exception occurred: Project 'Leon\AppData\Roaming\ASP.NET\https\.pem' does not exist Hello I am building an Angular/.Net Core project and creating the projects by following Microsoft's suggestion, https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-angular?view=vs-2022. I created one on my laptop which starts without a problem and one on my PC which fails. The key difference and what I suspect to be the problem is that my username on my PC has a space,"Eric Leon", while on my laptop is "eric.leon" but I can't figure out how to fix it. I searched articles and made sure that everything looked good on the angular.json and package.json files.
This is the Error

The error log does not contain more relevant information than the output. Notice how the Project starts with Leon\AppData\... instead of C:\users\Eric Leon\... and this is why I suspect the username is the problem, because it looks like its cutting of the path at the space in the username. I also looked at the aspnetcore-https.js which seems to be building the path and even replaced the baseFolder with a hardcoded path with that contained %20 in the name const baseFolder = 'C:/Users/Eric%20Leon/AppData/Roaming/ASP.NET\https'.

After hours of looking at this I haven't had success so far so any help would be appreciated

A: In package.json the start path for the .pem file and the .key file is specified.
"ng serve --ssl --ssl-cert %APPDATA%\\ASP.NET\\https..."
--ssl-cert should contain *C:\Users* and %APPDATA% should contain username\APPDATA\Roaming but in this case --ssl-cert included the first part of my username (firstname) and %APPDATA% started from the second part of the username (lastname). The solution was to put double quotes around %APPDATA% since command line tools only support double quotes and escape them with backslash since its in a json file.
so "ng serve --ssl --ssl-cert \"%APPDATA%\"\\ASP.NET\\https..."
Prior to that I was working around the issue by putting the files in a folder on the C drive and hardcoding the path.


text:
Q: Join two Box2d Bodies I am creating an app in which i am trying to Join two bodies in such away that when i move one body, the second body should be moved within the first body.
Here's my code to create a body:
    - (b2Body *)addBoxBodyForDynamicSprite:(CCSprite *)sprite {

    b2BodyDef spriteBodyDef;
    spriteBodyDef.type = b2_dynamicBody;
    //spriteBodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y/PTM_RATIO);
    CGPoint asolutePoint = [sprite.parent convertToWorldSpace:sprite.position];
    spriteBodyDef.position.Set(asolutePoint.x/PTM_RATIO, asolutePoint.y/PTM_RATIO);
    spriteBodyDef.userData = (__bridge void*)sprite;
    b2Body *spriteBody = world->CreateBody(&spriteBodyDef);

    b2PolygonShape spriteShape;
    spriteShape.SetAsBox(sprite.contentSize.width/PTM_RATIO/2,
                         sprite.contentSize.height/PTM_RATIO/2);
    b2FixtureDef spriteShapeDef;
    spriteShapeDef.shape = &spriteShape;
    spriteShapeDef.density = 0.3;
    spriteShapeDef.isSensor = true;
    spriteBody->CreateFixture(&spriteShapeDef);

    return spriteBody;
}

One body is kinematic and other body is Dynamic. I am moving these bodies by using:
theBody->SetTransform(locationWorld, theBody->GetAngle());

If i apply linear force here, the bodies are not moving & the Joint which i used to fix them is b2WeldJoint.
b2JointDef jointDef;
    jointDef.bodyA = another;
    jointDef.bodyB = leftHandFixBody;
    aJoint = (b2Joint *)world->CreateJoint(&jointDef);

It moves the dynamic body but the kinematic body remains on its position. I want to move both the bodies together. Any help will be really appreciated. Thanks!

A: Also, according to the manual, kinematic bodies are moved by setting their velocity, not by applying forces.

A kinematic body moves under simulation according to its velocity.
  Kinematic bodies do not respond to forces. They can be moved manually
  by the user, but normally a kinematic body is moved by setting its
  velocity. A kinematic body behaves as if it has infinite mass,
  however, Box2D stores zero for the mass and the inverse mass.
  Kinematic bodies do not collide with other kinematic or static bodies.

Also, I have found that using SetTransform(...) to move bodies is less than effective.  I created a portal with it to jump a body from one place to another, and that worked.  But if I updated it every simulation cycle, the body stopped colliding with other bodies.  This is just a word of caution.
Was this helpful?


text:
Q: Использование API Интересует вопрос, имеет ли смысл создавать API и подгружать данные на сайт, используя запросы к этому API, ведь можно просто подгружать информацию с базы данных напрямую.
Большие компании предоставляют свои API, в которых собрана некая информация, для того чтобы этим могли пользоваться все кто пожелает, но есть ли смысл делать API для своих небольших сайтов, чтобы подгружать информацию оттуда, а не напрямую с базы данных?


text:
Q: Indent second line of UILabel (swift) var testLabel = UILabel(frame: CGRectMake(8,0,tableView.frame.width-8,100))
let testDesc = "dsfdddfdsfdsfsdfdsfdsfdsfdsfdsfsdfdsfsdfsdfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsf"
var labelString = indexString + ".    " + testDesc
testLabel.text = labelString
testLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
testLabel.numberOfLines = 0
retCell.addSubview(testLabel)

My output:
1.    ksajdkasdsajdksajdksajd
asjdkjassadkasldkalsdklsakdl

How can make my output like the following:
1.    asdasdasdasdasdasdasds
      djaskdjsadjksadasjdjas

A: Make an attributed string (NSMutableAttributedString) and set its paragraph style's firstLineHeadIndent and headIndent as desired. Now set the label's attributedText to that attributed string.

A: Here is the code that I used
let paragraph = NSMutableParagraphStyle()
paragraph.firstLineHeadIndent = 0
paragraph.headIndent = 8 //You can change this to whatever indent you want

let mutString = NSAttributedString(
    string: "this is a test but I need this to be long so it flows onto multiple lines so I will keep going",
    attributes: [NSAttributedStringKey.paragraphStyle: paragraph]
)

mainLabel.attributedText = mutString


text:
Q: Make a Perl object callable? In Perl 5, is there a way to make an object callable?
Example.pm
package Example;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $self = {};
    bless($self, $class);
    return $self;
}

# implement function to make class callable

1;

main.pl
use Example;
my $ex = Example->new();
my $ex(); # call the object like this

A: This can be done by blessing a function reference instead of a hash reference to create the class.
For example:
Example.pm:
package Example;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $self = \&call;
    bless($self, $class);
    return $self;
}

# implement function to make class callable
sub call {
    print "Calling the function\n";
}

1;

main.pl:
use strict;
use warnings;
use Example;

my $ex = Example->new();
$ex->();

Output:

Calling the function


text:
Q: Retrieve SecKey from Keychain I am trying to upgrade the code that I got from this answer for generating CSR, from Swift 2 to Swift 3.
I have most of the code upgraded, but the following code in the Utility block of the original answer failed with the error:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

The error occurs at the line:

let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as NSDictionary, UnsafeMutablePointer($0)) }

func loadKeySecKeyFromKeyChain(key: String) -> SecKey{
    let query: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits): KEY_SIZE as AnyObject,
        String(kSecClass): kSecClassKey,
        String(kSecAttrApplicationTag): key as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue ]

    var dataTypeRef: Unmanaged<AnyObject>? = nil
    var resultData: SecKey? = nil

    let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as NSDictionary, UnsafeMutablePointer($0)) }
    NSLog("SecItemCopyMatching: " + status.description)

    if status == errSecSuccess {
        NSLog("private or public debug description is: " + dataTypeRef.debugDescription)
        resultData = (dataTypeRef!.takeRetainedValue() as! SecKey)
        NSLog("SecItemCopyMatching returns SecKey: " + resultData.debugDescription)
        return resultData!
    } else {
        return resultData!
    }
}

I have been stuck on this for a whole day, is there any suggestions for how to resolve this error?

A: Just use SecItemCopyMatching. I was able to convert it to Swift 3 and successfully generate CSR.
// Finds the SecKeyRef corresponding to the parameter key and returns it
func loadKeySecKeyFromKeyChain(key: String) -> SecKey {
    let query: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits): KEY_SIZE as AnyObject,
        String(kSecClass): kSecClassKey,
        String(kSecAttrApplicationTag): key as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue ]

    var dataTypeRef: Unmanaged<AnyObject>? = nil
    var resultData: SecKey? = nil
    var result: AnyObject?
    let status = SecItemCopyMatching(query as CFDictionary, &result)

    if status == errSecSuccess {
        resultData = result as! SecKey
        return resultData!
    } else {
        return resultData!
    }
}


text:
Q: Move file based on condition Can anyone help me finding solution to my requirement.
the requirement is I have to write a shell script which will scan a directory and read each file coming to it and will search for a string starts with (like "AB00732614") It will search for all files which contains AB* then it will move the file to another directory.

A: Assuming that the string AB-etc. is part of the contents of the files to be moved:
find /path/to/dir -type f -exec grep -qE 'AB[0-9]{8}' {} \; -exec mv -i {} /path/to/destination/ \;

This uses find to find all regular files under /path/to/dir.  For each file, grep will look whether it contains anything matching the extended regular expression AB[0-9]{8} (the string AB followed by exactly eight digits).  If it does, the file is moved to the directory /path/to/destination/.
If another file with the same name as the file being moved is already in the destination directory, you will have to confirm that you would like to overwrite that file.

A: You can use:
find . -type f -iname 'AB*' -exec mv -t ./another_directory/ {} \+

It is very well explained here: https://stackoverflow.com/a/5607677


text:
Q: Как хранить дерево Хаффмана? Подскажите по реализации сжатия статическим методом Хаффмана. Каким образом оптимально хранить в файле дерево Хаффмана?
A: Не обязательно сохранять дерево. Можно просто хранить счетчики для каждого символа в начале файла, а дерево восстанавливать перед декодингом. Eсли хранить счетчики по 8 байт, то потребуется 8B * 256 = 2KiB, что совсем не много.
UPD: если жалко 2KiB, то можно хранить счетчики более компактно. Например, ввести следующий формат для счетчика: префикс + счетчик. Префикс представляет собой трехбитовое целое число, равное размеру счетчика в байтах. Примеры:

*

*Счетчик равен 0. Сохраняется в 000 (3 бита).

*Счеткик равен 222. Сохраняется в 00111011110 (11 бит).

*Счетчик равен 1024. Cохраняется в 0100000010000000000 (19 бит).

Т.е. размер сохраненных данных для счетчика n будет равен ceil(ceil(log_2(n)) /  8) * 8 + 3 бит.
UPD2: придумал еще один способ, который, как мне кажется, лучше предыдущего.
Для начала опишу какую реализацию алгоритма построения дерева я собираюсь использовать:
nodes = [Node(WEIGHT[c], c) for c in ALPHABET].sort(reverse=True)
while nodes.size() != 1:
  l, r = nodes[0:2]
  nodes = nodes[2:]
  new_node = create_node_with_children(l, r)
  insert_index = 0
  if nodes.size() > 1: # на 2-x последних шагах уже не важен порядок
    while insert_index < nodes.size() and nodes[insert_index].weight > new_node.weight:
      insert_index += 1
  nodes[insert_index:insert_index] = [new_node]

Если внимательно посмотреть на код, то можно понять, что для восстановления топологии дерева нам достатоточно знать начальную расстановку символов в nodes и insert_index на каждом из шагов. Посчитаем сколько на это надо памяти.
Для хранения изначальной перестановки понадобится 255 байт (первый/последний символ можно не хранить, а получить методом исключения).
Далее замечаем, что число итераций в алгоритме фиксировано (255) и на i-ой итерации (считая с нуля) insert_index лежит в диапазоне [0, 255 - i), поэтому мы можем на поздних итерациях выделять меньше бит на хранения insert_index. А конкретно:
  i        | число бит на индекс
[0, 127)   | 8
[127, 191) | 7
[191, 223) | 6
[223, 239) | 5
[239, 247) | 4
[247, 251) | 3
[251, 253) | 2
[254, 256) | 0 // тут не надо ничего сохранять

Т.е. для хранeния индексов вставки нужно 127 * 8 + 64 * 7 + 32 * 6 + 16 * 5 + 8 * 4 + 4 * 3 + 2 * 2 = 1784 бит = 223 байт.
Итого получаем 255 + 223 = 478 байт, причем это число не зависит от размера входных данных, в отличии от способа описанного выше.
A: Я ничего не утверждаю, но кгда делал сам, то просто хранил символы в порядке уменьшения частоты и нечего больше.
Т.к. Хафмен оптимальный префиксный код, то по порядку символа в последовательности можно определить однозначно код.
A: @DarkGenius, Вы уже написали хороший вариант в комментарии -
Храним в файле информацию о структуре дерева. Для узла записываем левое поддерево, правое поддерево и бит "0", для листа записываем сам символ и бит "1". Начинаем сохранение, очевидно, с записи корня.
Действительно, получается достаточно эффективно, тем более, что у вершины дерева может только либо не быть потомков, либо быть два. 2 бита * (количество символов - 1) + сами символы (скорее всего, по 8 бит).
Но я расспросил коллегу, который делал более хитро. У него получилось примерно 1 бит на символ +, естественно, сами символы. Идея следующая: перестраиваем дерево так, чтобы оно было перекошено строго в одну сторону. Теперь перебираем все листы слева направо и записываем глубину, на которой они находятся. Для
 / \
a  /\
  d  /\
    c  b

получается
a d c b
1 2 3 3

Теперь остаётся записать символы в получившемся порядке, начальную глубину и "растёт-не растёт". Правда, вырасти может и на два и на три... На этот случай надо делать какое-нибудь адаптивное арифметическое кодирование. Но в основном должны быть 0 и 1, которые как раз закодируются одним битиком. Вобщем, по заключению коллеги, битик экономится, но очень трудоёмко в реализации.
Upd: или не арифметическим, а кодировать группы чисел Хаффманом с фиксированным деревом. Или хранить позиции чисел, отличных от 0, 1.
Под перекашиванием я имел в виду нечто вроде сортировки. Например,
   /    \
  /\   / \
 /\ c d  /\
a  b    e  f

надо преобразовать путём перестановки поддеревьев в
   /      \
  /\    /   \
 с  d  /\   /\
      a  b e  f


text:
Q: Webview inside scrollview not loading full content in android oreo Webview inside scrollview not loading full content in android oreo.
 <Scrollview>
<TextView>
         </TextView>
         <WebView>
         </WebView>
    </Scrollview>

Its not loading full page content.
Just try with the following url.
"Webview in Oreo not working"
Can anyone help me to solve this...


text:
Q: WSO2 APIM Analytics 3.1.0 server's Dashboard profile errors out while starting and the Analytics Dashboard doesn't open I was following one of the tutorials from WSO2's learning website and tried to setup the Analytics server 3.1.0 with APIM 3.1.0. I followed the below sequence of starting the servers.

*

*APIM Analytics worker profile

*APIM server

*APIM Analytics dashboard profile

The APIM Analytics worker profile and the APIM server started without any issue.
But on starting the Analytics dashboard profile, I am getting the below error though i can see message at the last that APIM Analytics Server started.
 **ERROR** {msf4j-core} - [SCR] Error while trying to bind reference Reference[name = microservice, interface = org.wso2.msf4j.Microservice, policy = dynamic, cardinality = 0..n, target = null, bind = addService, unbind = removeService]
        Details:
        Problematic reference = Reference[name = microservice, interface = org.wso2.msf4j.Microservice, policy = dynamic, cardinality = 0..n, target = null, bind = addService, unbind = removeService]
        of service component = org.wso2.msf4j.internal.MicroServicesServerSC
        component implementation class = org.wso2.msf4j.internal.MicroservicesServerSC
        located in bundle with symbolic name = msf4j-core
        bundle location = reference:file:../lib/plugins/msf4j-core_2.7.7.jar java.lang.reflect.InvocationTargetException
        at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.eclipse.equinox.internal.ds.model.ComponentReference.bind(ComponentReference.java:376)
        at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.bindReference(ServiceComponentProp.java:444)
        at org.eclipse.equinox.internal.ds.InstanceProcess.dynamicBind(InstanceProcess.java:416)
        at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:334)
        at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
        at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:915)
        at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
        at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
        at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:862)
        at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:801)
        at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127)
        at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:225)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:464)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:482)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:999)
        at org.wso2.carbon.uiserver.internal.deployment.msf4j.MicroservicesRegistrar.register(MicroservicesRegistrar.java:154)
        at org.wso2.carbon.uiserver.internal.deployment.msf4j.MicroservicesRegistrar.lambda$register$3(MicroservicesRegistrar.java:144)
        at org.wso2.carbon.uiserver.internal.deployment.msf4j.MicroservicesRegistrar$$Lambda$282.00000000160C0730.apply(Unknown Source)
        at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
        at java.util.HashMap$KeySpliterator.forEachRemaining(HashMap.java:1556)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:496)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:486)
        at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:241)
        at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
        at org.wso2.carbon.uiserver.internal.deployment.msf4j.MicroservicesRegistrar.register(MicroservicesRegistrar.java:145)
        at org.wso2.carbon.uiserver.internal.deployment.listener.AppTransportBinder.appDeploymentEvent(AppTransportBinder.java:76)
        at org.wso2.carbon.uiserver.internal.io.deployment.ArtifactAppDeployer.publishAppDeploymentEvent(ArtifactAppDeployer.java:154)
        at org.wso2.carbon.uiserver.internal.io.deployment.ArtifactAppDeployer.deploy(ArtifactAppDeployer.java:103)
        at org.wso2.carbon.deployment.engine.internal.DeploymentEngine.lambda$deployArtifacts$0(DeploymentEngine.java:291)
        at org.wso2.carbon.deployment.engine.internal.DeploymentEngine$$Lambda$237.0000000015F30F90.accept(Unknown Source)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at org.wso2.carbon.deployment.engine.internal.DeploymentEngine.deployArtifacts(DeploymentEngine.java:282)
        at org.wso2.carbon.deployment.engine.internal.RepositoryScanner.sweep(RepositoryScanner.java:112)
        at org.wso2.carbon.deployment.engine.internal.RepositoryScanner.scan(RepositoryScanner.java:68)
        at org.wso2.carbon.deployment.engine.internal.DeploymentEngine.start(DeploymentEngine.java:121)
        at org.wso2.carbon.deployment.engine.internal.DeploymentEngineListenerComponent.onAllRequiredCapabilitiesAvailable(DeploymentEngineListenerComponent.java:216)
        at org.wso2.carbon.kernel.internal.startupresolver.StartupComponentManager.lambda$notifySatisfiableComponents$7(StartupComponentManager.java:266)
        at org.wso2.carbon.kernel.internal.startupresolver.StartupComponentManager$$Lambda$159.0000000013DAFD90.accept(Unknown Source)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at org.wso2.carbon.kernel.internal.startupresolver.StartupComponentManager.notifySatisfiableComponents(StartupComponentManager.java:252)
        at org.wso2.carbon.kernel.internal.startupresolver.StartupOrderResolver$1.run(StartupOrderResolver.java:204)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)
Caused by: java.lang.NoClassDefFoundError: org.wso2.msf4j.util.RuntimeAnnotations (initialization failure)
        at java.lang.J9VMInternals.initializationAlreadyFailed(J9VMInternals.java:96)
        at org.wso2.msf4j.internal.MicroservicesServerSC.addMicroserviceToRegistry(MicroservicesServerSC.java:421)
        at org.wso2.msf4j.internal.MicroservicesServerSC.addService(MicroservicesServerSC.java:108)
        ... 49 more
Caused by: java.lang.IllegalStateException: java.lang.ClassNotFoundException: java.lang.Class$Atomic
        at org.wso2.msf4j.util.RuntimeAnnotations.<clinit>(RuntimeAnnotations.java:110)
        at org.wso2.msf4j.internal.MicroservicesServerSC.addMicroserviceToRegistry(MicroservicesServerSC.java:421)
        at org.wso2.msf4j.internal.MicroservicesServerSC.addService(MicroservicesServerSC.java:108)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        ... 48 more
Caused by: java.lang.ClassNotFoundException: java.lang.Class$Atomic
        at java.lang.Class.forNameImpl(Native Method)
        at java.lang.Class.forName(Class.java:332)
        at org.wso2.msf4j.util.RuntimeAnnotations.<clinit>(RuntimeAnnotations.java:58)
        ... 52 more

[2020-07-22 21:36:30,653]  INFO {org.wso2.carbon.uiserver.internal.deployment.listener.AppTransportBinder} - Web app 'policies' is available at 'https://10.184.69.117:9643/policies'.
[2020-07-22 21:36:30,662]  INFO {org.wso2.carbon.kernel.internal.CarbonStartupHandler} - **WSO2 API Manager Analytics Server started in 10.285 sec**

And, when I try to open the link : https://localhost:9643/analytics-dashboard/ , it gives an error which says: "Problem accessing: /analytics-dashboard/. Reason: Not Found".
Need help with this issue.

A: What version of Java are you using?
According to the error, you are looking for a class that does not exist, it may be a standard class that only has one version, I recommend using Java 11 for this version.


text:
Q: Vector field contour for a linear system Let's say $\boldsymbol{\vec F}$ is a field vector with a liner relationship
$$\boldsymbol{\vec F}(\boldsymbol{\vec  x})=\boldsymbol A \boldsymbol{\vec  x}$$
where $\boldsymbol{\vec  x}$ is a vector of size $n$ and $\boldsymbol A$ is a constant $n\times n$ square matrix.
For a given point $\boldsymbol{\vec  x}_0$, how can I find the hyper-surface $S(\boldsymbol{\vec  x})=0$ which crosses $\boldsymbol{\vec  x}_0$ and it is perpendicular to the vector field $\boldsymbol{\vec F}$?
I believe this there is an explicit form of the surface which depends on $\boldsymbol{\vec  x}_0$ and $\boldsymbol A$.

On hyper-surface $S$, there will be $n-1$ degree of freedom.
I am looking for a solution for an $n$ dimension vector field. This image is just for illustration.

PS. This question is a special case (linear form) of my previous question.

A: Such orthogonal hypersurfaces need not exist if $n\geq3$. Relevant here is Frobenius' theorem that gives the necessary and sufficient local integrability condition. The following source
http://staff.ustc.edu.cn/~wangzuoq/Courses/16F-Manifolds/Notes/Lec11.pdf
contains a readable introduction. Note that your vector field ${\bf F}$ defines at each point ${\bf x}$ an $(n-1)$-dimensional orthogonal hyperplane, called a distribution in the quoted notes.
Frobenius' theorem expands to a condition on the matrix $A$ in your question. The case $n=3$ should be intuitively comprehensible. About this case  I can say the following: If the vector field ${\bf F}$ has orthogonal surfaces these can be regarded as level surfaces of some scalar function $g$. This $g$ has an associated gradient field $\nabla g$ which then is orthogonal to these same surfaces, hence parallel to ${\bf F}$. It follows that there is a scalar function $\lambda$ such that
$${\bf F}=\lambda\>\nabla g\ .$$
We now compute $${\rm curl}({\bf F})=\nabla\lambda\times\nabla g\ .$$
It follows that ${\rm curl}({\bf F})$ is orthogonal to $\nabla g$, hence to the given ${\bf F}$. In this way we have derived the integrability condition
$${\rm curl}({\bf F})\cdot{\bf F}\equiv0\ .\tag{1}$$
This is a necessary condition for the existence of such a family of orthogonal surfaces. Frobenius' theorem says that this condition is also (locally) sufficient. (Unfortunately I could not find a proof of this simple case of Frobenius' theorem on the web.)
In the case of your ${\bf F}:=A{\bf x}$ this means the following: Being a linear function of ${\bf x}$ the field ${\bf F}$ has constant curl ${\bf c}=(A_{32}-A_{23},A_{13}-A_{31}, A_{21}-A_{12})$. The condition $(1)$ then expands to
$$A^{\top}{\bf c}={\bf 0}\ .\tag{2}$$
If $A$ is nonsingular then $(2)$ enforces ${\bf c}={\bf 0}$, which means that $A$ has to be a symmetric matrix. Rodrigo de Azevedo's solution shows that in this case we indeed can find orthogonal surfaces.

A: Given a linear vector field $\mathrm v : \mathbb R^n \to \mathbb R^n$ defined by $\rm v (x) :=  A x$ and a point $\mathrm x_0 \in \mathbb R^n$, we would like to find a function $f : \mathbb R^n \to \mathbb R$ such that vector field $\rm v$ is orthogonal to the following level set
$$\mathcal S := \left\{ \mathrm x \in \mathbb R^n \mid  f (\mathrm x) = 0 \right\}$$
and $\mathrm x_0 \in \mathcal S$. Let us demand that $\rm v$ be orthogonal to all level sets of $f$. Hence,
$$\nabla f (\mathrm x) = \mathrm A \mathrm x$$
Assuming that matrix $\rm A$ is symmetric and integrating the set of linear PDEs above, we obtain
$$f (\mathrm x) = \frac 12 \mathrm x^\top \mathrm A \, \mathrm x + f_0$$
Since $\mathrm x_0 \in \mathcal S$, the value of the integration constant is
$$f_0 = - \frac 12 \mathrm x_0^\top \mathrm A \, \mathrm x_0$$
and, thus,
$$f (\mathrm x) = \frac 12 \mathrm x^\top \mathrm A \, \mathrm x - \frac 12 \mathrm x_0^\top \mathrm A \, \mathrm x_0$$
If matrix $\rm A$ is not symmetric, then I do not know how to integrate the linear PDEs.

Example
Let $n=2$. Given $\mathrm A = \begin{bmatrix} 2 & 1\\ 1 & 2\end{bmatrix}$ and $\mathrm x_0 = \begin{bmatrix} 2\\ 0\end{bmatrix}$, we obtain the function
$$f (x_1, x_2) = x_1^2 + x_1 x_2 + x_2^2 - 4$$
The following plot depicts the level set (an ellipse) and the vector field. The length of the arrows is not proportional to $\| \rm A x \|_2$. The purpose is to show that the vector field is orthogonal to the ellipse.

Addendum
Let $n = 2$. The constraint $\nabla f (\mathrm x) = \mathrm A \mathrm x$ produces the following linear PDEs
$$\partial_1 f = a_{11} \, x_1 + a_{12} \, x_2 \tag{1}$$
$$\partial_2 f = a_{21} \, x_1 + a_{22} \, x_2 \tag{2}$$
Integrating equation (1) with respect to $x_1$, we obtain
$$f (x_1,x_2) = \frac 12 \, a_{11} \, x_1^2 + a_{12} \, x_1 \, x_2 + g (x_2)$$
Differentiating $f$ with respect to $x_2$ and using equation (2), we obtain the ODE
$$g' (x_2) = a_{22} \, x_2 + \underbrace{(a_{21} - a_{12})}_{= 0} \, x_1 = a_{22} \, x_2$$
which allows us to conclude that $a_{21} = a_{12}$, i.e., matrix $\rm A$ is symmetric. Integrating the ODE,
$$g (x_2) = \frac 12 \, a_{22} \, x_2^2 +  c$$
where $c$ is an integration constant. Thus,
$$f (x_1,x_2) = \frac 12 \, a_{11} \, x_1^2 + a_{12} \, x_1 \, x_2 + \frac 12 \, a_{22} \, x_2^2 +  c$$

A: In order to satisfy the perpendicularity condition, the vector field ${\bf F}(x)$ should be collinear to the normal vector of the hypersurface $S(x)=0$, i.e.
$\forall x\in\mathbb R^n\; \exists k(x)\in\mathbb R:$
$$\tag{1}
\nabla S(x)=k(x){\bf F}(x).
$$
Let $F(x)=(f_1(x),\ldots,f_n(x))$, then (1) can be rewritten in the coordinate form as
$$
\frac{\partial S}{\partial x_1}=k(x)f_1(x)\;,\ldots,\;\frac{\partial S}{\partial x_n}=k(x)f_n(x);
$$
or
$$
k(x)=\frac{\frac{\partial S}{\partial x_1}}{f_1(x)}=\;\ldots\;=
\frac{\frac{\partial S}{\partial x_n}}{f_n(x)}.
$$
We can equate the adjacent fractions and obtain
$$
\left\{\begin{array}{rcl}
f_2(x)\dfrac{\partial S}{\partial x_1}&=&f_1(x)\dfrac{\partial S}{\partial x_2}\\
&\vdots&\\
f_n(x)\dfrac{\partial S}{\partial x_{n-1}}&=&f_{n-1}(x)\dfrac{\partial S}{\partial x_n}\\
\end{array}\right.
$$
or finally
$$\tag{2}
\left\{\begin{array}{lll}
f_2(x)\dfrac{\partial S}{\partial x_1}-f_1(x)\dfrac{\partial S}{\partial x_2}&=&0\\
&\vdots&\\
f_n(x)\dfrac{\partial S}{\partial x_{n-1}}-f_{n-1}(x)\dfrac{\partial S}{\partial x_n}&=&0.\\
\end{array}\right.
$$
Hence, the question is: does the system (2) have nontrivial solutions?
1) n=2
Consider at first the simple case when $n=2$. In this case the system (2) consists of one equation
$$\tag{2a}
f_2(x)\dfrac{\partial S}{\partial x_1}-f_1(x)\dfrac{\partial S}{\partial x_2}=0.
$$
This equation can be solved using the method of characteristics:
$$\tag{3}
\frac{dx_1}{f_2(x)}=\frac{dx_2}{-f_1(x)}.
$$
The ode (3) always have a solution for any initial point (except for the case $f_1(x)=f_2(x)=0$), thus, the curve $S(x)=0$ exists.
Consider the subcase when ${\bf F}(x)$ is linear:
$$
f_1(x)= a_{11}x_1+a_{12}x_2,\quad f_2(x)= a_{21}x_1+a_{22}x_2.
$$
In this case the ode (3) has the form
$$
\frac{dx_1}{a_{21}x_1+a_{22}x_2}=\frac{dx_2}{-a_{11}x_1-a_{12}x_2}.
$$
It is a homogeneous differential equation, thus, a closed form solution can be found.
2) n>2
In the case when $n\ge 3$, there is a possibility that (2) has no nontrivial solutions. This is because the distribution spanned by the vector fields corresponding to the equations of (2) is not necessarily involutive.
The system (2) can be expressed in terms of the Lie derivative:
$$\tag{2b}
\mathcal L_{{\bf X}_1}S=0,\;\ldots,\;\mathcal L_{{\bf X}_{n-1}}S=0,
$$
where
$$
{\bf X}_1= \left( f_2(x),-f_1(x),0,\ldots,0 \right)^T,\;\ldots\;
{\bf X}_{n-1}= \left( 0,\ldots,0,f_n(x),-f_{n-1}(x) \right)^T
$$
The key fact about the system (2b) is that it implies
$$
\mathcal L_{[{\bf X}_i,{\bf X}_j]}S=
\mathcal L_{{\bf X}_i}(\mathcal L_{{\bf X}_j}S)-\mathcal L_{{\bf X}_j}(\mathcal L_{{\bf X}_i}S)=0
$$
for any $i,j=1,..,n-1$, where $[{\bf X}_i,{\bf X}_j]$ is the Lie bracket.
The distribution $D(x)=span\{{\bf X}_1,\;\ldots\;{\bf X}_{n-1}\}$ is involutive iff the Lie bracket $[{\bf X}_i,{\bf X}_j]$ of any pair of the vector fields ${\bf X}_1,\;\ldots\;{\bf X}_{n-1}$ belongs to $D(x)$, i.e. $[{\bf X}_i,{\bf X}_j]$ is a linear combination of the original vector fields. If the distribution is not involutive (let, for example, $[{\bf X}_i,{\bf X}_j]\notin D(x)$), then we can add the equation $\mathcal L_{[{\bf X}_i,{\bf X}_j]}S=0$ (which is not a linear combination of other equations) to (2b) without changing the solution set.
Now consider the counterexample. Let $n=3$, ${\bf F}(x)=(x_3,x_1,x_2)$. The system (2) becomes
$$\tag{2c}
\left\{\begin{array}{lll}
x_1\dfrac{\partial S}{\partial x_1}-x_3\dfrac{\partial S}{\partial x_2}&=&0\\
x_2\dfrac{\partial S}{\partial x_2}-x_1\dfrac{\partial S}{\partial x_3}&=&0.\\
\end{array}\right.
$$
The Lie bracket of the vector fields
$$
{\bf X}_1=(x_1,-x_3,0)^T,\quad {\bf X}_2=(0,x_2,-x_1)^T
$$
can be calculated as
$$
[{\bf X}_1,{\bf X}_2]=\frac{\partial {\bf X}_2}{\partial x} {\bf X}_1-
\frac{\partial {\bf X}_1}{\partial x} {\bf X}_2
$$
$$
=\left(\begin{array}{ccc}
0&0&0\\0&1&0\\-1&0&0
\end{array}\right)
\left(\begin{array}{c}
x_1\\-x_3\\0
\end{array}\right)-
\left(\begin{array}{ccc}
1&0&0\\0&0&-1\\0&0&0
\end{array}\right)
\left(\begin{array}{c}
0\\x_2\\-x_1
\end{array}\right)=
\left(\begin{array}{c}
0\\-x_1-x_3\\-x_1
\end{array}\right).
$$
Hence, the system (2c) is equivalent to the system
$$\tag{2d}
\left\{\begin{array}{rrrll}
x_1\dfrac{\partial S}{\partial x_1}&-x_3\dfrac{\partial S}{\partial x_2}&&=&0\\
&x_2\dfrac{\partial S}{\partial x_2}&-x_1\dfrac{\partial S}{\partial x_3}&=&0\\
&(-x_1-x_3)\dfrac{\partial S}{\partial x_2}&-x_1\dfrac{\partial S}{\partial x_3}&=&0\\
\end{array}\right.,
$$
but the system (2d) has no nontrivial solutions. From the last two equations
$$
(-x_1-x_3-x_2)\dfrac{\partial S}{\partial x_2}=0;
$$
we are not interested in the solutions on the plane $-x_1-x_3-x_2=0$, so
we can assume that $\dfrac{\partial S}{\partial x_2}=0$. Then it is easy to see that
$$
\dfrac{\partial S}{\partial x_2}=\dfrac{\partial S}{\partial x_1}=\dfrac{\partial S}{\partial x_3}=0,
$$
so the only possible solution is trivial.


text:
Q: Game of Life C++, checking neighbors I am trying to write Conway's Game of Life.
Unfortunately, when I go to check a block's neighbors, I always receive an error at certain elements in my arrays. Specifically at grid[0][11] it gives me one neighbor, however, I have it set so that I only ever add value to a variable called neighbors when a block around it is not space, or ' ' in my code.
The conditions in the if statements, I believe, also account so that it does not go outside the array.
The entire array is filled with ' ', and I still get a value to neighbor despite this.
I have been at this for hours and have found no solution. My code is still riddled with attempts to test, and I apologize for its lack of neatness. Thank you all in advance for any help you can give in solving my problem.
int _tmain(int argc, _TCHAR* argv[])
{
    bool infloop = true;
    //Create the playing grid.
    char grid[HEIGHT][WIDTH];
    //Comment out later. Used for testing.
    for(int i=0; i<75; i++)
        for(int j=0; j<22; j++)
            grid[i][j] = ' ';

    //Create initial seed here. grid [x coordinate] [y coordinate].
    //grid [1][1] = '+'; grid [2][1] = '+'; grid [3][1] = '+';

    //Key. * is going to live. + is alive currently.
    //- is going to die, and negative space is dead.

    //As Conway's Game of Life runs infinitely, create an infinite loop.
    while (infloop)
        generation(grid);

    cout << endl;
    system("pause");
    return 0;
}

void generation(char grid[][WIDTH]) {

    int neighbors;

    /*Check each point on the grid for alive or dead. If it is, check the
    surrounding neighbors and apply the game's rules.*/
    for(int x=0; x<75; x++) {
        for(int y=0; y<22; y++)
        {

            neighbors = 0;
            /*check all eight neighbors except for when outside of the
            array.*/
            if((grid[x+1][y] != ' ') && (grid[x+1][y] < grid[HEIGHT][y])){
                neighbors++; cout << "A";
            }

            if((grid[x-1][y] != ' ') && (grid[x-1][y] > grid[-1][y])){
                neighbors++; cout << "E";
            }

            if((grid[x][y+1] != ' ') && (grid[x][y+1] < grid[x][WIDTH])){
                neighbors++; cout << "C";
            }

            if((grid[x][y-1] != ' ') && (grid[x][y-1] > grid[x][-1])){
                neighbors++; cout << "G";
            }

            if((grid[x+1][y+1] != ' ') && (grid[x+1][y+1] < grid[HEIGHT][WIDTH])){
                neighbors++; cout << "B";
            }

            grid[0][11] = ' '; grid[11][0] = ' ';
            if((grid[x-1][y-1] != ' ') && (grid[x-1][y-1] > grid[-1][-1])){
                neighbors++; cout << "F";
            }

            if((grid[x+1][y-1] != ' ') && (grid[x+1][y] < grid[HEIGHT][y]) &&
                (grid[x][y-1] > grid[x][-1])){
                    neighbors++; cout << "H";
            }

            if((grid[x-1][y+1] != ' ') && (grid[x-1][y] > grid[-1][y])
                && (grid[x][y+1] < grid[x][WIDTH])){
                    neighbors++; cout << "D";
            }

            system("pause");

            cout << neighbors;

            //Set a marker for each point according to neighbor amounts and key.
            if(grid[x][y] == '+' && neighbors < 2)
                grid[x][y] = '-';

            if(grid[x][y] == '+' && (neighbors == 2 || neighbors == 3))
                grid[x][y] = '*';

            if(grid[x][y] == '+' && neighbors > 3)
                grid[x][y] = '-';

            if(grid[x][y] == ' ' && (neighbors == 3))
                grid[x][y] = '*';
        }
    }
    for(int x=0; x<75; x++){
        for(int y=0; y<22; y++)
        {
            if(grid[x][y] == '*')
                grid[x][y] = '+';

            if(grid[x][y] == '-')
                grid[x][y] = ' ';
        }
    }
    system("pause");
    display(grid);
}

A: Here is an easy way to check if a cell's neighbors are alive. Place the following code in a function and pass in the row and column of the cell you wish to check.
int live_cell_count = 0;
for (int i = -1; i <= 1; i++)
{
    for (int j = -1; j <= 1; j++)
    {
        //disregard grid[row][col]
        if (!(i == 0 && j == 0) && inBounds(row+i,col+j)
                 && grid[row+i][col+j] == '+')
              live_cell_count++;
    }
}

Note that bool inBounds(int, int) is a function that checks to make sure you aren't going off the array. If you were working with a 40 x 30 grid, inBounds() would be this simple one-liner
return ((row >= 0 && row < 40) && (col >= 0 && col < 30));
I leave it as an exercise to the OP to apply the rules of life based on the value of live_cell_count

A: The neighbor checking is currently checking the contents when you want to be checking the index.  Also, make sure you check the index before you check the contents, or you will get array out of bounds problems.
Here's the first one fixed:
if ((x+1 < HEIGHT) && (grid[x+1][y] != ' ')) { // Swap and index instead of contents.
   neighbors++; cout << "A";
}

A: 75 is better to be replaced by HEIGHT, 22 replaced by WIDTH.
if((grid[x+1][y] != ' ') && (x+1 < HEIGHT)) {
        neighbors++; cout<<"A";
}

should be
if((x+1 < HEIGHT) && (grid[x+1][y] != ' ')) { // The range check should be done firstly
        neighbors++; cout<<"A";
}


text:
Q: How to populate values inside a new column based values from other columns in a dataframe in Pandas I  have dataframe df has shown below.
  df
DATA ELEMENT    PORT    LOCATION    P_RISK  S_RISK  W_RISK  Total_Risk
Event 1000     SGSIN                      0       0       0       0
Event 2000     MYKUL                      0       1       0       1
Event 3000                PARIS           0       0       1       1
Event 4000                LYON            1       0       0       1
Event 1000     USNYK                      0       0       0       0
Event 2000     INCOK                      0       0       1       1
Event 3000                MUMBAI          0       0       0       0
Event 4000                LAHORE          1       0       0       1
Event 2000     INCOK                      0       0       0       0
Event 3000                PARIS           0       0       0       0

Condition
*If Data Element is 1000 or 2000 and Total Risk is 1 then populate the new column comment with the With `Risk Name + PORT
*If Data Element is 3000 or 4000 and Total Risk is 1 then populate the new column comment with the With Risk Name + LOCATION
*If Total Risk is 0 then populate No Risk Indentified
Expected Output
df
    DATA ELEMENT    PORT    LOCATION    P_RISK  S_RISK  W_RISK  Total_Risk  Comment
    Event 1000     SGSIN                      0       0       0       0     No Risk Indentified
    Event 2000     MYKUL                      0       1       0       1     S_RISK  predicted at  MYKUL
    Event 3000                PARIS           0       0       1       1     W_RISK predicted at  PARIS
    Event 4000                LYON            1       0       0       1     P_RISK  predicted at  LYON
    Event 1000     USNYK                      0       0       0       0     No Risk Indentified
    Event 2000     INCOK                      0       0       1       1     W_RISK predicted at  INCOK
    Event 3000                MUMBAI          0       0       0       0     No Risk Indentified
    Event 4000                LAHORE          1       0       0       1     P_RISK  predicted at  LAHORE
    Event 2000     INCOK                      0       0       0       0     No Risk Indentified
    Event 3000                PARIS           0       0       0       0     No Risk Indentified

How can this be done?

A: I am use dot with np.where
s2=df.filter(like='_RISK')
s2=s2.dot(s2.columns)
df['new']=np.where(s2=='' ,'No Risk Indentified',s2 + ' predict at ' +df.PORT.mask(df.PORT=='',df.LOCATION))
df
Out[35]:
    DATA  ELEMENT   PORT  ... W_RISK  Total_Risk                     new
0  Event     1000  SGSIN  ...      0           0     No Risk Indentified
1  Event     2000  MYKUL  ...      0           1   S_RISKpredict atMYKUL
2  Event     3000         ...      1           1   W_RISKpredict atPARIS
3  Event     4000         ...      0           1    P_RISKpredict atLYON
4  Event     1000  USNYK  ...      0           0     No Risk Indentified
5  Event     2000  INCOK  ...      1           1   W_RISKpredict atINCOK
6  Event     3000         ...      0           0     No Risk Indentified
7  Event     4000         ...      0           1  P_RISKpredict atLAHORE
8  Event     2000  INCOK  ...      0           0     No Risk Indentified
9  Event     3000         ...      0           0     No Risk Indentified
[10 rows x 9 columns]

Method 2
s2=df.filter(like='_RISK').ne(0).stack()
s2=s2[s2].reset_index(level=1)
df['new']=(s2['level_1'] + ' predict at ' +df.PORT.mask(df.PORT=='',df.LOCATION)).fillna('No Risk Indentified')


text:
Q: Setting system variable using Node I have been working on a node script that does the installation of external dependencies and was wondering if its possible to set the PATH variable using Node.
For example, If I want to install Go using script, I can execute command brew install Go and this works but when I do export GOPATH=$PATH, this is never set.
I also tried using process.env but this also does not work. Also my assumption with process is that it must run in a sandbox. So it will not update/ set anything outside.
So the question is, can I do this? If yes, how?

A: It is not possible in any programming language. At least on Unix (BSD, MacOS, Illumos etc.) and Linux, I'm not sure about Windows.
As a security feature, Unix processes are designed such that they cannot touch the environment of their parent's process. Only the parent process can influence the environment of their children.
When you are on a command line you are running a shell program (either Bash or Korn Shell or TCSH or Fish etc.). When you execute something on the command line such as a node.js script or Google Chrome or Minecraft these programs will be the children to your shell program. On Unix and Linux these child programs inherit their parent's environment.
That is why you can export environment (global) variables and your programs can access them. However, this relationship is one-way and it was designed that way on purpose.
You may notice that in shell scripts you can "save" commands to set environment variables in a file. For example in Bash you sometimes see people do this:
# variables.sh

export HELLO "World"

However, this will not work if you execute the script as a script:
$ bash variables.sh
$ echo $HELLO
                   <--------------------- nothing is displayed here
                                          the variable is not exported

You sometimes see people do this instead:
$ . variables.sh
$ echo $HELLO
World

And you may wonder how that works. Well.. in some shell languages the dot command imports the script instead of executing the script as a separate process. Think of it like import or require() in javascript.
Of course, Bash does not understand javascript syntax. It also does not understand C++ or Java or Ruby or PHP. It only understands Bash syntax.
So the longer answer is it is not possible in any programming language except for the language of the shell you are using (eg. if you are using Fish you need to write a script in Fish syntax or if you are using Ksh you need to write a script in Korn syntax).


text:
Q: how to make the divs at the same size how can i make all the divs at the same size
i am using django ??

                    {% for meg in objj %}

                    {% endfor %}

models:
class News(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    img = models.ImageField(upload_to='media/')

    def __str__(self):
        return self.title

enter image description here

A: The way you are doing, it is going to generate the divs of the same size only.
But then you are forgetting the
 inside the for loop.
Fixing that will work for you.
{% for meg in objj %}

{% endfor %}


text:
Q: Given a sequence $\left(\tfrac{x}{p}\right),\left(\tfrac{x+1}{p}\right),\dots,$ how hard it is to find an $x$ that fits? Let $p$ be some 1000-bit prime number.
Given a sequence $1$'s and $-1$'s
$$\left(\tfrac{x}{p}\right),\left(\tfrac{x+1}{p}\right),\dots,\left(\tfrac{x+80}{p}\right)$$ how hard it is to find an $x \in \mathbb{Z}_p$ if $p$ is prime?
Here $\left(\tfrac{x}{p}\right)$ denotes Legendre symbol, which can be defined as
$\left(\tfrac{x}{p}\right) := x^{(p-1)/2} \bmod p$.


text:
Q: PHP if statement: Zero vs 'empty' I'm creating a WordPress website using the Advanced Custom Fields plugin. I have a set of fields for tennis score results. In the template, I'm showing these fields like this:
<?php if(get_field('my_field')) : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

The problem is that some scores are zero, so they're not showing up. I understand that this is because 0 basically equals null, so the statement is false.
One solution I found and tried was this:
<?php if(get_field('my_field') !== false) : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

However, this means that empty fields now show up too, which is not desirable since there are a lot of fields that are intended to be hidden if empty.
So, my question is, is there a way to phrase an if statement that allows for zeros, while still returning false if the field is empty? Please note that some scores aren't purely numeric, with values like '6(1)'.

A: In order to check for empty strings you have to explicitly check them in your if condition.
<?php if(get_field('my_field') !== '') : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

The reason is 0, null, empty string, empty array all evaluate to (but are not exactly) false, in case of a boolean check.


text:
Q: Boostrap Validator Boas, tou a tentar fazer uma validator com o Boostrap mas não está a funcionar.
Eu quero que o input peso seja por exemplo : 70 kg.
O regex acho que está a funcionar mas quando dou submit, não aparece a div.invalid-feedback
<input class="form-control" type="text"  name ="peso" pattern="(\d*\.?\d+)\s*(lbs?|kg)" required placeholder="Peso" data-error="Isso nao é kg">

Isso não é kg

Obrigado

A: @JorgeFerreira faltou inserir a class help-block with-errors que usa o erro gerado por data-error="Isso nao é kg"

$(document).ready(function(){
  $("form").submit(function(){
  var input_peso = $('#peso').val();
  console.log(input_peso);
  return false;
    });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<form name="form" data-toggle="validator" role="form" action="#">

    Peso:
  <input id="peso" class="form-control" type="text" name="peso" pattern="^\d+(?:\.\d+)?\s*(?:kg|lbs|t)$" required placeholder="Peso" data-error="Isso nao é kg">

    <button type="submit" class="btn btn-primary">Submit</button>

</form>


text:
Q: The sequence $\{\ker(f-\lambda Id)^{k} - \ker(f-\lambda Id)^{k-1} \}_{k}$ is decreasing Given $V$ a vector space over a field $\mathbb{K}$ and a string $[d_{1} < d_{2} < \cdots < d_{k} = n]$, where $d_{i} = \dim \ker(f-\lambda Id)^{i}$.
I know that $$\{0\} \subset \ker(f-\lambda Id) \subset \cdots \subset \ker(f-\lambda Id)^{k} = V.$$
I would like to prove that the sequence $$\{dim \ker(f-\lambda Id)^{k} - dim \ker(f-\lambda Id)^{k-1} \}_{k}$$ Is decreasing.
Any help or solution would be appreciated.


text:
Q: How do I make images clickable so as to enlarge them using lightbox? I use markdown editor and insert an image by Insert Media, then I have, for instance,

But the images are not clickable. To enlarge them, I have to right-click the image and click Open Images in New Tab.
I installed lightbox plugins. So, if the images are clickable, users can click to enlarge images in a pop-up window. How do I achieve this?

I checked with my previous posts using Windows Live Writer. There are clickable. Here is an example, HTML source code.

A: When using the Insert Media button, you need to set the Link To in the attachment details to the media file.
This is visible in the following picture in the bottom right:


text:
Q: Java: Define int if another int doesn't exist yet I want to set a int old the value of int new, but in the first while loop int old has to be defined before int new, which means that int new doesn't exist yet. So int old can not get the value of int new.
How can I extract this case and define that int old = 0 (for example) in this first loop. I don't find a suitable function, because every if-loop with int new throws an exception because int new doesn't exist. How can I handle this?
    while(true) {
        try {
            int iold = inew;
            int inew = input.read();

            if (inew!=-1 && iold != -1) {
              text = tf.getText();
              tf.setText(text+(char)inew);
            }
            if (inew != -1 && iold = -1) {
             text = tf.getText();
             tf.setText(""+(char)inew);
            }
            Thread.sleep(100);
         } catch(Exception x) {
              x.printStackTrace();
         }
         repaint();
    }

A: Declare the int old as your member variable or before while loop.
int old = 0;
while(condition){
   // your codes
}

A: Simply do
    int inew = 0; //Or any default value
    while(true){
      try{

        int iold=inew;

        inew=input.read();

        if (inew!=-1 && iold!=-1)
        {
          text=tf.getText();
          tf.setText(text+(char)inew);
        }
        if (inew!=-1 && iold=-1)
        {
          text=tf.getText();
          tf.setText(""+(char)inew);
        }

        Thread.sleep(100);
      }
      catch(Exception x){
          x.printStackTrace();
      }

      repaint();
    }

A: Just declare int inew = 0 outside while clause, like this:
int inew = 0;
while(true)
{
  try{

    int iold=inew;

    inew=input.read();

    if (inew != -1) {
        text = tf.getText();
        if(iold != -1) {
            tf.setText(text+(char)inew);
        }
        else {
            tf.setText(""+(char)inew);
        }
    }
    Thread.sleep(100);
  }
  catch(Exception x){x.printStackTrace();}
  repaint();
}

First loop, iold will get value 0. I've optimized your code, too.


text:
Q: Why can't I call this value in a hashmap via a string key? Really simple code... doesnt work and I dont know why :)
String appserver="";
HashMap hm = new HashMap();
hm.put("APPSERVER101", "node101");
hm.put("APPSERVER103", "node102");
hm.put("APPSERVER105", "node103");
hm.put("APPSERVER107", "node104");
hm.put("APPSERVER201", "node108");
hm.put("APPSERVER203", "node110");

...

appserver = rs_g.getString("APPSERVER");

...

out.println("
" + hm.get(appserver) + "	");

The result is NULL, but if I set it manually like:
out.println("
" + hm.get("APPSERVER101") + "	");

I get the right result

A: Try to use the trim with hm.get(appserver) to be sure that there are no extra spaces causing the problem. Also try to print the value of appserver variable to be sure it contains "APPSERVER101" and nothing else.

A: rs_g.getString("APPSERVER"); must not be returning the value "APPSERVER101", otherwise the  expresssions hm.get(appserver) and hm.get("APPSERVER101") would be return the same result.
All that's happening inside the get method is a comparison of the passed value to every key in the map. If there's no match between that value and any key, that's going to be because the passed value isn't the same as as any key as judged by the .equals() method (in the case of Strings)


text:
Q: Why do I get the previous pushed message from npm web-push to my chrome service-worker?
*

*I use a node server

*Installed npm package web-push

*sending a POST request with payload that's pushing data with sendNotification

*→ ☠ My problem happens here.

*Receiving the pushed message in the service worker event listener
So everything's working fine, except that I always get the previous message and the first time I get nothing.

*

*server.sends A serviceWorker.receives NOTHING

*server.sends B serviceWorker.receives A

*server.sends C serviceWorker.receives B
//                  _         _
//  _ __   ___   __| | ___   (_)___   ___  ___ _ ____   _____ _ __
// | '_ \ / _ \ / _` |/ _ \  | / __| / __|/ _ \ '__\ \ / / _ \ '__|
// | | | | (_) | (_| |  __/_ | \__ \ \__ \  __/ |   \ V /  __/ |
// |_| |_|\___/ \__,_|\___(_)/ |___/ |___/\___|_|    \_/ \___|_|
//                         |__/

WEBPUSH.sendNotification(_receiver.sub, JSON.stringify(_payload)).catch(error => {
    console.error(error.stack);
    return !error;
});

//                      _                               _
//  ___  ___ _ ____   _(_) ___ ___  __      _____  _ __| | _____ _ __
// / __|/ _ \ '__\ \ / / |/ __/ _ \ \ \ /\ / / _ \| '__| |/ / _ \ '__|
// \__ \  __/ |   \ V /| | (_|  __/  \ V  V / (_) | |  |   <  __/ |
// |___/\___|_|    \_/ |_|\___\___|   \_/\_/ \___/|_|  |_|\_\___|_|

self.addEventListener('push', e => {
    console.log('', {pushNotification:e, data:e.data.json()});
    self.toBackground({
        action: "pushNotification",
        payload: e.data.json()
    });
});


text:
Q: TypeScript Error : Unexpected token `div`. Expected jsx identifier I was building a website based on nextjs-typescript and tailwindcss
and I am encountering this weird error Expression expected.

I am also getting this in the terminal:
  Unexpected token `div`. Expected jsx identifier
  const UseCases = () => {
  7 |   return (
  8 |

    :      ^^^
  9 |       <FadeIntoView>

This is my code
import dataUseCases from "../../data/cases.data"
import FadeIntoView from "../../utils/gsap/fadeIntoView"

import Cases from "./useCases"

const UseCases = () => {
  return (

      <FadeIntoView>

Case

          {dataUseCases.map((case, index) => (<Cases key={case.title + "-" + index} index={index + 1}  />))}

      </FadeIntoView>

  )
}

export default UseCases

and the file is named index.tsx and is located inside src/components/useCase
Tsconfig:
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

I tried a few suggestions from
swc#issue-2237
stack-overflow
But none of them seem to work here

A: case is a reserved keyword in javascript change that variable in your map to something else

A:
break  byte    case    catch
char    class*  const   continue
debugger    default delete  do
double  else    enum*   eval
export* extends*    false   final
finally float   for function
goto    if  implements  import*
in  instanceof  int interface
let*    long    native  new
null    package private protected
public  return  short   static
super*  switch  synchronized    this
throw   throws  transient   true
try typeof  var void abstract   arguments   await*  boolean
volatile    while   with    yield

all these keywords are reserved in javaScript you cannot use them as variables, labels, or function names


text:
Q: Charts.js renders axes, but not the dataset I'm trying to use Charts.js on an AWS Lambda function to create a chart image (png).
However, for some reason it plots the axes, but no data.
this is my code:
export const plotData = (values: number[]): Buffer | null => {
  const canvas = createCanvas(800, 600);
  let ctx: ChartItem = canvas as unknown as ChartItem;

  const plugin: Plugin = {
    id: "customCanvasBackgroundColor",
    beforeDraw: (chart: any, _args: any, options: any) => {
      const { ctx: context } = chart;
      context.save();
      context.globalCompositeOperation = "destination-over";
      context.fillStyle = options.color || "#99ffff";
      context.fillRect(0, 0, chart.width, chart.height);
      context.restore();
    },
  };

  const chart = new Chart(ctx, {
    type: "line",
    data: {
      datasets: [
        {
          label: "ph",
          data: values.map((y) => ({
            y,
            t: new Date(),
          })),
          borderWidth: 2,
          borderColor: "red",
          backgroundColor: "rgb(255, 0, 0, 0.5)",
        },
      ],
    },
    options: {
      responsive: false,
      animation: false,
      scales: {
        y: {
          beginAtZero: true,
        },
      },
      plugins: {
        legend: {
          position: "top",
        },
        title: {
          display: true,
          text: "TEstuibg",
        },
        customCanvasBackgroundColor: {
          color: "rgba(255,255,255, 1)",
        },
      },
    },
    plugins: [plugin],
  });

  // chart.draw();
  chart.update();

  return canvas.toBuffer("image/png");
};

And this is what it is rendering when I call plotData([100, 200, 300, 400, 500, 1600]):

I am already disabling animations and responsiveness. Is there something else I need to do?

A: I would create the image on the onComplete event, than everything should be visible, atleast this works in browsers.

from the documentation: "...The animation configuration provides callbacks which are useful for synchronizing an external draw to the chart animation....", but works surely for your image creating process. link to documentation

...
options: {
  animation:{
        duration: 0, // "no" animation
        onComplete: () => {
            ...
            // create image
            ...
        }
    }
}
...

Ofcourse: in this case your function plotData  would have to be async or pass a callback function for when the event onComplete fires.


text:
Q: Pixelart gets fuzzy using UIImageView I have an 16 * 16 pixel art image which i want to use in my  iOS app.
but when i select the image at my UIImageView the picture gets really blurry.
I think it has something to do with the way the image gets filtered, but i couldn't find any filtering options.
I already tried changing a lot of options, but just can't get it to work
How do i fix this?
( i am using iOS 7, Xcode 5.1.1, OS X 10.9 Mavericks and a iPhone 4S  (i don't think this info is needed, but just in case))
EDIT:
Here's an image:
http://i.stack.imgur.com/d3Yms.png
As you can see, the image on the right in photoshop looks great, but the image on the left in Xcode looks fuzzy

A: The problem is that scaling procedure interpolates pixels position and size while scaling it. If you want to use sharp pixelart-images you must prepare all resources and never rely on scaling by setting
_imageView.contentMode = UIVIewContentModeCenter;

OR
set scaling filters to value kCAFilterNearest
[_imageView.layer setMagnificationFilter:kCAFilterNearest];
[_imageView.layer setMinificationFilter:kCAFilterNearest];

if you like the second way, i'd recommend to set all ImageView frames with EVEN (2,4,6,8 etc) sizes and origins to avoid pixel misalign


text:
Q: didEnterRegion order of execution? So I asked a question about my code relating to didEnterRegion but perhaps I was being too specific, therefore could I ask someone to clarify the order of method calls in more generic terms for region monitoring, specifically when the app is in the background.
My understanding is:

*

*App registers region calling startMonitoringForRegion:

*User taps home button or locks device, app goes into the background.

*The devices location is monitored at the OS level, separate from  the app, the app is never launched by the OS to confirm the users current location.

*When the user crosses the boundary into the region, the OS looks for which app originally registered the region and launches that app.

*The app is launched in the background, (didFinishLaunchingWithOptions: is not called however), the CLLocationManager delegate is setup and it's didEnterRegion delegate method is called.

*In my case, this sets up a UILocalNotification which is presented immediately (banner displays on home screen if for example another app is in use, or on the lock screen if phone is dormant).

*The user actions the notification by swiping in the lock screen or tapping the banner, the app is launched and appWillEnterForeground/appWillBecomeActive is called AND the app delegate didRecieveLocalNotification: method is called if implemented.

This is my understanding, which is probably wrong as my UILocalNotification is never fired if the app is in the background. Could someone clarify which bits are wrong?

A: After further testing I've come to the conclusion that there's nothing wrong with my code and it's actually appears to be Apples implementation of region monitoring being poor. It seems to be only slightly better than the monitoring of significant location changes, and still relies on changes in wifi networks and cell towers. Even within a major UK city I found didEnterRegion wasn't trigged until you were up to 1000 meters into a mile wide region, if triggered at all. This explains why it works every time when testing though Xcode and forcing the location.
The only work around I've come up with so far is to calculate the distance remaining each time the users location is updated and to manually call the didEnterRegion delegate method when this is less than the regions radius/2. This is supposed to be done automatically by Apples code when you're more than 10m into the boundary, however I found that to be unreliable for the reasons above.
However given you can't get regular updates using the better accuracy of GPS whilst the app is in the background and this is only a problem when the app is in the background, it's not really a solution at all.  :o(


text:
Q: mongoose aggregate: output count of field value and total results I want the output to be something like : [{downVotes : 2}, {upvotes :3}, {totalReviews : 7}] the total reviews are the reviews matched by $match. Some users don't vote.
an example of one of the reviews:
 { _id: 584b5d633ac18451ddc4b2c6,
   companyName: 'napacabs.com',
   shortId: 'B1MrpR_Qe',
   updatedAt: Sat Dec 10 2016 16:18:29 GMT-0500 (Eastern Standard Time),
   anonId: 584b5d39f371067019df86e9,
   myUpdate: Fri Dec 09 2016 20:43:50 GMT-0500 (Eastern Standard Time),
   statements: [ [Object], [Object] ],
   vote: 'down',
   reviewText: 'Another B1MrpR_Qe',
   __v: 0,
   createdAt: Fri Dec 09 2016 20:41:50 GMT-0500 (Eastern Standard Time),
   usefulness: { useful: [], useless: [] },
   usefulnessResults: { useful: 0, useless: 0 },
   createdString: 'Fr, December 9th 16, 8:41:50 pm',
   momented: '20 hours ago',
   updatedString: 'Sa, December 10th 16, 4:18:20 pm' }

There might be 7 reviews. The vote field value changes depending on how the users vote.
I was able to group by votes but I did not know how to get the total reviews without depending on the vote value.
Also I would like to do some other aggregation on the statements field like get the value from object and aggregate. So I need to understand how to go back and do other aggregation steps and not just funnel it all down to fewer elements.
var sendDataToReviewForPage = function(nameOfCompany){
    return Review.aggregate([
            {$match : {companyName : nameOfCompany}},
            // {$unwind : "$createdString"},
            {$group : {_id : "$vote", type : {$push : "$vote"}}},
            {$project : {size : { $size : "$type" }}}
    ]);
};

I know the above code doesn't produce the results I wanted but I got a separation of the vote type I got something like [ { _id: 'down', size: 1 }, { _id: 'up', size: 1 } ] please help me get to final desired format.

A: Here is the solution for your question with some dummy data.
Data
{
    "votes" : "down",
    "company" : "abc",
    "review" : 1
}
{
    "votes" : "down",
    "review" : 2,
    "company" : "xyz"
}
{
    "votes" : "up",
    "review" : 3,
    "company" : "xyz"
}
{
    "votes" : "up",
    "review" : 5,
    "company" : "abc"
}
{
    "votes" : "up",
    "review" : 5,
    "company" : "abc"
}
{
    "votes" : "up",
    "review" : 5,
    "company" : "abc"
}
{
    "votes" : "down",
    "review" : 5,
    "company" : "xyz"
}
Below is my query for returns your expected output.
db.getCollection('votes').aggregate([
    {$match : { "company" : "abc"}},
    {
        $group :{
            _id : "null",
            "downVotes" : { $sum : { $cond : [ { $eq : ["$votes" , "down"] }, 1 ,0 ] } },
            "upVotes" : { $sum : { $cond : [ { $eq : ["$votes" , "up"] }, 1 ,0 ] } },
            "totalReviews":{ $sum : "$review"}
        }
    }
])

The output of above query is :
{
    "_id" : "null",
    "downVotes" : 1,
    "upVotes" : 3,
    "totalReviews" : 16
}


text:
Q: Trying to add a column to SQL Server table I am getting incorrect syntax errors with the following statement (SQL Server 2017)
USE ToDo
GO

ALTER TABLE tasks ADD COLUMN completed TINYINT(1);

Started executing query at Line 1
Commands completed successfully.
20:31:38Started executing query at Line 3

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'COLUMN'.

A very similar syntax was used to remove a column that worked fine.

A: This code would run in MySQL - but not on SQL Server. Consider:
alter table tasks add completed tinyint;

Rationale:

*

*alter table does not support column in SQL Server; just remove that keyword

*the tinyint datatype does not take a length


text:
Q: What XML Transformation is suitable here I am trying to narrow down on a suitable XML Transformation language/utility which would allow me to do some pretty heavy XML transformation ( file sizes i expect to be around 100 kb) . The source and target files consist of nearly 280 unique elements with up to 3 levels of object nesting representing a customer technical order. I have two to three streams of XML docs which i need to transform into a single XML document ( eg: 2 XML docs, one from an Order Management and one from a Resource Management system to be processed to generate a single target doc).
The transformations involve evaluation of nodes in the source streams and either assigning them to the target schema nodes or doing some transformation such as setting variable values for the target schema. The number of nodes in the source and target schema are not necessarily equal. I would like ideally the rules to be configurable rather than embedded in code (not sure if this is feasible) at the same time processing-light.
I have mix of  evaluative and conditional elements defined as Business rules  ( using a mix of scripting and XPath it would crudely look like this "If(/OrderData/Servicetype != /ResourceData/ServiceType) then /Target/ServiceType = /OrderData/ServiceType)"
I am still evaluating if a single pass parser will suffice the entire transformation. My main aim is to:

*

*Have a configurable file which can define parsing rules

*An engine which can read this file and parse as per the rule. Mostly to be configurable i believe it would need to be more of an interpreter based one since i believe the configurability requirement will automatically push compilation out the window.

*Configurable file could be definable in some defined syntax for evaluations, functions etc.

Any addition to the XML schema will obviously need an addition to the ruleset.
Ideally I just want to have to update the ruleset and the inputXML Schemas to have the Engine adapt to new parsing rules/input.
I want to be able to manipulate the entire schema in one pass.
Trying to parse the entire Target schema resulted in Java class size error being thrown which means I need to split the schema to parse it.
Further due to this XSLT I presume will only result in large processing times owing to the size. This I presume only leaves me an option of XML String parsing. (I wish there was awk for XML :) ).
I would be glad if someone can guide me to any resource which can help. Is there an equivalent JAVA utility ?
I know this sounds like a Christmas Wishlist written to Santa :) but in case someone has already done something like the above please give me a shout or a suggestion. I can share the XML schemas and a sample of the exact translation rules being defined if required.

A: There are thousands upon thousands of people using XSLT to do exactly what you describe. Look no further. It can even be reasonably described as "awk for XML". You'll get a lot of productivity benefits by using XSLT 2.0 instead of version 1.0, which is still more widely available than 2.0. For file sizes of a few hundred Kb you don't need to worry about streaming.