text:
Q: Lucene changing from RAMDirectory to FSDIrectory - Content-Field missing I'm just a lucene starter and and i got stuck on a problem during a change from a RAMDIrectory to a FSDirectory:
First my code:
    private static IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_43,
            new StandardAnalyzer(Version.LUCENE_43));
    Directory DIR = FSDirectory.open(new File(INDEXLOC)); //INDEXLOC = "path/to/dir/"
    // RAMDirectory DIR = new RAMDirectory();

    // Index some made up content
    IndexWriter writer =
            new IndexWriter(DIR, iwc);

    // Store both position and offset information
    FieldType type = new FieldType();
    type.setStored(true);
    type.setStoreTermVectors(true);
    type.setStoreTermVectorOffsets(true);
    type.setStoreTermVectorPositions(true);
    type.setIndexed(true);
    type.setTokenized(true);

    IDocumentParser p = DocumentParserFactory.getParser(f);
    ArrayList<ParserDocument> DOCS = p.getParsedDocuments();

    for (int i = 0; i < DOCS.size(); i++) {
        Document doc = new Document();
        Field id = new StringField("id", "doc_" + i, Field.Store.YES);
        doc.add(id);
        Field text = new Field("content", DOCS.get(i).getContent(), type);
        doc.add(text);
        writer.addDocument(doc);
    }
    writer.close();
    // Get a searcher
    IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(DIR));
    // Do a search using SpanQuery
    SpanTermQuery fleeceQ = new SpanTermQuery(new Term("content", "zahl"));
    TopDocs results = searcher.search(fleeceQ, 10);
    for (int i = 0; i < results.scoreDocs.length; i++) {
        ScoreDoc scoreDoc = results.scoreDocs[i];
        System.out.println("Score Doc: " + scoreDoc);
    }
    IndexReader reader = searcher.getIndexReader();

    AtomicReader wrapper = SlowCompositeReaderWrapper.wrap(reader);
    Map<Term, TermContext> termContexts = new HashMap<Term, TermContext>();
    Spans spans = fleeceQ.getSpans(wrapper.getContext(), new Bits.MatchAllBits(reader.numDocs()), termContexts);
    int window = 2;// get the words within two of the match
    while (spans.next() == true) {
        Map<Integer, String> entries = new TreeMap<Integer, String>();
        System.out.println("Doc: " + spans.doc() + " Start: " + spans.start() + " End: " + spans.end());
        int start = spans.start() - window;
        int end = spans.end() + window;
        Terms content = reader.getTermVector(spans.doc(), "content");
        TermsEnum termsEnum = content.iterator(null);
        BytesRef term;
        while ((term = termsEnum.next()) != null) {
            // could store the BytesRef here, but String is easier for this
            // example
            String s = new String(term.bytes, term.offset, term.length);
            DocsAndPositionsEnum positionsEnum = termsEnum.docsAndPositions(null, null);
            if (positionsEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
                int i = 0;
                int position = -1;
                while (i < positionsEnum.freq() && (position = positionsEnum.nextPosition()) != -1) {
                    if (position >= start && position <= end) {
                        entries.put(position, s);
                    }
                    i++;
                }
            }
        }
        System.out.println("Entries:" + entries);
    }

it's just some code i found on a great website and i wanted to try .... everything works great using the RAMDirectory. But if i change it to my FSDirectory it's giving me a NullpointerException like :

Exception in thread "main" java.lang.NullPointerException     at
  com.org.test.TextDB.myMethod(TextDB.java:184)     at
  com.org.test.Main.main(Main.java:31)

The statement Terms content = reader.getTermVector(spans.doc(), "content"); seems to get no result and returns null. so the exception. but why? in my ramDIR everything works fine.
It seems that the indexWriter or the Reader (really don't know) didn't write or didn't read the field "content" properly from the index. But i really don't know why its 'written' in a RAMDirectory and not written in a FSDIrectory?!
Anybody an idea to that?

A: Gave this a test a quick test run, and I can't reproduce your issue.
I think the most likely issue here is old documents in your index.  The way this is written, every time it is run, more documents will be added to your index.  Old documents from previous runs won't get deleted, or overwritten, they'll just stick around.  So, if you have run this before on the same directory, say perhaps, before you added the line type.setStoreTermVectors(true);, some of your results may be these old documents with term vectors, and reader.getTermVector(...) will return null, if the document does not store term vectors.
Of course, anything indexed in a RAMDirectory will be dropped as soon as execution finishes, so the issue would not occur in that case.
Simple solution would be to try deleting the index directory and run it again.
If you want to start with a fresh index when you run this, you can set that up through the IndexWriterConfig:
private static IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_43,
        new StandardAnalyzer(Version.LUCENE_43));
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

That's a guess, of course, but seems consistent with the behavior you've described.


text:
Q: Reverse-Engineering Memory Load Techniques? I am attempting to reverse engineer a game (with permission). I am using IDA Pro. The functions are sub_xxxxx, meaning that they are protected functions.
However, the strings that would be the names for the functions, when looking at the only cross-reference, are shown in the following manner:
__data:xxxxxxxx                 DCD aEcdh_compute_k     ; "ECDH_compute_key"
__data:xxxxxxxx                 DCB   0
__data:xxxxxxxx                 DCB 0x40
__data:xxxxxxxx                 DCB   12
__data:xxxxxxxx                 DCB 0x3B

Some of the numbers, including the DCBs are changed for the sake of safety (OCD)
I had attempted to use the 40 12 3B to use as an offset. However, the offset brings me to the middle of a random loc_xxxxx, along with the others.
My question to you is, how would I go about finding where the actual function is? Is the offset from the top of the .data segment? Or is it from the actual declaring string itself?
I do not expect or require a full answer; obviously this may not have been encountered in the past, and I may not have given enough information needed. (If you need more information, please ask, thanks). Basically, I am asking, "What should I try next?", trying to find the most likely answer. Thank you.

A: You're ignoring the processors endianity, which is usually little endian.
Hhitting D two times (once to convert data representation from single byte to word and another to convert it from word to dword) will convert the data to a dword for you. Alternatively, you could also hit O to directly convert data representation to an offset (which is of size dword on most architectures)
This is most likely to show you offset to address 0x003b1240, which is probably the address you were looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Better to multiply matrices in javascript or a shader? I've been looking at several webgl examples.  Consider MDN's tutorial.  Their vertex shader multiplies the vertex by a perspective matrix and a world position matrix:

gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);

But the uMVMatrix is itself the product of several transforms (translation, rotation, etc) calculated in javascript with the help of some matrix libraries.
It seems like it would be faster to calculate their products directly in the shader; surely that's faster than doing it in .js.  Is there some reason why they choose this approach?
Now, I guess you can stack an arbitrary number of transforms in an arbitrary order this way, which is more flexible.  But say that flexibility isn't needed, is there any reason to avoid doing transforms directly in the shaders?   Something like

gl_Position = uPMatrix * uRotationMatrix * uScaleMatrix * uTranslationMatrix * vec4(aVertexPosition, 1.0);

e: To add some context, in my particular case I'll only be rendering 2D rectangular entities (mostly sprites), so the number of vertices will always just be 4.
Given the overhead of bringing in a library to do fast .js matrix multiplication, seems like pushing these calculations into the shader is definitely the way to go for my personal case.
(Plus, even if it were slower in the balance than doing it in javascript, shunting the calculations into the GPU is probably worth something in and of itself!)

A: it depends ....
If you do it in the shader it's done for either every vertex (vertex shader) or every pixel (fragment shader). Even a GPU does not have infinite speed so let's say you are drawing 1million vertices. It's likely 1 set of matrix math calculations in JavaScript vs 1 million matrix calculations in on the GPU, the JavaScript will win.
Of course your milage may very. Every GPU is different. Some GPUs are faster than others. Some drivers do vertex calculations on the CPU. Some CPUs are faster than others.
You can test, unfortunately since you are writing for the web you have no idea what browser the user is running, nor what CPU speed or GPU or driver etc. So, it really depends.
On top of that, passing matrices to the shader is also a non-free operation. In other words it's faster to call gl.uniformMatrix4fv once than the 4 times you show in your example. If you were drawing 3000 objects whether 12000 calls to gl.uniformMatrix4fv (4 matrices each) is significantly slower than 3000 calls (1 matrix each) is something you'd have to test.
Further, the browsers teams are working on making math through JavaScript for matrices faster and trying to get it closer to C/C++.
I guess that means there is no right answer except to test and those results will be different for every platform/browser/gpu/drivers/cpu.

A: I think that JayC and gman got the point.
I would like to try to explain it too.
Fact 1:
Javascript on CPU and shader on GPU are two different things and you have to work with them with this on your mind. We have two kinds of shader in WebGL. Vertex shader and fragment shader. Vertex does set of calculations on each vertex and fragment does some set of calculation for every pixel. Shader calculations are usually much more faster then javascript.
Fact 2:
Each shader obtains few variables from javascript and it will use them to recalculate vertex/pixel parameters. Number of these variables is limited and each shader loop obtain same variables.
Fact 3:
Shader code is much more sensitive then javascript one. Cause javascript is executed once, but shader is always a loop. So if you multiplicate two numbers/matrices 4x4, javascript performance will be almoast same and you will not notice anything. But shader will do it in every loop, so one line can drop performance from ultra high to ultra low. This is what gman says.
So now what is possible to do? (Im not entirely sure that this is possible with webgl shaders, but I think it might be. ) Imagine that you have only few verticies. Like 3, 5 or 20, or even more, it doesnt really matter. And you want to make 100000 matrices multiplications for each vertex. So in fact you can first multiplicate all 100000 things together and then use that result to do just one multiplication with each vertex and you will get a same result as if you multiplicate each vertex 100000 times.
How will you do that. You will pick these 100000 matrices and assume that they are vertices. Then you will write a shader, that will multiplicate it and you will somehow obtain a result. So the multiplication will be pretty fast. And now you will write a shader, that will use a result and will work with final vertices.
But I have to say two things. Im not sure if one shader loop can obtain anything from another loop in webgl. One loop can work only with one vertex and it doesnt see other vertices, but I think you can use attribute variable to share it. We have only 2 kinds of shaders. Second is, that this task doesnt require expert mind, but genius one.
What about performance? Imagine that you dont want to do 100000 multiplications. You want less, like 2, 3 or 20. Then if you use a shader to do that work, you will have to use pipeline to send data to GPU and then back to CPU, wich can be slower then doing calculations in javascript.
At the end... so even if shader is used for graphic calculations, it is possible to use it in different way. But your approach must be different, conscious and resourceful, which is harder then simple javascript multiplication. Hope it helps everyone.


text:
Q: What can and cannot be implemented in the advice guideline for new users? Context: Chemistry SE is going through changing their interface shown to new users
When a new user decides to write their first question, they are greeted with this pop up,

My question, is what can be added to this guideline page? Are things like MathJax, multiple lists allowed within the advice page?


text:
Q: python splitting string without cutting words I found some similar questions, but nothing from python.
The context:
I have many pdf files (text) which have a table among other texts.
The position and size of the table varies from file to file.
I already tried different libraries but pdftotext was the best until now. tabula didn't work for example.
Solution until now:
I use pdftotext to extract all the info as a big string, find the substrings that will always delimit the table and save the table in a variable
Unfortunately, I can't write the whole content of the table, but the first two lines:
D  Staph. aureus  Ps. aeruginosa E. coli ATCC Ser.             Asp.           Cand. albicans
a  ATCC 6538,     ATCC 9027, Ps. 8739, Ent.     marcescens     brasiliensis   ATCC 10231,

since pdftotext puts a "\n" at the end of each line, I could split the table into each row
My goal here is to separate this string into substrings as columns like this:
['Staph. aureus', 'Ps. aeruginosa', 'E. coli ATCC', 'Ser.', 'Asp.', 'Cand. albicans']

and this:
['ATCC 6538,     ', 'ATCC 9027, Ps. ', '8739, Ent.     ', 'marcescens     ', 'brasiliensis   ', 'ATCC 10231,']

The second line was delimited in every 15 characters for example
I realized that the maximum length of a column is 15 characters, so i tried splitting it like this, with n = 15:
print([line[i: (i + n)] for i in range(0, len(line), n)])

but this is what I get:
['Staph. aureus  ', 'Ps. aeruginosa ', 'E. coli ATCC Se', 'r.             ', 'Asp.           ', 'Cand. albicans']

the question here is how to cut the string in substrings without cutting the words?
I already realized that if I cut on the position line[i + n], the position line[i+n-1] has to be equal to " " in order to not cut a word.

A: You can split a string into words using str.split(). If you do not provide a deliminator it will use spaces by default and return the words of a string. See the official Python documentation here.

A: The data seems to be tab delimited, but with the tabs replaced with spaces.
The only pattern I can spot is multiple spaces between column values.If this is the case your code would break if there was a double space (e.g. typo by the author).
Using the maximum column width is risky. It would break if the columns have short values (e.g. 'one', 'two').

A: Would this be of help?
str = "D  Staph. aureus  Ps. aeruginosa E. coli ATCC Ser.             Asp.
Cand. albicans"
list = []

for s in str.split():
    if "." in s:
        list.append(s)
    elif list:
        list[-1] = f"{list[-1]} {s}"

print(list)

output:
['Staph. aureus', 'Ps. aeruginosa', 'E. coli ATCC', 'Ser.', 'Asp.', 'Cand. albicans']

This splits the string at whitespace, then goes through the resulting array and starts a new entry in the list if a word contains "." and appends that index in the list with the following words until the next word with "." is encountered.
I can't see a rule that we could apply to all rows, but with these two examples we could do:
line1 = "D  Staph. aureus  Ps. aeruginosa E. coli ATCC Ser.             Asp.           Cand. albicans"
line2 = "a  ATCC 6538,     ATCC 9027, Ps. 8739, Ent.     marcescens     brasiliensis   ATCC 10231,"

for line in (line1, line2):
    if line[0] == "D":
        list = []
        for s in line.split():
            if "." in s:
                list.append(s)
            elif list:
                list[-1] = f"{list[-1]} {s}"
        print(list)

    if line[0] == "a":
        count = 0
        list = []
        for s in line2[3:]:
            if count % 15 == 0 or count == 0:
                list.append(s)
                if len(list) > 1: list[-2] = list[-2].rstrip()
            else:
                list[-1] = f"{list[-1]}{s}"
            count += 1
        print(list)

output:
['Staph. aureus', 'Ps. aeruginosa', 'E. coli ATCC', 'Ser.', 'Asp.', 'Cand. albicans']
['ATCC 6538,', 'ATCC 9027, Ps.', '8739, Ent.', 'marcescens', 'brasiliensis', 'ATCC 10231,']

Looks pretty horrible, but hopefully gives some ideas. :)


text:
Q: Not able to fetch Get params in production I have developed API's with Zf2 and DynamoDB, I am able to get values from GET params in my local machine but unable to get values from GET params when I uploaded the API's in production
.
FYI: POST method is working properly in production.
Below is the controller get function.
public function get($id)
{
     $abcModel = new ABCModel();
     error_log("tournamentId:".$this->params()->fromQuery('tournamentId') );
     $query = $this->getRequest()->getQuery();
     error_log("tournamentId1:".$query['tournamentId']);
     error_log("tournamentId2:".$this->getEvent()->getRouteMatch()->getParam('tournamentId'));
     error_log("tournamentId3:".$this->params('tournamentId'));
     error_log("tournamentId4:".$this->params()->fromRoute('tournamentId'));
 }

I have tried all the answers of this question ZF2: Get url parameters in controller.
Can any one know what could be the reason for this?
Any light on the path would be helpful.

A: To use query string in the production environment, you have to use some alternate approach.
You can add parameter along with route to hold the query string value. But the query string needs to be passed using "/" mark between the route and query string instead of using "?" mark.
/route-name/key=value&key=value1

and the routing configuration need to be
'router' => array(
'routes' => array(
    '<route-name>' => array(
        'type' => 'segment',
        'options' => array(
            'route' => '<route-name>[/:action][/:queryPara][/]',
            'constraints' => array(
                'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                'queryPara' => '[a-zA-Z][a-zA-Z0-9_-&=]*',
            ),
            'defaults' => array(
                'controller' => 'Application\Controller\Index',
                'action' => 'index',
            )
        ),
    ),
)),

You can create a function that will extract the query string and returns the array containing key=>value pairs of query string.
And in controller you have to call the function by passing the query string which will be stored in "/queryPara" part after the route name using the following statement you will get the string
$this->params('queryPara')

Hope it helps
Thanks


text:
Q: (discord.js) How can i make a category then add a new channel too that category What im trying to do is have discord.js make a category then after that make a channel then move that channel into the category if there is any possible way.
My Code Now:
    if(command === 'spamcategory'){
      let amount = args.slice(0).join(" ")
      let name = args.splice(1,Infinity).join(" ")
for (var i = 0; i < 200; i++) {

      message.guild.channels.create(name, { type: "GUILD_CATEGORY" });

}

    }

A: message.guild.channels.create(name, { type: "GUILD_CATEGORY" })
    .then(async (category) => {
        await category.createChannel('channelName');
    });


text:
Q: Return Vertices In Undirected Graph I am trying to come up with a greedy algorithm in Python that returns the vertices in an undirected graph given a certain starting vertex.  I understand that DFS determines if a cycle exists, but I am trying to actually return the vertices that form the cycle.  I am using an adjacency matrix to represent the following graph:
adjacencyMatrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]

pictorially this is an undirected graph comprised of a single cycle.
My current thought process is to set my starting index to the first 1 I come across (In this case adjacencyMatrix[0][1]).  Then I would look at the rest of the row to see if another 1 was there, because that means my current vertex is connected to that index.  However, I am not entirely sure if (a) this is the right approach and (b) how to "move" to the next vertex.  For example, how would I navigate my nested for loop to move from the adjacencyMatrix[0][1] vertex to the adjacencyMatrix[0][2] vertex? Would I just swap the row and column indices?
EDIT
This solution I came up with seems to work for the few graphs I tried it on:
def findCycle(matrix):
    visited = list()
    cycleNotFound = True
    row = 0
    col = 0
    startVertex = (0, 0)

    while cycleNotFound:

        # Only add a vertex if it has not already been visited
        if (matrix[row][col] == 1) and ((row, col) not in visited):
            # Set the startVertex when the first node is found
            if len(visited) == 0:
                startVertex = (row, col)

            # Add the current vertex and its counter part
            visited.append((row, col))
            visited.append((col, row))

            # If row and col are equal, infite loop will get created
            if row != col:
                row = col
                col = 0
            else:
                row += 1

        # If back at starting point, break look
        elif ((row, col) == startVertex) and (len(visited) > 1):
            cycleNotFound = False
            visited.append(startVertex)

        # Else, continue to look for unvisted neighbors
        else:
            col += 1

    return visited

if __name__ == "__main__":
    matrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
    cycle = findCycle(matrix)
    index = 0
    # Print the vertices.  Only print even vertices to avoid duplicates.
    while (index < len(cycle)):
        print cycle[index]
        index += 2

it is not the most elegant solution and I'm sure there is some major refactoring that needs to be done.

A: You may try this:
def findCycle(node):
    cycle = stack()
    if( DFS(node, cycle) ):
        return cycle
    return None

def DFS(node, cycle):
    cycle.append(node)
    mark node as visited
    foreach node.neighbors as neighbor:
        if neighbor already visited:
            return true
        else:
            if( DFS(neighbor, cycle) ) return true
    cycle.remove(node)
    return false


text:
Q: How to disable a function in Mobile with Jquery My site has a fixed menu at the top, I used the sticky plugin however I want to disable this function in mobile.
Is it possible to hide or disable the function with Jquery? To da to do only with the javascript
This is my html code

                            <select id="localizacao" multiple class="dropdown-select">
                                <option value="" disabled selected>Finalidade</option>
                                <option value="1">Venda</option>
                                <option value="2">Aluguel</option>
                                <option value="3">Aluguel Temporada</option>
                            </select>

                            <select id="localizacao" multiple class="dropdown-select">
                                <option value="" disabled selected>Localização</option>
                                <option value="1">Capão da Canoa</option>
                                <option value="2">Torres</option>
                                <option value="3">Tramandaí</option>
                            </select>

                            <select id="bairro" multiple class="dropdown-select">
                                <option value="" disabled selected>Bairro</option>
                                <option value="1">Centro</option>
                                <option value="2">Zona nova</option>
                                <option value="3">Guarani</option>
                            </select>

                            <select multiple class="dropdown-select">
                                <option value="" disabled selected>Dormitórios</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4 ou +</option>
                            </select>

                            <select multiple class="dropdown-select">
                                <option value="" disabled selected>Dormitórios</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4 ou +</option>
                            </select>

                            <select multiple class="dropdown-select">
                                <option value="" disabled selected>Dormitórios</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4 ou +</option>
                            </select>

And this is my Jquery
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  $("#fixed-search").sticky();
}

$("#fixed-search").sticky({topSpacing:10});

Example
In this image you can see the fixed menu above the other items
I solved the issue with
 if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

}else{
  $("#fixed-search").sticky({topSpacing:10});

}

A: Use BOM object to find the with of device based on the device with apply what changes you want to implement
Write below code in js
if(window.innerWidth < 767) {
   $("#fixed-search").sticky();
} else {
   $("#fixed-search").sticky({topSpacing:10});
}

A: I wouldn't use the user agent. You can use Media Queries.
https://www.w3schools.com/howto/howto_js_media_queries.asp


text:
Q: Replacing CRLF in PNG file I am trying to replace CRLF with LF (see reason @ Read binary stdout data from adb shell?)
A brief summary of the above referenced thread is that basically when piping a screenshot from an Android device via the Android debug bridge, it looks like the line feeds line endings in the data stream are being replaced with carriage return line feeds, therefore I am receiving a corrupted file at the other end of the pipe. What has worked for others is undoing the replacement via code, as below, but it doesn't seem to be working from me.
My code is still spitting a corrupted file... any ideas why?
++ I know the code isn't as clean and efficient as it can be, will fix up after so please hold the comments related to my coding skill, or lack thereof.
Thanks
        static void Main(string[] args)
        {
            // adb shell screencap -p > <path>
            string path = @"<filepath>\screen.png";

            var fs = new FileStream(path, FileMode.Open);
            var fsw = new FileStream(path.Replace(".png", "_fixed.png"), FileMode.Create);

            var buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();

            var switched = Repair(buffer);
            fsw.Write(switched, 0, switched.Length);
            fsw.Flush();
            fsw.Close();

            Console.WriteLine(buffer.Length);
            Console.WriteLine(switched.Length);

            Console.Read();
        }

        static byte[] Repair(byte[] enc)
        {
            var bstr = new MemoryStream();
            for (int i = 0; i < enc.Length; i++)
            {
                if (enc.Length > i + 1 && enc[i] == 0x0d && enc[i + 1] == 0x0a)
                {
                    bstr.WriteByte(0x0a);
                    i++;
                }
                else bstr.WriteByte(enc[i]);
            }

            bstr.Flush();
            bstr.Close();

            return bstr.ToArray();
        }


text:
Q: Main Header (H1) Pulling from Page Title The H1 Header is pulling from the Page title. I want to be able to customize the header and not have it pull.
Can anyone assist?
<title>
<?php if (is_home () ) { bloginfo('name'); }
elseif (is_category() ) { echo strip_tags(category_description()); }
elseif (is_single() ) { single_post_title().'|'.bloginfo('name'); }
elseif (is_page() ) { single_post_title().'|'.bloginfo('name'); }
else { wp_title('',true); } ?>
</title>


text:
Q: Postgresql recursive function I have the following recursive function in PostgreSQL. but I wonder how it works

*

*the sequence of execution (it goes deep hierarchy by each root node first or list all root node first then go to next level.)

*how it breaks from this function.

Can anyone help me explain this?
CREATE OR REPLACE FUNCTION build_hierarchey(location_id int) RETURNS SETOF jsonb
AS $BODY$
    BEGIN
        RETURN QUERY
        SELECT
            CASE WHEN COUNT(x) > 0
                THEN ((to_jsonb(t) || jsonb_build_object('Children', jsonb_agg(f.x)))
                ELSE to_jsonb(t)
            END
        FROM "Locations" t
        LEFT JOIN build_hierarchey(t."Id") AS f(x) ON true
        WHERE t."ParentLocationId" = location_id OR (location_id IS null AND t."ParentLocationId" IS null)
        GROUP BY t."Id", t."Name";
    END;
$BODY$ LANGUAGE 'plpgsql'

this is how I use it.

select jsonb_agg(build_hierarchey) from build_hierarchey(null::int)

Result in json (hirarchey)
[
  {
    "Id": 11,
    "Name": "Zone-C",
    "Children": [
      {
        "Id": 23,
        "Name": "01-C",
        "CategoryId": null
      },
      {
        "Id": 20,
        "Name": "01-A",
        "CategoryId": null
      }
    ],
    "CategoryId": null
  },
  {
    "Id": 19,
    "Name": "Zone-K",
    "CategoryId": null
  },
  {
    "Id": 1,
    "Name": "ccc",
    "Children": [
      {
        "Id": 3,
        "Name": "01-A",
        "CategoryId": null
      },
      {
        "Id": 5,
        "Name": "01-C",
        "Children": [
          {
            "Id": 8,
            "Name": "01-C-03",
            "CategoryId": null
          },
          {
            "Id": 7,
            "Name": "01-C-02",
            "CategoryId": null
          },
          {
            "Id": 6,
            "Name": "01-C-01",
            "CategoryId": null
          }
        ],
        "CategoryId": null
      },
      {
        "Id": 4,
        "Name": "01-B",
        "CategoryId": null
      }
    ],
    "CategoryId": null
  },
  {
    "Id": 18,
    "Name": "Zone-J",
    "CategoryId": null
  },
  {
    "Id": 2,
    "Name": "Zone-B",
    "Children": [
      {
        "Id": 10,
        "Name": "02-A",
        "CategoryId": null
      },
      {
        "Id": 9,
        "Name": "01-A",
        "CategoryId": null
      }
    ],
    "CategoryId": null
  },
  {
    "Id": 16,
    "Name": "Zone-H",
    "CategoryId": null
  },
  {
    "Id": 15,
    "Name": "Zone-G",
    "CategoryId": null
  },
  {
    "Id": 14,
    "Name": "Zone-F",
    "CategoryId": null
  },
  {
    "Id": 17,
    "Name": "Zone-I",
    "CategoryId": null
  },
  {
    "Id": 22,
    "Name": "Zone-AA",
    "CategoryId": null
  }
]

Here is the "Locations" table. (self-referencing)

SELECT "Id", "Name", "ParentLocationId" FROM "Locations"

ID  Name      ParentLocationId
1   "ccc"
2   "Zone-B"
3   "01-A"      1
4   "01-B"      1
5   "01-C"      1
6   "01-C-01"   5
7   "01-C-02"   5
8   "01-C-03"   5
9   "01-A"      2
10  "02-A"      2
11  "Zone-C"
14  "Zone-F"
15  "Zone-G"

A: As with many recursive functions, we can break this down conceptually into several steps.
First, we have the base case - when given null as input, the query selects all locations with no parent:
SELECT
    ...
FROM "Locations" t
WHERE location_id IS null AND t."ParentLocationId" IS null

Next, we have the repeated case - when given an ID as input, the query selects all locations which have that ID as their parent:
SELECT
    ...
FROM "Locations" t
WHERE t."ParentLocationId" = location_id

Then we add the recursion - when returning either of the above lists, also call the function again, with each ID found:
SELECT
    ...
FROM "Locations" t
LEFT JOIN build_hierarchey(t."Id") AS f(x) ON true

The ON true clause is there because there has to be some condition, but the actual rows to join are determined by the t."Id" passed into the function. It needs to be a LEFT JOIN, because the function will sometimes generate no rows; e.g. with your sample data build_hierarchey(3) will return no rows, but we don't want that to exclude location 3 from the results of build_hierarchey(1).
Now we need to combine the results of the current query (t) with the results of the recursive function call (f):
SELECT
    CASE WHEN COUNT(x) > 0
        THEN ((to_jsonb(t) || jsonb_build_object('Children', jsonb_agg(f.x)))
        ELSE to_jsonb(t)
    END
FROM ... as t
LEFT JOIN ... as f(x)
GROUP BY t."Id", t."Name";

Again, this has to handle the case where the function returned no rows. The rest is just formatting: flattening each set of results into a JSON object and combining them in the desired structure.
Now, to your questions:

the sequence of execution (it goes deep hierarchy by each root node first or list all root node first then go to next level.)

In SQL, it's rarely useful to talk about order of execution, because a DBMS doesn't generate one row at a time and spit out the result, it tries to generate the requested data as efficiently as possible. As far as I know, the DBMS is free to choose whether all the rows at one level are loaded into memory, and the function run on each; or whether the function is run depth-first as each row is encountered.
Generally speaking, the only thing that is guaranteed is that the results will come out in the order requested by the query. In this case, there is no ORDER BY clause, so the actual order of results at each level is also completely undefined - the DBMS will pick whichever order is most convenient when running the query.

how it breaks from this function.

This function is not actually guaranteed to exit; its exit condition relies on the assumption that your data contains no cycles - that is, that it will eventually reach a node with no "children" (i.e., an ID that never appears in the ParentLocationId column).
To demonstrate a cycle, consider this data:
ID  Name      ParentLocationId
1   "A"       3
2   "B"       1
3   "C"       2

A call to build_hierarchey(1) will proceed as follows:

*

*Fetch nodes with parent 1: found ID=2

*Fetch nodes with parent 2: found ID=3

*Fetch nodes with parent 3: found ID=1

*Fetch nodes with parent 1: infinite loop
This is probably prevented elsewhere in the application, but we also have one extra protection: by calling build_hierarchey(null) we can never encounter such a cycle. We can prove this as follows:

*

*Every node has either one parent or none

*A cycle consists of following parents and reaching the same node

*For a node to form part of a cycle, it must have a parent

*Therefore the nodes with null as their parent are not part of a cycle

*If a node is in a cycle, its parent must be in that same cycle (cycle A-B-C-A can be extended to A-B-C-A-B, and so on)

*Therefore, a node in a cycle cannot have a parent whose parent is null, because that parent could not be part of the cycle

*Therefore, starting with a node whose parent is null (which is what build_hierarchey(null) does) will never reach a cycle, even if one exists in the table


text:
Q: Why, on entering a wrong type of value as input, the variable "b" is always assigned to 1? In this simple code,
#include <stdio.h>
int main(void)
{
     int a, b;
     scanf("%d %d",&a,&b);
     printf("\nThe value of a is : %d",a);
     printf("\nThe value of b is : %d",b);
}

When I enter a wrong type of value as input, the variable b is always getting assigned to 1.
I have tried to add another variable "c" and printed its value at the end of the code, but still the variable "b" is always assigned to 1.
Why?

A: If value of a scanf() argument after scanf() returns is undefined if the conversion was unsuccessful, but the most likely behaviour is that it remains unchanged.  In this case b is uninitialised so could have any value regardless of the behaviour of scanf() .
Consider:
#include <stdio.h>
int main(void)
{
    int a = -1, b = -1;
    scanf("%d %d",&a,&b);
    printf("\nThe value of a is : %d",a);
    printf("\nThe value of b is : %d",b);

    return 0 ;
}

I would expect in this case both a and b to have either the entered value or -1 if the conversion fails - even though that is not actually required.
scanf() returns the number of arguments converted and assigned.  Consider:
#include <stdio.h>
int main(void)
{
    int a = 0, b = 0;
    int convert = scanf("%d %d",&a,&b) ;
    if( convert > 0 )
    {
        printf("\nThe value of a is : %d",a);

        if( convert > 1 )
        {
            printf("\nThe value of b is : %d",b);
        }
        else
        {
            printf("\nThe value of b is undefined" );
        }
    }
    else
    {
        printf("\nThe value of a is undefined" );
    }

    return 0 ;
}

For your test input 54test hello it outputs:

45test hello

The value of a is : 45
The value of b is undefined


text:
Q: Ruby and Rails paperclip error I don't know whats wrong: When I lunch rails server, it generate error.
$ rails server
DL is deprecated, please use Fiddle
=> Booting Thin
=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
.../config/environments/development.rb
:43:in `block in <top (required)>': undefined local variable or method `paperclip' for #<...:Application:0x61ad108> (NameError)

I installed gems in gemfile:
gem 'thin'
gem 'protected_attributes'
gem 'paperclip' , '~> 4.2'

Than, I specify environments/development.rb:
paperclip.options[:image_magick_path] = "d:/Ruby21/ImageMagick"
#ENV['PATH'] = Paperclip.options[:command_path] + ";" + ENV['PATH']

A: If you haven't, run bundle install to install your new gems.

A: In your development.rb file, I believe that paperclip.options[:image_magick_path] = "d:/Ruby21/ImageMagick" should actually be Paperclip.options[:image_magick_path] = "d:/Ruby21/ImageMagick" - call 'options' on the Class, not an instance.


text:
Q: Catch a window close event from action script/flash If this is a duplicate question I am sorry, it seems basic enough but could not find a proper answer.
The only way I have found so far to capture the browser window close event from actionscript/flash is actually to capture the event in javascript, and then use a javascript/flash data passing from the javascript callback.
Something around those lines:

window.onbeforeunload = clean_up;

function clean_up()
{
var flex = document.${application} || window.${application};
flex.myFlexFunction();
}
</SCRIPT>

and the flash part:
import flash.external.ExternalInterface;
ExternalInterface.addCallback("myFlexFunction",cleanUp);

public function cleanUp():void{
  //your flash code here
}

Is this the proper way ?
Are there other alternatives ?

A: You can never catch the window close event from pure flash. That said, as far as I know, this is the proper way to handle this.


text:
Q: Javascript: Get Tomorrow start of time with specific timezone I am new to momentjs and stuck with an issue. I have to clear document from mongoDB at the start of every day. Example: data has to be cleared at 2020-07-14T00:00:00:000z. I have added TTL for the same.
This is what I have added.
    const date  = new Date();
    date.setDate(date.getDate() + 1);
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);

The problem is the pod which is running the code is in UTC time. ie; 09:00pm UTC (server pod time) -> 12.00 am Finish Time -> 02:30 am IST (My local time). Is there any way I can get the start of the day in the above mentioned format with "Europe/Helsinki" timezone, so that finish time 12.00AM in my server, document should get cleared.
Any help would be really appreciated.
Thanks in advance

A: If you want your app to be operated at a time which is in another time zone than what you have in the server, you need to offset the time by the hours which makes the difference between your server time and the local time.
For example, the EUST (Europe/Helsinki) is +3GMT. You need to add this offset to the comparison equation if you want the operation to be aligned with your local time.
const offsetEUST = 3;

const date  = new Date();
date.setDate(date.getDate() + 1);
date.setHours(0 + offsetEUST );
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);


text:
Q: Definition of spacetime in GR: what is the underlying set of the spacetime manifold? In all the references/textbooks that I have looked at, the precise definition of spacetime is never really clear. By gathering the hypothesis that we need to make, I get the following definition: $$\text{spacetime is a smooth connected and orientable Lorentzian manifold with or without boundary}.$$
But it seems that we never really specify the set on which we put the manifold structure. Is this okay? For example, let's take the Schwarzschild metric, on which manifold is this metric defined? $\mathbb{R}^4$ with the usual/trivial smooth structure?
[EDIT]
I'm familiar with the basics notions of differential and Riemannian geometry, my question is, perhaps better formulated: what is the set $M$ on wich we define a smooth atlas $A$ to make the smooth manifold $(M,A)$?

A: A manifold is a set - you don't need to put the manifold structure onto anything. Take a look at the first line of the wikipedia page for a manifold:  a manifold is defined as a topological space which satisfies certain properties (and a topological space is a set of points).
Intuitively: a manifold is a set which looks flat if you zoom in close enough on any of its points. This is where your notion of $\mathbb{R}^4$ comes in - since any spacetime in GR is a manifold, this means it looks like flat Minkowski space ($\mathbb{R}^4$) if you zoom in close enough on any of its points.
If you zoom out, the space may be curved and not resemble $\mathbb{R}^4$ at all (as is the case for Schwarzschild). The thing you use $\mathbb{R}^4$ for when describing Schwarzschild space is to describe points on the manifold with coordinates (see coordinate chart on wikipedia).
Coordinate charts always can map/describe a region $U \subseteq \mathcal{M}$ of a manifold $\mathcal{M}$, but sometimes they fail to describe the entire manifold (ie. sometimes $U \neq \mathcal{M}$ for a particular coordinate chart). Or the coordinates might have singularities at certain points on the manifold as well (as is the case in Schwarzschild space: ordinary Schwarzschild coordinates famously break down at the horizon).

A: The set is not predetermined but arises from physical/mathematical requirements of the given solution.
GR is local theory and sufficinetly small region of spacetime is assumed to be isomorphic to open region of $\mathbb{R}^4.$ Globally the set is given by "gluing" these regions together until you arive at global solution you are satisfied with. GR does not strictly speaking enforce this. However, it is reasonable to demand some properties like smoothness of the metric, maximal extension and so on. In the case of Schwarzschild spacetime, these requirements are strong enough to guarantee uniqueness.

A: Mathematical conditions such as Hausdorf or paracompactness apply to mathematical models of reality.  They are introduced to prove theorems that apply to these models. Do not confuse mathematical models of reality with reality itself. Whether the universe is everywhere Hausdorf or paracompact  is something to be decided by experiment. No amount of studying the continuum hypothesis or alternative  axiom systems for the real line can tell us anything about the space in which we live.

A: General Relativity is a mathematical framework within which we can construct Lorentzian manifold models of reality. In general, structures (e.g. the spacetime manifold) of a given model taken to represent some aspect of observable reality need not be physically real aspects of nature, whatever that might mean. Indeed, they're almost certainly not-- what are the odds that the formalism we decided was most natural to us perfectly captures the nature of reality? In practice, all we can ask of a model is that it provides a means of unequivocally (within discernible error) predicting some observations. We like (accurate) models that are broad in scope, offering a means of predicting many different types of observations, and that sit well philosophically within the larger network of other successful models, but even these cannot be presumed to present "actual" reality.
All that to say: the only crucially significant feature of a model is the collection of predictions it makes. Details of a model's structure that don't impact its predictions are ultimately of little import, especially if they also don't impact the model's philosophical interpretation. The particular set of cardinality $2^{\aleph_0}$ one chooses to think of as underlying the Lorentzian manifold of a GR model is probably one of the least impactful (both observationally and philosophically) features I can imagine, and for this reason, GR makes no such choice outright-- any one at all will do.
A comment worth making is that the set in question is essentially universally given an interpretation as the set of spacetime events, pairs of "space" and "time" instances that characterize where and when something can occur, but this is only a heuristic intuition, not a rigorous definition that nails down the set theoretic object under consideration. Since all candidate sets are bijective, such an interpretation on one of them induces the same on all others.


text:
Q: Can we find a discontinuous function such that $\int_1^x f(t)dt=e^{2x}-e^x$? I was asked to solve the following problem:

When $\int_a^x f(t)dt=e^{2x}-e^x$, find $a$.

Not written in the problem, but maybe it is rational to suppose that $f$ is an Riemann integrable function on $\mathbb{R}$ and $a$ is real.
Suppose that $f$ is a continuous function, then $\int_a^x f(t)dt$ is differentiable and its derivation is $f(x)$ by the fundamental theorem of calculus. Thus $f(x)=2e^{2x}-e^x$ and $\int_a^x f(t)dt=e^{2x}-e^x-(e^{2a}-e^a)$, so we obtain $a=0$.
However, I doubt that it is a ill-posed problem, because I have no evidence that $f$ is continuous, though $\int_a^x f(x)dx$ is differentiable for any $x$. If we can find a discontinuous function $f$ and nonzero $a$ satisfying the condition, then my doubt is correct.
Can we find such function?

A: With any reasonable sort of integral, $\int_a^a f(t)\; dt = 0$, so taking $x=a$ you want
$0 = e^{2a} - e^a = e^a (e^a-1)$.  The only real solution is $a=0$.
If you allow complex $a$, $a=2 n \pi i$ works for any integer $n$, in the sense that $\int_\Gamma (2 \exp(2z) - \exp(z))\; dz = \exp(2 x) - \exp(x)$ for any contour $\Gamma$ starting at $2n\pi$ and ending at $x$.

A: Even if you assume $f$ is Lebesgue-integrable, then $F(x) = \int_a^xf(t)\,dt$ is (locally) absolutely continuous and is thus a.e. differentiable with $F'(x) = f(x)$ a.e. So, at least $f(x) = 2e^{2x}-e^x$ a.e. and also $a = 0$.


text:
Q: Internet Explorer is not launching my selenium webdriver code
Selenium WebDriver code is:
File file = new File("D:\\Polycom_Space\\WebdriversIEDriverServer_x64_2.53.1\\IEDriverServer.exe");

System.setProperty("webdriver.ie.driver",file.getAbsolutePath());
capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability("requireWindowFocus", true);
driver = new RemoteWebDriver(host, capabilities);

**//grid node configuration is---**

cd Polycom_Space\Java Libraries Server
java -jar selenium-server-standalone-2.53.1.jar -role webDriver -hub http://localhost:4242/grid/register -port 5557 -Dwebdriver.ie.driver=D:\Polycom_Space\Webdrivers

\IEDriverServer_x64_2.53.1\IEDriverServer.exe -browser browserName="internet explorer" -maxInstances=4 -maxSession 1

Exception is:

org.testng.internal.thread.ThreadExecutionException: org.testng.internal.InvokeMethodRunnable$TestNGRuntimeException: java.lang.RuntimeException: Error forwarding the new session cannot find : Capabilities [{ensureCleanSession=true, acceptSslCerts=true, requireWindowFocus=true, browserName=IE, version=, platform=WINDOWS}]

A: The -D properties should come before the jarfile (otherwise it is treated as an argument of the application, not an option of the JVM).
From java help, the usage is
java [-options] -jar jarfile [args...]

Try executing it with
java -Dwebdriver.ie.driver=D:\Polycom_Space\Webdrivers\IEDriverServer_x64_2.53.1\IEDriverServer.exe -jar selenium-server-standalone-2.53.1.jar -role webDriver -hub http://localhost:4242/grid/register -port 5557 -browser browserName="internet explorer" -maxInstances=4 -maxSession 1

A: The problem lies in your test code.

Error forwarding the new session cannot find

is the grid's way of telling you that whatever node you requested for (based on your capability), the grid could not find in its farm of nodes.
Your test code is requesting for a browser whose name is IE, but the Grid has only one node which supports a browser named internet explorer
The line

capabilities=DesiredCapabilities.internetExplorer();

already takes care of setting the browser name properly.
So you don't need the below line (this is the line that is causing the issue) :

capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");

Please remove that line and try again.
Also its better to tweak your node capabilities via a nodeConfig JSON file rather than you trying to pass them via the command line (its easy to make mistakes when using the command line)
This document should help you get oriented with JSON node configs.


text:
Q: É impossível fazer trucate a uma tabela com foreign keys mesmo estando vazia? Considere a tabela "A" e "B".
A tabela "B" possui uma foreign keys referente a tabela "A".
A tabela "A" não possui nenhuma foreign keys.
Nenhuma das tabelas possuem registros.
Ao tentar fazer um trucate a tabela "A", o seguinte erro é retornado:

Cannot truncate a table referenced in a foreign key constraint (bd.B, CONSTRAINT FK_1E45D7B68A6FD59C FOREIGN KEY (a_id) REFERENCES bd.A (id))

Se não existe nada nas tabelas, porque ocorre o erro?

A: Apesar de não haver motivos para se querer truncar uma tabela vazia, o erro acontece porque truncate é diferente de delete. Como você está usando chave estrangeira, é provável que esteja usando InnoDB, o que torna o truncate um processo ainda mais peculiar.
Quando você escreve um TRUNCATE table1 no InnoDB, ele automaticamente tenta dar um DROP table1 e depois recria-a. Mas é impossível excluir uma tabela que é referenciada por chave estrangeira.
Se você só quer truncar a tabela para poder voltar o auto_incremento para 1, você pode
ALTER TABLE tabela1 AUTO_INCREMENT=1

Se a tabela estiver vazia, como você disse, isso funcionará perfeitamente.


text:
Q: Dereference operator gives different results than array offset operator with void* The following C++ Win32 console program assigns an array to a pointer to void, and prints the results in two different ways:
// Foo.cpp : A Win32 console application.
//
#include "stdafx.h"

typedef unsigned char elem_type;
#define ELEM_COUNT 4

int _tmain(int argc, _TCHAR* argv[])
{
    elem_type *ary = new elem_type[ELEM_COUNT];
    for (int i = 0; i < ELEM_COUNT; i++)
    {
        ary[i] = ((i + 1) * 5); // multiples of 5
    }
    void *void_ary = ary;

    for (int i = 0; i < ELEM_COUNT; i++)
    {
        printf("void_ary[%d] is %u\t", i, ((elem_type*)void_ary)[i]);
        printf("*(void_ary+%d) is %u\n", i, *((elem_type*)(void_ary))+i);
    }

    void *allocd_ary;
    return 0;
}

Here is the output:
void_ary[0] is 5        *(void_ary+0) is 5
void_ary[1] is 10       *(void_ary+1) is 6
void_ary[2] is 15       *(void_ary+2) is 7
void_ary[3] is 20       *(void_ary+3) is 8

Using square brackets prints the result that I expected.  But dereferencing pointer offsets does not, even though the array is being typecast.
Why the discrepancy?

A: Well that is because you are dereferencing the value then adding 'i' to the result. You need some more parenthesis around the pointer cast or using static_cast which is more obvious.
As in:
*(static_cast<elem_type*>(void_ary)+i)

A: printf("*(void_ary+%d) is %u\n", i, *((elem_type*)(void_ary))+i);

Here it seems that you are dereferencing the value BEFORE adding i to it. This will cause to get always the first element of the array (since you are dereferencing the same pointer 5 times) and add i to it.
Try with:
*((elem_type*)(void_ary)+i)

A: Your expression don't mean the same thing. What you write as
*(void_ary+i)

Is not actually that. In fact it is
void_ary[0]+i

according to your printf notation.

If you write
*((elem_type*)(void_ary))+i

as
*((elem_type*)(void_ary)) + i

then I think it becomes more clear.  You are looking for:
*((elem_type*)(void_ary)+i)


text:
Q: Display image from file path asp.net mvc4 I'm trying to display an image outside of the root folder of my asp .net mvc4 project - to no avail.
The img tag I have tried inside the .master page and .ascx control is:

My controller looks like:
class imagesController : Controller
{
    public ActionResult someimage()
    {
        return File(@"C:\...\image.png", "image/png");
    }
}

The method above doesn't get called, instead I'm getting a: http://localhost:62372/Builder/@Url.Action(%22someimage%22,%20%22imagesController%22) Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my routing, in case it matters:
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        //--default routing and default route--
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Login", action = "OpenLogin", id = UrlParameter.Optional } // Parameter defaults
        );

    }

I have gathered more info about the error:
Exception information:
Exception type: ArgumentException
Exception message: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.Combine(String path1, String path2)
...

A: One solution would be to look up the image path prior to page load and pass it to the view in a ViewBag variable.  This does not fix your 500 error but you may not need to solve this issue in that way.
Controller:
public ActionResult ImagePage()
    {
       ViewBag.ImageSrc = GetMeMyImagePath();
       return View();
    }

View

A: In the end I got it working by using this syntax instead:


text:
Q: How do I resend a "failed" WebRequest? I send POST and GET WebRequest that should support longer periods of internet being down. The idea is to queue the failed (timedout) webrequest and to try to resend them periodically until the internet is up again and all queued WebRequests are sent.
However, I seems that I cannot just reuse the old WebRequest. Do I need to set it up again?
IAsyncResult result = request.BeginGetResponse (o => {
        callCallback (o);
}, state);

When request is just setup using:
var request = HttpWebRequest.Create (String.Format (@"{0}/{1}", baseServiceUrl, path));
request.Method = "GET";
request.ContentType = "application/xml; charset=UTF-8";
request.Headers.Add ("Authority", account.Session);
return request;

it works fine. But after a timeout (and request.Abort ();) and calling BeginGetResponse() on the same webrequest just freezes.

A: You cannot call BeginGetResponse() multiple times on the same HttpWebRequest. I'm not sure whether that's support on .NET, but it's not possible with Mono's implementation (and not something that'd be easy to change).
See also Can I reuse HttpWebRequest without disconnecting from the server? - the underlying network connection will be reused.


text:
Q: Convergence and non-negative supermartingales Given $ (X_n)_{n\geq0}$ is a non-negative supermartingale and $X_{\infty}$ is an almost sure limit, I want to show that $ \forall n\geq0$ $$\mathbb{E}(X_\infty \mid \mathcal{F}_n) \leq X_n$$

My approach:
First, for $(X_n)$ a supermartingale I would say we then have $$ \mathbb{E}(X_m\mid\mathcal{F}_n)\leq X_n \quad \forall m\geq n$$
Now, my assumption is that $X_m$ does not necessarily converge to $X_\infty$ in $L^1$, so $\mathbb{E}(X_m)$ does not necessarily converge to $\mathbb{E}(X_\infty)$. Hence my idea would be to show that $X_m$ is uniformly integrable, where then we could show, for $X_m \longrightarrow X_\infty$ a.s in $L^1$ then $\mathbb{E}(X_m\mid\mathcal{F}_n) = \mathbb{E}(X_\infty\mid\mathcal{F}_n)$.
However, I think my approach is way off. Could someone please help me out, it would be greatly appreciated.

A: By conditional Fatou, $E(\liminf_k X_{n+k}\mid\mathcal F_n)\leq \liminf_k E(X_{n+k}\mid\mathcal F_n)$, hence $$E(X_\infty\mid\mathcal F_n)\leq \liminf_k E(X_{n+k}\mid\mathcal F_n)$$
Since $\forall k, E(X_{n+k}\mid\mathcal F_n)\leq X_n$, we have $\liminf_k E(X_{n+k}\mid\mathcal F_n)\leq X_n$ and the result follows.


text:
Q: How to combine SQL query for getting total records and getting records for pagination limit I have to apply two queries for pagination.
1) Select all records.
2) Select records with limit.
As per example
$total_records = 'select * from table_name';

$for_pagination = 'select * from table_name limit 10, 2';

Is there any solution or way to get limit records and all records together with single query?

A: Can you use Union All? if they have the same number of columns and data type.
https://www.techonthenet.com/mysql/union_all.php
Otherwise, could you please provide further information (such as sample data) as we don't have much idea on your request based on information from your question.


text:
Q: In ExtJS 4.0, how to config several "feature"s in a grid and toggle among them? var groupingFeature = Ext.create('Ext.grid.feature.Grouping');
Ext.create('Ext.grid.Panel', {
     // other options
     features: [groupingFeature]
});

Can I add a new feature into the [groupingFeature] array? How can I do it?
And if there are several features, how can I toggle among them?

Now I know how to set several features (but I'm not sure wether this way is correct or not):
var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
  id: 'group',
  ftype: 'groupingsummary',
  groupHeaderTpl: '{name}',
  hideGroupedHeader: true,
  enableGroupingMenu: false
});
var abstractSummaryFeature = Ext.create('Ext.grid.feature.AbstractSummary',{
  id: 'summary',
  ftype: 'abstractsummary',
  hideGroupedHeader: false,
  enableGroupingMenu: true
});
Ext.create('Ext.grid.Panel', {
     // other options
      dockedItems: [{
          dock: 'top',
          xtype: 'toolbar',
          items: [{
              tooltip: 'Change the feature',
              text: 'Change',
              handler: function(){
                  var view = Ext.getCmp('sell_quote_item_grid').getView();
                  view.getFeature('group').disable();//someone says I can toggle in this way,
                  view.getFeature('summary').enable();//I tried but failed...
                  view.refresh();
              }
          }]
      }],
     features: [groupingFeature, abstractSummaryFeature]
});

A: Based on this code in TableChunker.js, it is as simple as disabling the "features" you don't want to render. and then refreshing the view.
You can disable a feature by calling feature.disable() and enable it by calling feature.enable() which seems wrong, I would expect feature.enable(enabled=true|false)
    for (; i < ln; i++) {
        if (!features[i].disabled) {
            features[i].mutateMetaRowTpl(metaRowTpl);
            Ext.apply(memberFns, features[i].getMetaRowTplFragments());
            Ext.apply(tplMemberFns, features[i].getFragmentTpl());
            Ext.apply(tableTplMemberFns, features[i].getTableFragments());
        }
    }

An even more difficult question is how do you get a groupingSummary and a Summary to work together in the SAME table.  That is a good deal harder.


text:
Q: Plotting a 3d sphere in Python and using a jpg "bumpmap" I'm trying to plot a 3d sphere in Python with matplotlib and Mayavi. The function I'm using is mayavi.mlab.mesh
I can change the colours of the sphere, but I can't get either to use a jpg file as a colourmap.
How do I colour the surface of a sphere with an image file?


text:
Q: Idiom for being forced to dig your own grave? Suppose that a team of people is laid off but is asked to temporarily stay to train their replacements.  Is there any idiom that would describe people in such a conflicting situation? "Digging their own grave" comes to mind, but I typically associate that with cases where people work against their own interests by their own accord, not because they're forced to. "Faustian bargain" also isn't quite right but feels like the type of phrase I'm looking for.

A: rub salt in the wound to make a difficult situation even worse for someone
In speech I have often heard/used the shortened form 'rub(s) it in'.
As if being laid off wasn't bad enough, to rub it in [rub salt into the wound] management required us to train our replacements.

A: It's a dilemma, which in general means a choice between two unpleasant alternatives. In this case, you gain money but lose your pride, or keep your pride but lose money. It could be seen as a Hobson's choice: take the deal or get nothing. Idioms include between a rock and a hard place, damned if you do and damned if you don't.

A: I think it doesn't matter if they're "forced" ie at gunpoint to do something, or "coerced" as in giving a lot of incentive to do what will end their success/career/life. Then there's literally digging your own grave, ie at literal gun point, for a more "dramatic" scenario (I imagine Westerns would have been FILLED with these scenarios as the bandits or the like did their business).
Fallout New Vegas starts, I believe, with the main character literally doing this and then being shot in the head. But then Fallout doesn't even TRY to take itself seriously like Skyrim does... (or at least pretends to). (Fallout is full of stuff like robots sitting on toilets, teddy bears sitting on toilets reading the newspaper, etc. It's a ridiculous game, is what I'm saying.)


text:
Q: Error when using premake with the function "UseLibs" with OpenGL sdk I am using premake to make new projects using the OpenGL sdk. I am trying to put together my first real project, but I am having an error when I run premake4 vs2010 command. I am trying to use the UseLibs function to gain access the the OpenGL sdk elements, however premake is throwing an error which says:

"attempt to call global 'UseLibs' (a nil value)

Heres the lua code:
solution "OpenGL"
    configurations {"windows", "linux", "Debug", "Release"}
    project "MyProject"
        kind "ConsoleApp"
    language "c++"
files {"First OpenGL v3\*.cpp", "First OpenGL v3\*.h"}

UseLibs {"glimage", "glload", "freeglut", "glutil", "glmesh", "glfw", "glm"}

configuration "windows"
    defines "WIN32"
    links {"glu32", "opengl32", "gdi32", "winmm", "user32"}

configuration "linux"
    links {"GL"}

configuration "Debug"
    targetsuffix "D"
    defines "_DEBUG"
    flags "Symbols"

configuration "Release"
    defines "NDEBUG"
    flags {"OptimizeSpeed", "NoFramePointer", "ExtraWarnings", "NoEditAndContinue"};

Much of the code here is based on what it says to do on the tutorial so I am not sure why I am getting this error. I am fairly new at this, so if you see any other issues please tell me. Thanks.

A: Allow me to quote from what you linked to:

Regardless of whether the main premake4.lua file does all the work, the first thing you should do is execute this instruction:

dofile("path/to/GLSDK/links.lua")

I don't see that line in your Premake4 build script.
Also, there's no need to include both FreeGLUT and GLFW. You cannot possibly use them both in the same application, since they both do the same thing. They create OpenGL windows. I mean, I guess you could possibly use them both, but it seems unlikely to work.
Your program uses one or the other. Whichever one it uses is the one you should put in the UseLibs command.
Also:
configurations {"windows", "linux", "Debug", "Release"}

windows and linux are not normal, user-specified, configurations. They're OS configurations. You don't list them in the solution configuration's list; they're part of the system. Listing them here may cause problems.


text:
Q: Controller Doesn't accept my request. It always show 404 not found I am creating a spring Maven application which to send email.I just started the project and getting error 404 not found. Any help would be appreciated.
I have tried changing the dependencies of dispatcher servlet and checked if request goes to specific method but it seems, request never accepted by the controller.
Here is configuration:
index.jsp
Compose

web.xml
<servlet>
    <servlet-name>frontController</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>frontController</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

frontController-servlet.xml
 <context:component-scan base-package="com.springmvc.mainController.ControllerDemo">
     </context:component-scan>
 <mvc:annotation-driven></mvc:annotation-driven>
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/jsp/"></property>
     <property name="suffix" value=".jsp"></property>
 <bean>

ControllerDemo.java
@RequestMapping("/compose")
public String compose()
{
    System.out.println("Request Received...");
    return "new";
}

It never accepts request.


text:
Q: Select option doesn't post correctly after being manipulated with javascript I have a select field where the content changes depending on another select field. With the my script disabled, my selection posts fine and is inserted in my DB. However, when I mess with the select field with javascript, my posted value defaults to the default one ("1"). I am also running chzn (http://harvesthq.github.io/chosen/) but the problem persists even with it disabled. Here is my JS :
$(function() {
    var $dropdown = $("#type");
    var $for = $("#for");

    $for.clone().attr('id', 'for2' ).insertAfter($for).hide();
    $for2 = $('#for2');

    function getType() {
        $type = $dropdown.val();
        return $type;
    }

    function checkType($type) {
        if ($type == 1) {
            $for.find('.skin').remove();
            $for2.find('.champion').clone().appendTo($for).trigger("liszt:updated");
        } else if ($type == 2) {
            $for.find('.champion').remove();
            $for2.find('.skin').clone().appendTo($for).trigger("liszt:updated");
        }
    }

    getType();
    checkType($type);

    $dropdown.change(function() {
        getType();
        checkType($type);
    });
});

What causes this issue? Thanks for looking :)
edit Running alert($for.find($("option:selected")).text()); indeed returns my selected option. I really don't understand why it is not getting posted.
edit2 I can get it to work by appending a (hidden) text field, and setting it's value when my select changes, and of course updating my controller to use the "for-value" :
$('<input/>').attr({ type: 'text', id: 'for-value', name: 'for-value' }).insertAfter($for).hide();
$forValue = $('#for-value');

$for.change(function() {
    $forVal = $for.val();
    $forValue.val($forVal);
});

But this is so ugly.... why can't I get it to work the regular way? Am I missing something?
edit3
As requested, HTML :
<form action="insert" method="POST">

    ...

    type
    <select id="type" name="type">
        <option value="1">Champion</option>
        <option value="2">Skin</option>
    </select>

    For
    <select id="for" name="for">
        @foreach ($skins as $skin)
        <option class="skin" value="{{ $skin->id }}">{{ $skin->name }}</option>
        @endforeach
        @foreach ($champions as $champion)
        <option class="champion" value="{{ $champion->id }}">{{ $champion->name }}</option>
        @endforeach
    </select>

    ...

    <button>Insert</button>

</form>

edit4 Even worse, as suggested by Stano to include a name while cloning makes it work, it even works if I remove the attribute during the chain :
$for.clone().attr('id', 'for2').insertAfter($for).hide(); //doesn't work.
$for.clone().attr({ id: 'for2', name: 'for2' }).insertAfter($for).hide(); //works
$for.clone().attr({ id: 'for2', name: 'for2' }).removeAttr('name')
    .insertAfter($for).hide(); //works even if I remove the attribute

A: Cloning the object would also take the name with it, and posting would take the last name referenced in the HTML, which was the copy of the first select. This is why it would always return 1.
Removing, or renaming the name attribute during the chain counters this, like so :
$for.clone().attr('id', 'for2').removeAttr('name').insertAfter($for).hide();


text:
Q: Importing HTML without AJAX? I recently finished a web plugin that has a tool composed of around 350 lines of HTML markup. I have stored such in a GUI.html file. I am able to load this file with jQuery's $("#some.element").load("GUI.html"); as long as I'm not testing locally.
However, since this plugin is meant to be used by others, I think is too much of a pain to not be able to test locally, so I got around this by storing the markup in a string in a JavaScript file:
// GUI.js
MyPlugin.GUI = "

...';

This works since loading scripts is not restricted locally in browsers such as Chrome (while XMLHttpRequests are).
Is there any other less intrusive way to load the HTML file without having to turn it into an ugly string that will be cumbersome to edit later?


text:
Q: Unicode font is not rendering in SWING when combine three characters ക (\u0D15) + ് (\u0D4D) + ര (\u0D30), getting ര്ക instead of ക്ര I am working on a text editor for Malayalam in Java.
Unicode font is not rendering correctly in Swing - JTextArea.
Combination of characters. Instead of blending two characters, Text area displaying it separately. Both swing and font support those characters but in key combinations it is not working Even though supported font is used.
For Example:
What is needed
ക്രാ

What is getting
്രക

Code
jButton69.setFont(new java.awt.Font("Meera", 0, 12)); // NOI18N
        jButton69.setText(" ്ര");

    jTextArea1.append(jButton69.getText());

EDIT: (Complementary information from author's commentary):
When combine three characters ക (\u0D15) + ് (\u0D4D) + ര (\u0D30), I am getting ര്ക instead of ക്ര.
Language is Malayalam, Font is Meera

A: You must set the JTextArea font to a Unicode font.
Besides that, the button69 has nothing to do with the problem, so I don't use it.
The following code is showing the text the way you want:
String problemText = "ഔ";
Font font = new Font("Arial Unicode MS", Font.PLAIN, 18);
JTextArea jTextArea1 = new JTextArea();
jTextArea1.setFont(font);
jTextArea1.append(problemText);

I hope it helps.

A: Please check out Zero Width Joiners and Zero Width Non-joiners. For your requirement, I got the correct output by using a zero width joiner as: \u0d15 + \u0d4d + \u200d + \u0d30.

A: Please check out Zero Width Joiners and Zero Width Non-joiners. For your requirement, I got the correct output by using a zero width joiner as: \u0d15 + \u0d4d + \u200d + \u0d30 (Please ignore my previous answer, it is the same but posted with the wrong user account).


text:
Q: Redux thunk async action cannot access first parameter I  have an action that currently works fine using .then but when I try and convert it to async ... await it suddenly can't access the first parameter of the function. The second parameter still works fine though.
Current function that works fine:
export const signInUser = (email, password) => {
  return (dispatch) => {
    return firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => {
        console.log('signed in')
        const { uid, email } = firebase.auth().currentUser
        dispatch({ type: 'SIGN_IN', uid, email })
        return dispatch(fetchAllData())
      })
      .catch(error => {
        throw (error)
      })
  }
};

New function that doesn't work because 'email' is undefined.
export const signInUser = (email, password) => {
  return async (dispatch) => {
    console.log('testing')
    console.log(password)
    console.log('testing', email, password)
    await firebase.auth().signInWithEmailAndPassword(email, password)
    console.log('signed in')
    const { uid, email } = firebase.auth().currentUser
    dispatch({ type: 'SIGN_IN', uid, email })
    return dispatch(fetchAllData())
  }
};

The first console log of console.log('testing') works fine and outputs the string 'testing'. The second console log of console.log(password) also works fine and prints the inputted password. But the third console log console.log('testing', email, password) doesn't get shown at all.
This is how the function is called:
Parent component passes it to child component:
submit={(email, password) => dispatch(signInUser(email, password))}
Child component calls it:
  const submitForm = (event) => {
    event.preventDefault();
    if (validForm) {
      setLoading(true)
      submit(email, password)
        .catch(err => {
          setLoading(false)
          console.log('catch:', err.code)
          setError(err.code)
        })
    }
  }

The output I am receiving is catch: undefined.
Also, if I change the function to this:
export const signInUser = (email, password) => {
  const userEmail = email
  return async (dispatch) => {
    console.log('testing')
    console.log(password)
    console.log('testing', userEmail, password)
    await firebase.auth().signInWithEmailAndPassword(userEmail, password)
    console.log('signed in')
    const { uid, email } = firebase.auth().currentUser
    dispatch({ type: 'SIGN_IN', uid, email })
    return dispatch(fetchAllData())
  }
};

Then it works fine. But I don't know why I would need to change it like this?
Thanks

A: Ok so the reason it wasn't working was because on the next line I was declaring email like this const { uid, email } = firebase.auth().currentUser
 which was overriding the function parameter of email and therefore giving me the error that i was using email before it was declared.


text:
Q: Why java.util.Arrays uses Two Sorting Algorithms? java.util.Arrays uses quicksort (actually dual pivot quicksort in the most recent version) for primitive types such as int and mergesort for objects that implement Comparable or use a Comparator.
Why the difference?
Why not pick one and use it for all cases?

A: A good explanation here:-

Quicksort is faster in both cases. Mergesort is stable in both cases.
  But for primitive types quicksort is stable too! That's because
  primitive types in Java are like elementary particles in quantum
  mechanics. You can't tell the difference between one 7 and another 7.
  Their value is all that defines them. Sort the array such [7, 6, 6, 7,
  6, 5, 4, 6, 0] into [0, 4, 5, 6, 6, 6, 6, 7, 7]. Not only do you not
  care which 6 ended up in which position. It's a meaningless question.
  The array positions don't hold pointers to the objects. They hold the
  actual values of the objects. We might as well say that all the
  original values were thrown away and replaced with new ones. Or not.
  It just doesn't matter at all. There is no possible way you can tell
  the difference between the output of a stable and unstable sorting
  algorithm when all that's sorted are primitive types. Stability is
  irrelevant with primitive types in Java.

A: I think that the reason is stability.
The primitives do not have an identity, so it is impossible to distinguish between 2 integers with the same value. This is not the case for referenced types this might be problematic as quick sort might change their relative positions and that is why a more stable merge sort is used.
Also, not using n*log n for primitives might be because it would require a clone of an array. For reference types it does not really matter as they arrays of objects are normally bigger than the corresponding arrays of references. However, for primitives clonning uses double memory.


text:
Q: How to execute sql query with python variables null or empty Hi I'm using python 3 and snowflake.
Example:
MY_SCHEMA = 'TEST'
MY_TABLE = Empty

sql = "SELECT SCHEMA, TABLE FROM TABLE_LOG WHERE SCHEMA = %s AND TABLE = %s"

tuple1 = (MY_SCHEMA, MY_TABLE)
cur.execute(sql,tuples1)

I tried with this:
 WHERE SCHEMA = %s OR (SCHEMA IS NULL AND %s IS NULL) also WHERE SCHEMA = IIF(%S IS NULL, SCHEMA, %s)

I'm getting TypeError: not enough arguments for format string. I would like to run this query for all schemas if I dont have defined MY_SCHEMA variable and also for all tables if MY_TABLE variable is null or empty.
I would be grateful for any advice.

A: I found a solution this issue:
MY_SCHEMA = 'TEST'
MY_TABLE = None

cur.execute("SELECT SCHEMA,TABLE FROM TABLE_LOG WHERE SCHEMA = COALESCE(%(schema_variable)s,SCHEMA) AND TABLE = COALESCE(%(table_variable)s,TABLE )",{"schema_variable": MY_SCHEMA, "table_variable": MY_TABLE})


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'params') - React I am not sure what I'm missing here. I did a few search about this error but I can't not find anything that will on my error. The Home screen page will render all images. Prior to this, when a single image is clicked, it will open a new page to show the image. What i was trying to do is, when the image is clicked, i would like the image PLUS the detailed information of the image. All I get is an empty blank page with the error on dev tools (see below). Thank you in advance...
ProductScreen.js:18 Uncaught TypeError: Cannot read properties of undefined (reading 'params')
Here's the code:
import React, { useEffect } from 'react';
import Rating from '../components/Rating';
import { Link, useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import { detailsProduct } from '../actions/productActions';

function ProductScreen(props) {

  const dispatch = useDispatch();

  const { id } = useParams();
  console.log("A", id);
  const productId = props.match.params.id; // this is the error as per dev tools
  console.log(props.match.params.id);

  const productDetails = useSelector((state) => state.productDetails);

  const { loading, error, product } = productDetails;

  useEffect = (() => {
    dispatch(detailsProduct(productId));
  }, [dispatch, productId]);

 return (

 //code here

  )
}

export default ProductScreen;

  [1]: https://i.stack.imgur.com/jdshU.png

A: Looks like you are not passing the props match while creating the JSX Element of ProductScreen. This line will look like this
<ProductScreen match={someMatchObj} />

As @mushroomator suggests you should also check if the value is undefined.

A: @mushroomator
This is my JSX...
 return (

      {loading ? (
        <LoadingBox></LoadingBox>
      ) : error ? (
        <MessageBox variant="danger">{error}</MessageBox>
      ) : (

          <Link to="/">Back To Result</Link>

{product.name}

                  <Rating
                    rating={product.rating}
                    numReviews={product.numReviews}
                  >
                  </Rating>

                  Price: ${product.price}

                  Description:

{product.description}

Price

${product.price}

Status

                        {product.countInStock > 0 ? (
                          In Stock
                        ) : (
                          Unavailable
                        )}

                    <button className="primary block">Add to Cart</button>

      )}

 )
}

export default ProductScreen;


text:
Q: Dropping Column with all distinct values in pandas I want to drop a column from the dataframe if all values are distinct and none repeat.
for example:
    ID  NAME    VALUE1  VALUE2  VALUE3
 0  1   Alpha   100     A1      ULV
 1  2   Alpha   100     A1      SMU
 2  3   Alpha   200     A2      UT

Column ID would get dropped since no values repeat and it would turn into this:
    NAME    VALUE1  VALUE2  VALUE3
0   Alpha   100     A1      ULV
1   Alpha   100     A1      SMU
2   Alpha   200     A2      UT

How could I do this?

A: You can use a list comprehension to check if each column has duplicated items:
import pandas

# Recreate example dataframe
df = pandas.DataFrame({
    'ID': [1,2,3],
    'NAME': ['Alpha', 'Alpha', 'Alpha'],
    'VALUE1': [100, 100, 200],
    'VALUE2': ['A1', 'A1', 'A2'],
    'VALUE3': ['ULV', 'SMU', 'UT'],
})

df = df[[col for col in df.columns if df[col].duplicated().any()]]

Output:
    NAME  VALUE1 VALUE2
0  Alpha     100     A1
1  Alpha     100     A1
2  Alpha     200     A2

A: max_ = max(df.nunique().to_list())

cols = []
for i, (key, val) in enumerate(df.nunique().to_dict().items()):
    if val != max_:
        cols.append(key)

df = df[[col for col in cols]]


text:
Q: How to print stack trace of a thread (with thread id) via bash command? I would try to monitor the action performed on a  thread something like tail command. And it should print the stackTrace of the thread (whose thread id is known).
I could print the stack trace of all the threads which is currently running under the java process like the following
pid=$(ps -ef |grep 'catalina' | grep java | awk ' { print $2 } ');
eval '/home/jdk/bin/jstack -F $pid' > stack_trace.txt

But I need to print stack trace of the thread whose thread id is known.
Any help in this  regard is most welcome. Thanks in advance :)

A: Can you try to see if below works for you.
TARGET_THREAD_ID=xxx JAVA_PID=$(ps -ef | grep "[org].apache.catalina.startup.Bootstrap"  | awk '{print $2}'); jstack -F ${JAVA_PID} | sed -n -e "/Thread ${TARGET_THREAD_ID}/,/Thread /p" | head -n -1

Which will print something like below
Thread xxx: (state = BLOCKED)
 - java.lang.Object.wait(long) @bci=0 (Compiled frame; information may be imprecise)
 - java.lang.Object.wait() @bci=2, line=502 (Compiled frame)
 - java.lang.ref.Reference.tryHandlePending(boolean) @bci=54, line=191 (Compiled frame)
 - java.lang.ref.Reference$ReferenceHandler.run() @bci=1, line=153 (Compiled frame)


text: Q: How to sync between client timings and server timings in PHP? I've some logs in my website, If I host the website on my localhost it is showing my local time, but if I host the same codes on my server and even though I set my default timezone using date_default_timezone_set('Asia/Kolkata'); the logs are using different timings. I'm using Linux server How can I sync between these two timings.


text:
Q: Upload multiple files to multiple S3 buckets in Terraform I am very new to terraform. My requirement is to upload objects to existing s3 buckets. I want to upload one or more objects from my source to one or more buckets utilizing only one resource. Using count and count.index I can create different numbers of resources. However, doing so will prevent me from using fileset which helps to recursively upload all the contents in the folder.
The basic code look like this. This is for multiple file uploads to single bucket but I would like to modify for multiple uploads to different buckets.;
variable "source_file_path"{
   type = list(string)
   description = "Path from where objects are to be uploaded"
}

variable "bucket_name"{
    type = list(string)
    description = "Name or ARN of the bucket to put the file in"
}

variable "data_folder"{
    type = list(string)
    description = "Object path inside the bucket"
}

resource "aws_s3_bucket_object" "upload_object"{
    for_each = fileset(var.source_file_path, "*")
    bucket = var.bucket_name
    key = "${var.data_folder}${each.value}"
    source = "${var.source_file_path}${each.value}"
 }

I have created a vars.tfvars file with following values;
source_file_path = ["source1","source2"]
bucket_name = ["bucket1","bucket2"]
data_folder = ["path1","path2"]

So, what I need is, terraform to be able to upload all the files from the source1 to bucket1 s3 bucket by creating path1 inside the bucket. And similarly for source2, bucket2, and path2.
Is this something that can be done in terraform?

A: From your problem description it sounds like a more intuitive data structure to describe what you want to create would be a map of objects where the keys are bucket names and the values describe the settings for that bucket:
variable "buckets" {
  type = map(object({
    source_file_path = string
    key_prefix       = string
  }))
}

When defining the buckets in your .tfvars file this will now appear as a single definition with a complex type:
buckets = {
  bucket1 = {
    source_file_path = "source1"
    key_prefix       = "path1"
  }
  bucket2 = {
    source_file_path = "source2"
    key_prefix       = "path2"
  }
}

This data structure has one element for each bucket, so it is suitable to use directly as the for_each for a resource describing the buckets:
resource "aws_s3_bucket" "example" {
  for_each = each.buckets

  bucket = each.key
  # ...
}

There is a pre-existing official module hashicorp/dir/template which already encapsulates the work of finding files under a directory prefix, assigning each one a Content-Type based on its filename suffix, and optionally rendering templates. (You can ignore the template feature if you don't need it, by making your directory only contain static files.)
We need one instance of that module per bucket, because each bucket will have its own directory and thus its own set of files, and so we can use for_each chaining to tell Terraform that each instance of this module is related to one bucket:
module "bucket_files" {
  for_each = aws_s3_bucket.example

  base_dir = var.buckets[each.key].source_file_path
}

The module documentation shows how to map the result of the module to S3 bucket objects, but that example is for only a single instance of the module. In your case we need an extra step to turn this into a single collection of files across all buckets, which we can do using flatten:
locals {
  bucket_files_flat = flatten([
    for bucket_name, files_module in module.bucket_files : [
      for file_key, file in files_module.files : {
        bucket_name  = bucket_name
        local_key    = file_key
        remote_key   = "${var.buckets[each.key].key_prefix}${file_key}"
        source_path  = file.source_path
        content      = file.content
        content_type = file.content_type
        etag         = file.digests.md5
      }
    ]
  ])
}

resource "aws_s3_bucket_object" "example" {
  for_each = {
    for bf in local.bucket_files_flat :
    "s3://${bf.bucket_name}/${bf.remote_key}" => bf
  }

  # Now the rest of this is basically the same as
  # the hashicorp/dir/template S3 example, but using
  # the local.bucket_files_flat structure instead
  # of the module result directly.

  bucket       = each.value.bucket_name
  key          = each.value.remote_key
  content_type = each.value.content_type

  # The template_files module guarantees that only one of these two attributes
  # will be set for each file, depending on whether it is an in-memory template
  # rendering result or a static file on disk.
  source  = each.value.source_path
  content = each.value.content

  # Unless the bucket has encryption enabled, the ETag of each object is an
  # MD5 hash of that object.
  etag = each.value.etag
}

Terraform needs a unique tracking key for each instance of aws_s3_bucket_object.example, and so I just arbitrarily decided to use the s3:// URI convention here, since I expect that's familiar to folks accustomed to working with S3. This means that the resource block will declare instances with addresses like this:

*

*aws_s3_bucket_object.example["s3://bucket1/path1example.txt"]

*aws_s3_bucket_object.example["s3://bucket2/path2other_example.txt"]
Because these objects are uniquely identified by their final location in S3, Terraform will understand changes to the files as updates in-place, but any changes to the location as removing an existing object and adding a new one at the same time.
(I replicated the fact that your example just concatenated the path prefix with the filename without any intermediate separator, and so that's why it appears as path1example.txt above and not path1/example.txt. If you want the slash in there, you can add it to the expression which defined remote_key inside local.bucket_files_flat.)


text:
Q: rollup esm and umd builds, with typescript plugin and declarations, not possible? I want to use rollup to make two builds of my library, an UMD version as well as a never ESM version
Earlier my configuration when using the non official plugin rollup-plugin-typescript2 looked like this:
import typescript from 'rollup-plugin-typescript2'
import pkg from '../package.json'
export default {
  input: 'src/index.ts',
  output: [
    {
      file: pkg.main,
      format: 'umd',
      name: pkg.name,
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'esm',
      sourcemap: true
    },
  ],
plugins: [
    typescript({
        tsconfig: "src/tsconfig.json",
        useTsconfigDeclarationDir: true
    }),
  ],
}

And in my package json I have:
  (...)
  "scripts": {
    "build": "rollup -c ./scripts/dist.js",
  },
  "main": "dist/index.js",
  "module": "dist/index.esm.js",
  "files": [
    "dist"
  ],
  (...)

And in my tsconfig.json I have:
  (...)
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "declarationDir": "./dist/@types/chrisweb-utilities",
    (...)

The resulat was "created dist/index.js, dist/index.esm.js in 2.6s" ... all good
The files that got created where the following:
/dist
|-@types
 |-index.d.ts
|-index.js
|-index.esm.js
|-index.esm.js.map
|-index.js.map

Today I tried to use the official plugin @rollup/plugin-typescript instead (because I use that one in other projects where I only do a single ESM build and it works without a problem and I wanted to use the same plugins through out all of my projects)
I had a first error because of the  configuration propery only rollup-plugin-typescript2 understands:
"(!) Plugin typescript: @rollup/plugin-typescript TS5023: Unknown compiler option 'useTsconfigDeclarationDir'."
So I removed it, which fixed that problem ...
But I got another error: "[!] (plugin typescript) Error: @rollup/plugin-typescript: 'dir' must be used when 'outDir' is specified."
So I added dir to my configuration, which then looked like this:
import typescript from '@rollup/plugin-typescript';
import pkg from '../package.json'
export default {
  input: 'src/index.ts',
  output: [
    {
      file: pkg.main,
      format: 'umd',
      name: pkg.name,
      sourcemap: true,
      dir: "dist",
    },
    {
      file: pkg.module,
      format: 'esm',
      sourcemap: true,
      dir: "dist",
    },
  ],
plugins: [
    typescript({
        tsconfig: "tsconfig.json",
    }),
  ],
}

Nope, next error shows up: "[!] Error: You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks."
Actually I don't even want to generate chunks, I'm fine with a single file, but I remove dir I'm back to the previous error. So next thing I tried was to keep "dir" and instead remove "file"
This worked, or at least I got a success message: "created dist, dist in 2.6s" but the problem now is that instead of having two builds I just have a single one "dist/index.js", the first build for UMD gets owerwritten by the second one for ESM.
I thought ok one last try, lets output the UMD version in a subfolder of /dist and the ESM version in another one, so I changed my config to this:
  (...)
  output: [
    {
      format: 'umd',
      name: pkg.name,
      sourcemap: true,
      dir: "dist/umd",
    },
    {
      format: 'esm',
      sourcemap: true,
      dir: "dist/esm",
    },
  ],
  (...)

This failed too :( this time with this error: "[!] (plugin typescript) Error: @rollup/plugin-typescript: 'outDir' must be located inside 'dir'." So my outDir is "./dist" which yes is not in dir: "dist/umd" anymore, I only have one outDir in tsconfig, so it can't be in each rollup output.dir, or do I miss something here?
Oh and I actually also tried something else, remember that earlier error where rollup told me that "'dir' must be used when 'outDir' is specified", so I removed outDir from tsconfig.json and hey another rollup error (at this point I think I got all possible rollup errors ;) ) which was the following: "[!] (plugin typescript) Error: @rollup/plugin-typescript: 'dir' must be used when 'declarationDir' is specified."
So I also commented out "declarationDir" in the tsconfig ... no more error, but this is not really the solution as now I don't have typescript type definition files getting generated.
I went back and forth and tried all combinations for hours, but no luck so far...
So I'm stuck and was wondering if someone can help me out? Maybe you had this or a similar problem? Either I'm missing something or this a bug in which case I will open a ticket in a few days.


text:
Q: Reuse PyQt window design across multiple instances I have designed a window in QT designer and then converted it to Python code. Then I created class A and Class B which inherit from PYQT code. Then I create the third class call it C and inherit from class A and B.
from QTfile import *
from PyQt5.QtWidgets import *
class A(QMainWindow):
def __init__(self):
    super().__init__()
    self.A1= Ui_MainWindow()
    self.A1.setupUi(self)

class B(QMainWindow):
def __init__(self):
    super().__init__()
    self.B1= Ui_MainWindow()
    self.B1.setupUi(self)

Now the problem is when I want to use super().__init__() function, I only can initiate one of them.
class C( A,B):
def __init__(self):
    super().__init__()

If I use A.__init__() and B.__init__(), it works again only for one classes
class C( A,B):
def __init__(self):
    A.__init__()
    B.__init__()

Now the question is how can I initiate the multiple classes?

A: If you want to reuse the design in multiple window instances, you can try the following:
class BaseWindow(Ui_MainWindow, QMainWindow):
    def __init__(self):
        Ui_MainWindow.__init__(self)
        QMainWindow.__init__(self)
        self.setupUi(self)

class A(BaseWindow):
    def __init__(self):
        super().__init__()

class B(BaseWindow):
    def __init__(self):
        super().__init__()


text:
Q: Ubuntu won't boot from USB 2.0 Although my computer is capable of booting from USB devices and I have set the boot order correctly in my BIOS, I find that I am unable to boot any installation of Ubuntu I have (be they on external Hard Drives or USB card readers etc.) from either of my USB 2.0 ports.
These exact same installations boot perfectly fine from my USB 3.0 port!
Now, I get that USB 2.0 is much slower but it should still boot eventually provided the computer can do it. I know my computer can boot from the 2.0 ports because ubuntu IS found and does actually initiate the booting process but after several long minutes of light flashing and disk access, the booting process freezes and Ubuntu never comes up even if you wait hours.
Take the same disk out, place it in the USB 3.0 port and Ubuntu loads in a few minutes perfectly.
I would be perfectly happy with that situation if it wasn't for the fact that I only have one USB 3.0 port which I need for other purposes once Ubuntu is booted and it seems you cannot boot anything from a USB hub... so I'm kind of 'up the creek without a paddle'...or 'without a USB 3.0 port' as the case may be.
Any help would be greatly appreciated. :)

A: Ok, I'm going to answer my own post, as seems to be the tradition on here. I really don't understand this forum. I've used MANY forums in my life and I'm never used another forum where everyone just sends comments and no one actually answers the question by replying to the post... anyway... putting that weirdness to one side...
For anyone having this same difficulty I've worked out how to get Ubuntu (regardless of which version is used, which is, as I said, UNIMPORTANT) to boot over USB 2.0. The answer is at install time, do not format the disk you plan to install Ubuntu on as ext4! Instead, format as ext3! Works perfectly on USB 2.0 now. Ext4 works fine for USB 3.0. I have no idea why this is the case, I just know that it works.
Thanks me!


text:
Q: Oauth2 Resource Server + Azure AD + Java Code (Non Spring Boot/Framework) Is there any solutions available to implement Oauth2 Resource Server using Azure AD without the spring boot/security frameworks. All examples I am finding are done in spring boot.
I have a java web application project which uses Jersey framework. I am trying to find some java code/sdk which will help to implement this.
Thanks in advance

A: Sometimes use of a library works better than a framework like Spring, as long as you understand the security principles.
An OAuth secured API should just need to validate JWTs and this applies to those issued by Azure AD or any other provider, since the security involved is standards based.
Have a look at this code example which uses a respected Java library. The example is in Kotlin but you will find it trivial to integrate into a Java API.
You will need to pass the result of access token validation (scopes and claims) to the API logic, then use these values for domain specific authorization. It is common to use a request attribute for this.
Azure AD tokens have a few peculiarities, mostly on the client side, so post back if you have any follow up questions.