text:
Q: help in plotting Minimize function Please help in plotting the following function versus $c2 \in [-1,1]$
$$S = \mathop {\min }\limits_{\theta 1,\theta 2,\phi 1,\phi 2} F(c2,\theta 1,\theta 2,\phi 1,\phi 2)$$
where ${\theta _i},{\phi _i}$  belong to the interval $[0,2\pi ]$.
Here my function:
S = 1/(32 Log[2]) E^(-I (ϕ1 + ϕ2)) (8 (-2 E^(I (ϕ1 + ϕ2)) +
        1/2 √(E^(2 I (ϕ1 + ϕ2)) +
            c2^2 (E^(2 I ϕ1) + E^(4 I ϕ1) + E^(
               2 I ϕ2) + E^(4 I ϕ2) +
               3 E^(2 I (ϕ1 + ϕ2)) + E^(
               2 I (2 ϕ1 + ϕ2)) + E^(
               2 I (ϕ1 + 2 ϕ2))) +
            c2 (1 + E^(2 I ϕ1) + E^(2 I ϕ2) + E^(
               4 I (ϕ1 + ϕ2)) + E^(
               2 I (2 ϕ1 + ϕ2)) + E^(
               2 I (ϕ1 + 2 ϕ2)))) Abs[Sin[2 θ1]] Abs[
          Sin[2 θ2]]) Log[
       1/8 E^(-I (ϕ1 + ϕ2)) (4 E^(
           I (ϕ1 + ϕ2)) - √(E^(
              2 I (ϕ1 + ϕ2)) +
              c2^2 (E^(2 I ϕ1) + E^(4 I ϕ1) + E^(
                 2 I ϕ2) + E^(4 I ϕ2) +
                 3 E^(2 I (ϕ1 + ϕ2)) + E^(
                 2 I (2 ϕ1 + ϕ2)) + E^(
                 2 I (ϕ1 + 2 ϕ2))) +
              c2 (1 + E^(2 I ϕ1) + E^(2 I ϕ2) + E^(
                 4 I (ϕ1 + ϕ2)) + E^(
                 2 I (2 ϕ1 + ϕ2)) + E^(
                 2 I (ϕ1 + 2 ϕ2)))) Abs[
            Sin[2 θ1]] Abs[Sin[2 θ2]])] -
     4 (4 E^(
         I (ϕ1 + ϕ2)) + √(E^(
            2 I (ϕ1 + ϕ2)) +
            c2^2 (E^(2 I ϕ1) + E^(4 I ϕ1) + E^(
               2 I ϕ2) + E^(4 I ϕ2) +
               3 E^(2 I (ϕ1 + ϕ2)) + E^(
               2 I (2 ϕ1 + ϕ2)) + E^(
               2 I (ϕ1 + 2 ϕ2))) +
            c2 (1 + E^(2 I ϕ1) + E^(2 I ϕ2) + E^(
               4 I (ϕ1 + ϕ2)) + E^(
               2 I (2 ϕ1 + ϕ2)) + E^(
               2 I (ϕ1 + 2 ϕ2)))) Abs[Sin[2 θ1]] Abs[
          Sin[2 θ2]]) Log[
       1/8 E^(-I (ϕ1 + ϕ2)) (4 E^(
           I (ϕ1 + ϕ2)) + √(E^(
              2 I (ϕ1 + ϕ2)) +
              c2^2 (E^(2 I ϕ1) + E^(4 I ϕ1) + E^(
                 2 I ϕ2) + E^(4 I ϕ2) +
                 3 E^(2 I (ϕ1 + ϕ2)) + E^(
                 2 I (2 ϕ1 + ϕ2)) + E^(
                 2 I (ϕ1 + 2 ϕ2))) +
              c2 (1 + E^(2 I ϕ1) + E^(2 I ϕ2) + E^(
                 4 I (ϕ1 + ϕ2)) + E^(
                 2 I (2 ϕ1 + ϕ2)) + E^(
                 2 I (ϕ1 + 2 ϕ2)))) Abs[
            Sin[2 θ1]] Abs[Sin[2 θ2]])]);

A: First make S into a proper function like this (clear kernel first):
S[ϕ1_?NumericQ, ϕ2_?NumericQ, θ1_?NumericQ, θ2_?NumericQ, c2_?NumericQ] := ...

Then write:
cx[a_] := 0 <= a <= 2 π
f[c2_] := NMinimize[{Re@S[ϕ1, ϕ2, θ1, θ2, c2],
     cx[ϕ1], cx[ϕ2], cx[θ1],
     cx[θ2]}, {ϕ1, ϕ2, θ1, θ2}][[1]] //Re

It only considers the real part as there's a very small imaginary part (floating point error?) which needs to be discarded.
Plot[f[c2], {c2, -1, 1}]


text:
Q: Format an Excel cell from VB 6.0 with an amount to two decimal places When using vb 6.0 to make a cell, we cannot force the amount to be shown with 2 places after the decimal if the number does not have end in 1-9.  For example 59.12   shows up correctly but if we try 59.10  we get 59.1 in the cell.  Have tried many different formats and text outputs but with no success.
In answer to what we have tried below is a portion of the code we have been trying with the most remarked out:
StartForm:

ActiveWorkbook.Styles.Add(Name:="NelcoAmt").NumberFormat = "#.00"

'ActiveWorkbook.Styles("Number").NumberFormat = "######.00"
'ActiveWorkbook.Styles("Number").Application.FixedDecimalPlaces = 2
'ActiveWorkbook.Styles("Currency").Application.Caption = ""

'ActiveWorkbook.Styles("Currency").IncludePatterns = False

'ActiveWorkbook.Styles("Currency").Application. = ""

'ActiveWorkbook.Styles("Currency").Application.

'xlSheet.Cells(1, 34).NumberFormat = "@"

'xlSheet.Cells(2, 34).NumberFormat = "#.00"

'xlSheet.Cells(2, 34).Format = "#.00"

ActiveWorkbook.Styles("NelcoAmt").Application.FixedDecimalPlaces = 2
xlSheet.Cells(2, 34).Style = "NelcoAmt":  '.NumberFormat = "#.00": 'Number

'For i% = 1 To ActiveWorkbook.Styles.Count

'Text$ = ActiveWorkbook.Styles(i%).Name

'xlSheet.Cells(i%, 1).Style = Text$
'xlSheet.Cells(i%, 1).Value = 59.4

'xlSheet.Cells(i%, 2).Value = Text$

'Next i%

Rem-----9/15/14---set header for variables
xlSheet.Cells(1, 1).Value = "UniqueFormKey"
xlSheet.Cells(1, 2).Value = "FormName"
xlSheet.Cells(1, 3).Value = "OR_EFIN"
xlSheet.Cells(1, 4).Value = "OR_Type"

Rem======================================start of test section
Dim NumAns As Double

'7/16/15
    'NumAns = Format$(Format$(Val(Frm941Inp.Scr941(19)), "########.00"), "@@@@@@@@@@@")
    txtOut = Format$(Format$(Val(Frm941Inp.Scr941(19)), "########.00"), "@@@@@@@@@@@")

    'NumAns = FormatNumber((Val(Frm941Inp.Scr941(19))), 2)

    NumAns = Val(Frm941Inp.Scr941(19))

    If Val(Frm941Inp.Scr941(18)) = 0 Then txtOut = "0.00"
    txtOut = Frm941Inp.Scr941(19)
'xlSheet.Cells(2, 34).NumberFormat = "@": ' = txtOut: '"########.00"]
'xlSheet.Cells(2, 34) =  (FormatNumber(Val(Frm941Inp.Scr941(19)), 2), "text"): 'txtOut ', "########.00"): '5d 2 tax on add medi wage
'xlSheet.Cells(2, 34) = "'" & FormatNumber(Val(Frm941Inp.Scr941(19)), 2): 'txtOut ', "########.00"): '5d 2 tax on add medi wage
'txtOut = "'" & txtOut

xlSheet.Cells(2, 34).Style.NumberFormat = "#.00": 'Number
xlSheet.Cells(2, 34) = Format(NumAns, "#.00"): 'txtOut: 'Val(Frm941Inp.Scr941(19)):  'txtOut ', "########.00"): '5d 2 tax on add medi wage

'xlSheet.Cells(2, 34).Style.NumberFormat = "#.00": 'Number

'xlSheet.Cells(2, 34).NumberFormat = "#.00"

'xlSheet.Cells(2, 34).Value = Val(Frm941Inp.Scr941(19))

'xlSheet.Cells(2, 34).value = FormatNumber(Val(Frm941Inp.Scr941(19)), 2): '"#######.00")
'xlSheet.Cells(2, 34).Value = Format$(Format$(Val(Frm941Inp.Scr941(19)), "########.00"), "@@@@@@@@@@@")

'xlSheet.Cells(2, 34).Value = Val(Frm941Inp.Scr941(19)): '5d 2 tax on add medi wage
Rem===================================end of test section=================================================

A: For spreadsheets: What is displayed in the cell, and what is actually stored may differ quite much.
Example: Date and time values are 1.0 per day, with hours minutes and seconds present in the decimals so that 42205.5 equals "2015-07-20 12:00".

To have "59.1" (or anything else that may be rounded to that in two decimals) display as "59.10" you need to set the display format to "0.00" or similar.
Press and hold CTRL then hit 1;
In the dialogue, find "Number", click on it and change "Decimal places" to read "2". Now click OK to set it and leave the dialogue.
An alternative is using "Custom" (or "User defined" for LibreOffice) in the same dialogue and type in "0.00" as "Format code" - with the same end result.
Exactly how to do it from VBA? I'll leave that as a task for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ - How to detect I am running without a terminal In C/C++ how can my programs determine if there is a desktop (system or remote) or not?
My project has three separate programs running (now) in separate gnome-terminals.  It is launched by the last line of .profile, so it starts whether I am at the system desktop (gnome) or remotely connecting by VPN/telnet or VPN/remote-desktop.  My machine is 250 miles away at a test site, so I frequently login remotely to make changes and have to restart the program.
I'd like my program to be able to detect that it is launched from a desktop environment or from a telnet session.  Preferably, I want them to continue running after the remote connection is broken.
Obviously, I need to make my programs into daemons so they will persist after I close the connection.   But if I start them in a terminal on a desktop environment, where I can actually have three terminals open, I'd like to watch their progress messages.  And if I disconnect the remote desktop, I'd like the daemons to detect this and turn off printing (to the now killed terms) but keep on running in normal (silent) daemon mode.  Best of all, the programs could recheck for a desktop occasionally and resume printing by opening new terminals.
Is this possible?  Any coding suggestions?
Thanks in advance.

A: You can use the isatty function. Detect if stdin is a terminal or pipe?
#include <stdio.h>
#include <io.h>

//...

if (isatty(fileno(stdin)))
    printf( "stdin is a terminaln" );
else
    printf( "stdin is a file or a pipen");

You can find more information at http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_12.html
Some more code: http://pastebin.com/S3Lr9tik

A: The traditional solution for this problem is an option in the command
line.  Such programs will typically demonize themselves unless given a
special debug option telling them not to.
Another solution would be to use a shell script to start the program as
a demon, via the nohup command (and redirecting standard input and
output to /dev/null).
As for determining whether your managing terminal is local or not, it
could be difficult; both X and telnet use virtual terminals, so if
you're running under X, you may not be able to distinguish between a
telnet session and a local xterm window.  Still, it might be worth
trying... Under Linux, /proc/<procid>/fd/0 is a symbolic link to the
device connected to standard in (fd 0): using something like readlink,
you should be able to determine the actual name.  Or fstat will give
you the major and minor numbers of the device.  Given these, you might
be able to determine which is which.  If your local terminal is not
under X, but a real terminal, it will definitely have a different minor
number than a pseudo-terminal.  For xterms, it's possible that the minor
numbers of the pseudo-terminals fall in different ranges, or even that
there are distinct sets of pseudo-terminals for remote links and for X;
you'll probably have to experiment some, and there might be no working
solution.  (For starters, to tty at each terminal, and see what it
says.  I don't have local access to a Linux machine to check, but I seem
to remember that on Solaris, X terminals had names like /dev/ttyxx; my
remote terminals on Linux here are /dev/pts/xx.  (Where xx is a
number in each case.)


text:
Q: Change the img source based on a specific image I have a page that has several icon images that need changing. I cannot get to the images by ID as they are generated by the server so always change, but I can get to them by a class name.
So I want to change say just 4 of the several icon images on the page by getting the image source and checking it matches the criteria of the image I want to change and then swap in the new icon image.
I have some clunky versions in javascript and JQuery but I'm really looking for a slick version that's functional and simple.
I did find this worked fine for 4 separate images needing changing in multiple locations:
 function changeArrow() {
            $('img[src="chevron-orange-round-down.jpg"]').attr('src', 'chevron-blue-round-down.jpg')
            $('img[src="chevron-orange-round-up.jpg"]').attr('src', 'chevron-blue-round-up.jpg')
            $('img[src="chevron-orange-round-left.jpg"]').attr('src', 'chevron-blue-round-left.jpg')
            $('img[src="chevron-orange-round-right.jpg"]').attr('src', 'chevron-blue-round-right.jpg')
        }

I expected that I'd need a loop such as .each as suggested below but this changed all instances of image that met the criteria.

A: You can set the src attr $('.image').attr('src', 'val');
or by a simple loop
$('.image').each(function(i, obj) {
    if($(this).attr('src')=='some criteria')
    {
    $(this).attr('src', 'val');
    }
});


text:
Q: Codeigniter - Bootstrap Modal - passing data I am pretty new to Codeigniter and aiming to follow best practice as I learn. Currently I have a table that is generated via DB
HTML Table

        <?php echo $gal['name']; ?>

      <?php echo $gal['clientName']; ?>

<?php endforeach; ?>

The Modal

        <button type="button" class="close" data-dismiss="modal">×</button>

Edit Gallery

<?php echo form_open('url'); ?>

            <?php print_r($galleryName); ?>

                <?php
                    $galleryName = array(
                        'id'            => 'galleryName',
                        'name'          => 'galleryName',
                        'placeholder'   => 'Gallery Name',
                        'required'      => 'required',
                    );
                    echo form_label('Gallery Name:', 'galleryName');
                    echo form_input($galleryName);
                ?>

    Close
    Next

The link calls a bootstrap modal where I want to pass the data for the selected gallery. I know that I can pass the data via jQuery, but is it possible to keep this modal in the MVC framework and if yes how does one go about calling the controller via the modal link?
Thanks so much on the help, and would be happy to accept any suggestions on resources for CodeIgniter. I am currently working through the Nettuts videos, though they are dated,and also  working through the user guide.

A: i really think you are misunderstanding what modal is and what a controller is, you can't do this without ajax call:   how does one go about calling the controller via the modal link
what i usually do is to create a view/modals/ folder then put there all my bootstrap modals so for example:
application/views/modals/my_modal_form.php

and that will looks as you shown, inside:

        <button type="button" class="close" data-dismiss="modal">×</button>

Edit Gallery

<?php echo form_open('url'); ?>

            <?php print_r($galleryName); ?>

                <?php
                    $galleryName = array(
                        'id'            => 'galleryName',
                        'name'          => 'galleryName',
                        'placeholder'   => 'Gallery Name',
                        'required'      => 'required',
                    );
                    echo form_label('Gallery Name:', 'galleryName');
                    echo form_input($galleryName);
                ?>

    Close
    Next

so when i need that single modal i just load it inside the main controller view i want to show up that modal doing simply:

    <?php echo $this->load->view('modals/my_modal_form'); ?>

        <?php echo $gal['name']; ?>

      <?php echo $gal['clientName']; ?>

<?php endforeach; ?>

A: Ajax is the way to go, i made a template library in wich i load all my modals so they can be called by javscript from anywhere on the app, then use ajax to submit the forms


text:
Q: JSON parse error: Cannot construct instance of `com.tess4j.rest.model.Image` (although at least one Creator exists): I have JSON parse error of

JSON parse error: Cannot construct instance of `com.tess4j.rest.model.Image` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.tess4j.rest.model.Image` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1')\n at [Source: (PushbackInputStream); line: 2, column: 8] (through reference chain: java.util.LinkedHashMap[\"id\"])

and unable to solve this once .
CLASS:
public class Image {
    @Id
    private String id;
    private String userId;
    @JsonProperty("image")
    private  byte[] image;
    private String extension;
    private String text;
//get & setters }

CONTROLLER:
 @RequestMapping(value = "ocr/v1/upload", method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public Status doOcr( @RequestBody Map<String, Image> image ) throws Exception {
try {
  ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(((Image) image).getImage()));
               Tesseract tesseract = new Tesseract(); // JNA Interface Mapping
                String imageText = tesseract.doOCR(ImageIO.read(bis));
                ((Image) image).setText(imageText);
                repository.save(image);
                LOGGER.debug("OCR Result = " + imageText);
            } catch (Exception e) {
                LOGGER.error("TessearctException while converting/uploading image: ", e);
                throw new TesseractException();
            }
            return new Status("success");       }

 @RequestMapping(value = "ocr/v1/images/users/{userId}", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public List<Image> getUserImages(@PathVariable String userId) throws Exception {
            List<Image> userImages = new ArrayList<>();
            try {
                userImages = repository.findByUserId(userId);
            } catch (Exception e) {
                LOGGER.error("Exception occurred finding image for userId: {} ", userId, e);
                throw new Exception();
            }            return userImages;        }

TEST CASE:
@Test
    public void testDoOcr() throws IOException {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        Image image = new Image();
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("eurotext.png");
        image.setUserId("arun0009");
        image.setExtension(".png");
        image.setImage(Base64.encodeBase64(IOUtils.toByteArray(inputStream)));
        String response = given().contentType("application/json").headers(headers).body(image).when().post("http://localhost:8080/ocr/v1/upload").then()
            .statusCode(200).extract().response().body().asString();
        System.out.println(response);
    }

    @Test
    public void testGetUserImages() throws IOException {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        String response = given().contentType("application/json").headers(headers).when()
            .pathParam("userId", "arun0009").get("http://localhost:8080/ocr/v1/images/users/{userId}")
            .asString();
        System.out.println(response);
    }

JSON

{
    "id": "1",
    "userId": "arun0009",
    "extension": ".png",
    "text" : null,
    "image" : "ENCODE DETAILS OF IMAGe"
}

TRIED out with different json format and added json dependency in build gradle  but the same error repeat. UNABLE TO SOLVE.
image


text:
Q: Issue with click-drag-select in text input field also scrolls parent element, webkit bug or feature? There's a weird behavior that I've been experiencing with only the webkit browsers since last year, and it is driving me nuts.
I've tried doing searches on this, but I don't seem to be able to hit the keywords relating to this issue.
I have a html structure as below:

long line

<input type="text" value=""/>

long line

You can visit the live example in the jdfiddle link:
jsfiddle
For me, using Chrome(18), when one clicks and drag-selects text in the text input field out of the input box, you are able to "scroll" the parent element, although the CSS overflow is set to hidden.
You can try it from the fiddle by click select-dragging right, top, bottom, left. Works wonders.
More complex html structure yields more bizzare scrolling behaviors. In fact, I can almost do a slide show animation with elements sliding in and sliding out in sequence, just by drag selecting.
This behavior isn't experienced in firefox, fortunately.
Is anyone experiencing this behavior as well?
Is this supposed to be a feature of webkit?
Does anyone knows how to disable this "scrolling" behavior?
Thanks!
edit:
Thanks to @PhilipK, he has found a related post with a javascript solution answered below.
As my webpage is heavy with javascript I would like to find out if there are there any possible CSS solutions.
edit2:
Thanks to @tiffon, he found another javascript solution. His solution could be implemented in CSS (but with some limitations to mouse events, so the CSS solution is kind of incomplete).

A: I think abusing pointer-events: none; might be another option:
Dupe question: https://stackoverflow.com/a/13897395/1888292
http://jsfiddle.net/7CuBV/21/

A: So this worked for me - see here - basically listen to the onscroll event and set both scrollTop and scrollLeft to 0.

A: I found this problem too, after a bit of experimentation I removed an overflow:hidden from one of the parent divs (the very outer div which was scrolling), and it appears to have solved it. I wasn't using any iframes.

A: I know this an old thread, but I've just faced the same problem.
I created this fix:
// DISABLE INPUT DRAG SCROLL (CHROME BUG FIX)
var disableScrollDrag = false;
$('input, select, textarea').unbind('mousedown').mousedown(function(e) {
    disableScrollDrag = true;
    $(this).css('pointer-events', 'none').addClass('disable-scroll-drag');
});

$('body').mousemove(function() {
    if (disableScrollDrag === true) {
        $('.disable-scroll-drag').each(function () {
            $(this).css('pointer-events', 'auto');
        });
        disableScrollDrag = false;
    }
});

A: Just wrestled with this strange one for the first time. I found that if I set the width of the text field to something less-than-or-equal-to the container, the parent element didn't scroll in relation to the text input value.

A: The example linked to above gives the basic idea, but it's about an iframe and can be a little confusing to implement on a text input within a div, which is what I (and the original poster) were facing.
Here's what I ended up doing, using jquery;
$('body').on('select', '.my_text_input', function(e) {
        $('.div_that_was_moving_weirdly').scrollLeft(0);
         return false;
    });

This is still imperfect, as there will be a jarring scroll over and then jump back, since the select event doesn't seem to kick in until you're done selecting. I tried various events but this is the best I could do.


text:
Q: What would you do to avoid conflicting data in this database schema? I'm working on a multi-user internet database-driven website with SQL Server 2008 / LinqToSQL / custom-made repositories as the DAL. I have run across a normalization problem which can lead to an inconsistent database state if exploited correctly and I am wondering how to deal with the problem.
The problem: Several different companies have access to my website. They should be able to track their Projects and Clients at my website. Some (but not all) of the projects should be assignable to clients.
This results in the following database schema:
**Companies:**
ID
CompanyName

**Clients:**
ID
CompanyID (not nullable)
FirstName
LastName

**Projects:**
ID
CompanyID (not nullable)
ClientID (nullable)
ProjectName

This leads to the following relationships:
Companies-Clients (1:n)
Companies-Projects (1:n)
Clients-Projects(1:n)

Now, if a user is malicious, he might for example insert a Project with his own CompanyID, but with a ClientID belonging to another user, leaving the database in an inconsistent state.
The problem occurs in a similar fashion all over my database schema, so I'd like to solve this in a generic way if any possible. I had the following two ideas:

*

*Check for database writes that might lead to inconsistencies in the DAL. This would be generic, but requires some additional database queries before an update and create queries are performed, so it will result in less performance.

*Create an additional table for the clients-Projects relationship and make sure the relationships created this way are consistent. This also requires some additional select queries, but far less than in the first case. On the other hand it is not generic, so it is easier to miss something in the long run, especially when adding more tables / dependencies to the database.
What would you do? Is there any better solution I missed?
Edit: You might wonder why the Projects table has a CompanyID. This is because I want users to be able to add projects with and without clients. I need to keep track of which company (and therefore which website user) a clientless project belongs to, which is why a project needs a CompanyID.

A: I'd go with with the latter, having one or more tables that define the allowable relationships between entities.

A: Note, there's no circularity in the references you have, so the title is misleading.
What you have is the possibility of conflicting data, that's different.

Why do you have "CompanyID" in the project table? The ID of the company involved is implicitly given by the client you link to. You don't need it.
Remove that column and you've removed your problem.
Additionally, what is the purpose of the "name" column in the client table? Can you have a client with one name, differing from the name of the company?
Or is "client" the person at that company?

Edit: Ok with the clarification about projects without companies, I would separate out the references, but you're not going to get rid of the problem you're describing without constraints that prevent multiple references being made.
A simple constraint for your existing tables would be that not both the CompanyID and ClientID fields of the project row could be non-null at the same time.

A: If you want to use the table like this and avoid the all the new queries just put triggers on the table and when user tries to insert row with wrong data the trigger with stop him.
Best Regards,
Iordan

A: My first thought would be to create a special client record for each company with name "No client". Then eliminate the CompanyId from the Project table, and if a project has no client, use the "No client" record rather than a "normal" client record. If processing of such no-client's is special, add a flag to the no-client record to explicitly identify it. (I'd hate to rely on the name being "No Client" or something like that -- too fuzzy.)
Then there would be no way to store inconsistent data so the problem would go away.

A: In the end I implemented a completely generic solution which solves my problem without much runtime overhead and without requiring any changes to the database. I'll describe it here in case someone else has the same problem.
First off, the approach only works because the only table that other tables are referencing through multiple paths is the Companies table. Since this is the case in my database, I only have to check whether all n:1 referenced entities of each entity that is to be created / updated / deleted are referencing the same company (or no company at all).
I am enforcing this by deriving all of my Linq entities from one of the following types:

*

*SingleReferenceEntityBase - The norm. Only checks (via reflection) if there really is only one reference (no matter if transitive or intransitive) to the Companies table. If this is the case, the references to the companies table cannot become inconsistent.

*MultiReferenceEntityBase - For special cases such as the Projects table above. Asks all directly referenced entities what company ID they are referencing. Raises an exception if there is an inconsistency. This costs me a few select queries per CRUD operation, but since MultiReferenceEntities are much rarer than SingleReferenceEntities, this is negligible.
Both of these types implement a "CheckReferences" and I am calling it whenever the linq entity is written to the database by partially implementing the OnValidate(System.Data.Linq.ChangeAction action) method which is automatically generated for all Linq entities.


text:
Q: Return Json in login_check im new with symfony and i'd like to return a json when a user make login, but i dont know how.
I'm using a simple form with login_check to authenticate the user in my database, i just want to return this:
$response = new JsonResponse('borala', 200,  array(
            'Access-Control-Allow-Origin'  => '*',
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept',
            'Content-Type' => 'application/json'));

A: Because login_check is a 'phantom' route that doesn't actually correspond to a contoller, you'll need to use a Custom Authentication Handler.  Here's how I've done it (simplified):
The Handler
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
    protected $router;
    protected $session;

    public function __construct( RouterInterface $router, Session $session )
    {
        $this->router  = $router;
        $this->session = $session;
    }

    public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
    {
        if( $request->isXmlHttpRequest() )
        {
            $response = new Response( json_encode( array( 'success' => false, 'message' => $exception->getMessage() ) ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;
        }

        $request->getSession()->set( Security::AUTHENTICATION_ERROR, $exception );

        return new RedirectResponse( $this->router->generate('site_login') );
    }

    public function onAuthenticationSuccess( Request $request, TokenInterface $token )
    {
        if( $request->isXmlHttpRequest() )
        {
            $response = new Response( json_encode( array( 'success' => true ) ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;
        }

        $url = ( $this->session->get('_security.main.target_path') ) ? $this->session->get('_security.main.target_path') : $this->router->generate('home') ;

        return new RedirectResponse( $url );
    }

Set the Handler as a Service:
security.auth_handler:
    class:      MyNamespace\Service\Security\Listeners\AuthenticationHandler
    public:     false
    arguments:  ['@router','@session']

Set the Handler against the Firewall:
    site:
        ...
        form_login:
            login_path:             /login
            check_path:             /check_login
            success_handler:        security.auth_handler
            failure_handler:        security.auth_handler
        logout:
            path:                   /logout
            target:                 /


text:
Q: Unity On Click error TowerSelection class I think is working fine.
 public class TowerSelection : MonoBehaviour {

        public GameObject towerType;

        void Start()  {}

        void Update() {
        }

        public void TowerType (GameObject prefab) {
            towerType = prefab;
            Debug.Log (towerType.name);
        }

    }

TowerSpot class,  the problem is in OnMouseUp Method at  " prefabTower = GameObject.FindObject ... "
public class TowerSpot : MonoBehaviour {

    private GameObject prefabTower;

    private GameObject tower;
    private int gold;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void OnMouseUp()
    {
        if (placeTower())
        {

            **prefabTower = GameObject.FindObjectOfType<TowerSelection>().towerType;**

            Debug.Log (prefabTower.name);

            gold = GameManager.Manager.getGold();

            if (gold > 0)
            {
                Instantiate( prefabTower , this.transform.position, this.transform.rotation);
                GameManager.Manager.currentGold(-20);
            }
            else
            {
                Debug.Log("No hay suficiente dinero");
            }

        }

    }

    private bool placeTower()
    {
        return tower == null;
    }
}

This is the line I think it is returning "NULL", I have tried doing a lot of things but the error continues.
prefabTower = GameObject.FindObjectOfType<TowerSelection>().towerType;

The error is this one, Object reference not set to an instance of an object.
What I am doing is a tower defence game, I have 2 buttons depending on what tower I am selecting, tower 1 or tower 2, using On Click in the inspector I call the TowerType method and I add the tower's Prefab, but when using the method FindObjectOfType<>() It returns null everytime, and I dont know why.
Any idea?

A: FindObjectOfType looks in the scene and returns the first occurrence of type T. Clearly there are no T objects in the scene (no towers) therefore the assumption that one must found is wrong, hence trying to retrieve the property produces the error.
Why are you doing this anyway? If you are trying to create a tower, that prefab should either be references in the script directly (assigned to a public var in the inspector) or fed via loading a resource at runtime.


text:
Q: In MIPS what should I return when the answer is null I have a MIPS function to find a character in a string. I'm not sure what to return if the character isn't in the string. In c++ I might return -1, but I'm not sure that's the correct convention in MIPS. Should I return 0? raise an error? something else?
# return the address of the first occurance of the character in a1 in the string at the address in a0
FIND:
move $t0,$a0    # t0 has address
LOOP:
lb $t1,0($t0)   # load current char into mem
beq $t1,$a1,END # check if the current char is the right one
beq $t1,$zero,FAIL # end of string
addi $t0,$t0,1  # move to next char
j LOOP
FAIL:
li $t0,-1  # return -1 as the address
END:
move $v0,$t0    # return
jr $ra


text:
Q: failed run Postgres in alpine dockerfile i am trying to deploy my Go app with Alpine in docker, I was able to use it on my Mac and then going to Production with Centos 8 got issues
here is my Dockerfile:
FROM golang:alpine

RUN apk add --no-cache postgresql

RUN apk update && apk add --no-cache gcc && apk add --no-cache libc-dev && apk add --no-cache --update make

# Set the current working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. they will be cached of the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the WORKDIR inisde the container
COPY . .

# Build the Go app
RUN go build .

RUN rm -rf /usr/local/var/postgres/postmaster.pid

// this commands below like "psql -c ;'DROP DATABASE IF EXISTS prod'"
// "psql -c ;'CREATE USER prod'"
RUN make setup

# Exporse port 3000 or 8000 to the outisde world
EXPOSE 3000..

CMD ["make", "run" ]

then i got error:
psql: error: could not connect to server: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

on my make setup i do the migration, create user, database
can make SUPERUSER on psql for that alpine also??
what u can see on the above syntax, is there any wrong and how to correct it? I have stuck from yesterday

A: Delete your original docker file's from 8th line to 20th and add these.
If your folder structure like this :
- directory
    |
    -> Dockerfile
    -> go.mod
    -> go.sum
    -> go source files

# Copy go mod and sum files
COPY . /app

# Set the current working Directory inside the container
WORKDIR /app

RUN go mod download

RUN go build .

A: You cannot run database commands in a Dockerfile.
By analogy, consider the go generate command: you can embed special comments in your Go source code that ask the Go compiler to run programs for you, typically to generate other source files.  Say you //go:generate: psql ... in your source code and run go generate ... && go install .  Now you run that compiled binary on a different system.  Since you're not pointing at the same database any more, the database setup is lost.
In the same way, a Dockerfile produces a compiled artifact (in this case the Docker image) and it needs to run independently of its host environment.  In your example you could docker push the image you built on MacOS to a registry, and docker run it from the CentOS host without rebuilding it (and that's probably better practice for a production system).
For the specific commands you show in the question, you could put them in a database container's /docker-entrypoint-initdb.d directory, or otherwise just run them once pointing at your database.  For more general-purpose database setup you might look at running a database migration tool at application startup, either in your program's main() function or in a wrapper entrypoint script.


text:
Q: Creating new numpy matrix from list of rows of existing matrix I have a 2D numpy array A, and a list x. The elements of x are indices of the rows of A. I want to create a new matrix B, by taking the rows of A as indicated by x. How can I do this?

A: You can pass x as an argument when indexing A to create your new matrix B as below. See the docs here.
import numpy as np

A = np.arange(25).reshape((5,5))

x = [1, 2, 4]

B = A[x]

print(B)
# [[ 5  6  7  8  9]
# [10 11 12 13 14]
# [20 21 22 23 24]]


text:
Q: layout:false not working in express.js 3? i try to skip rendering the layout when rendering a view in express.js. I use jade as my template language. the code i use:
res.render("show", { job: data, layout: false });

any advice? it keeps rendering the layout....
thanks

A: I am not 100% sure but I think that's the default now.
Otherwise try:
app.set('view options', {
    layout: false
});


text:
Q: calculate the probability that more than three claims will be received during a consecutive two-month period, given that...
Attempt
Let $N_1$ and $N_2$ be the number of claims received in months 1 and 2. We want to calculate $P(N_1+N_2>3 | N_1 < 2 )$.
First, we calculate $P(N_1 + N_2 > 3 \cap N_1 < 2 )$
Now, clearly $N_1$ can be only $1$ 0r $0$, thus can write
$$ P(N_1 + N_2 > 3 \cap N_1 < 2 ) = P(N_2 > 2 \cup N_2 > 1 ) = P(N_2>2) + P(N_2>1) = 2 - P(N_2 \leq 2)-P(N_2\leq1) = 2 - P(N_2= 2)-2P(N_2=1)-2P(N_2=0) $$
We thus obtain that
$$ P(N_1 + N_2 > 3 \cap N_1 < 2 ) = 2 - \frac{2}{3^3} - \frac{4}{3^2} - \frac{4}{3} $$
Now, we calculate $P(N_1<2)$ this is just
$$ P(N_1=0) + P(N_1=1) = \frac{2}{3} + \frac{2}{3^2} = \frac{24}{3^3} $$
Hence,
$$P(N_1+N_2>3 | N_1 < 2 ) = \frac{ 2 - \frac{2}{3^3} - \frac{4}{3^2} - \frac{4}{3} }{  \frac{24}{3^3} } = \frac{1}{6}$$
now, the answer keys gives $\boxed{ans: 1/54}$. what am I doing wrong in this problem?

A: By the definition of conditional probability, we have
$$
\mathbb P(N_1+N_2>3\mid N_1<2) = \frac{\mathbb P(N_1+N_2>3,N_1<2)}{\mathbb P(N_1<2)}. $$
Now,
$$
\mathbb P(N_1<2) = \mathbb P(N_1=0)+\mathbb P(N_1=1) = \frac23+\frac29 = \frac89,
$$
and
\begin{align}
P(N_1+N_2>3,N_1<2) &= \mathbb P(N_1+N_2> 3,N_1=0)+\mathbb P(N_1+N_2> 3,N_1=1)\\
&= \mathbb P(N_2>3)\mathbb P(N_1=0) + \mathbb P(N_2> 2)\mathbb P(N_1=1)\\
&= (1 - (\mathbb P(N_2=0) + \mathbb P(N_2 =1)+\mathbb P(N_2=2)+\mathbb P(N_2=3))\mathbb P(N_1=0) + (1 - (\mathbb P(N_2=0) + \mathbb P(N_2 =1)+\mathbb P(N_2=2))\mathbb P(N_1=1)\\
&= \left(1 - \left(\frac23+\frac29+\frac2{27}+\frac2{81} \right)\right)\cdot \frac23 + \left(1 - \left(\frac23+\frac29+\frac2{27} \right)\right)\cdot \frac29\\
&= \frac4{81},
\end{align}
so that
$$
\mathbb P(N_1+N_2>3\mid N_1<2) = \frac4{81}\cdot\frac98 = \frac1{54}.
$$


text:
Q: iPhone Orientation Change I know how to do an orientation change, but lets say you have a view with buttons, labels, ect.  The autoresizing distorts and makes the view look strange.  What's the accepted way to do this, do I just create a portrait and landscape view.  If so where would I actually do the swapping of these views.

A: Do all kind of resizing  and reposition in your layoutSubviews method of UIView.
Once the orientation is changed, your layoutSubviews would be called then you can know the current orientation by using UIDevice class. and reposition your views child accordingly
UIDevice property to be used for getting current orientation .
@propertyic,readonly) UIDeviceOrientation orientation

A: My sandbox app:
https://github.com/comonitos/programatical_device_orientation
The solution is easy


text:
Q: All max elements and their postition of array So, for example, I have array: [1, 4, 9, 3, 9]
I need to find all max elements [9, 9] and their index [2, 4]
How can I do this? In C language
int i, pom, max;
max=*gradovi;
for(i=0;i<n;i++) {
  if(*(gradovi+i)>max) {
    max=*(gradovi+i);
    pom=i;
  }
  if(*(gradovi+i)==max) {
    pom=i;
  }
}
return pom;

I need postions of all max elemenents, but this print just last

A: In any case you need a container that will store the indices of the elements with the maximum value.
You can allocate memory dynamically for such a container.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>

size_t max_elements( const int a[], size_t n, size_t **result )
{
    *result = NULL;
    size_t count = 0;

    if ( n != 0 )
    {
        size_t max_i = 0;
        count = 1;

        for ( size_t i = 1; i < n; i++ )
        {
            if ( a[max_i] < a[i] )
            {
                max_i = i;
                count = 1;
            }
            else if ( !( a[i] < a[max_i] ) )
            {
                ++count;
            }
        }

        *result = malloc( count * sizeof( size_t ) );

        if ( *result != NULL )
        {
            for ( size_t i = max_i, j = 0; i < n && j < count; i++ )
            {
                if ( !( a[i] < a[max_i ] ) ) ( *result )[j++] = i;
            }
        }
    }

    return count;
}

int main(void)
{
    int a[] = { 1, 4, 9, 3, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t *result = NULL;

    size_t count = max_elements( a, N, &result );

    for ( size_t i = 0; i < count; i++ )
    {
        printf( "%zu: %d, ", result[i], a[result[i]] );
    }

    putchar( '\n' );

    free( result );

    return 0;
}

Its output is
2: 9, 4: 9,

If the returned value from the function is not equal to 0 but the pointer result was set to NULL then it means that there was a memory allocation error. You can check such a situation.

A: I'm stupid, it's simple solution:
void maks(int *gradovi, int n){
int i, pom, max;
max=*gradovi;
for(i=1;i<n;i++){
    if(*(gradovi+i)>max){
        max=*(gradovi+i);
    }
    if(*(gradovi+i)==max){
        pom=i;
        printf("Najvise zarazenih je u gradu sa indeksom: %d\n", pom);
    }
}

}


text:
Q: Communicating with an unsecure device: Security by Abstraction Vs HTTP HTTPS callback I have a web-server with an SSL certificate, and an unsecured device on a GSM/GPRS network (arduino MKR GSM 1400). The MKR GSM 1400 library does not feature a SSL server, only an SSL Client. I would prefer to use a library if that's possible, but I don't wanna write a SSL Server class. I am considering writing my own protocol, but I'm familiar with HTTPS and will make writing the interface on the webserver side easier.

*

*The GSM Server only has an SSL Client

*I am in control of both devices

*Commands are delivered by a text string

*Only the webserver has SSL

*My C skills are decent at best

I need the SSL Server to be able to send commands to the Arduino Device, but I want these commands to be secured (The arduino device opens and closes valves in a building).

The other option would maybe have some sort of PSK, but I wouldn't know where to start on that. Is there an easy function to encrypt and decrypt a "command string". I also don't want "attackers" to be sending commands that I've sent before.
My Basic question is, does this method provide some reasonable level of security? Or is there some way to do this that I'm not thinking of.

A: While in a perfect world there would be a better approach, you are currently working within the limits of what your tiny system provides.
In this situation I find your approach reasonable: the server simply tells the client using an insecure transport that there is some message awaiting (i.e. sends some trigger message, actual payload does not matter) and the client then retrieves the message using a transport which both protects the message against sniffing and modification and also makes sure that the message actually came from the server (i.e. authentication).
Since the trigger message from the server contains no actual payload (arrival of the message itself is enough payload) an attacker could not modify or fake the message to create insecure behavior in the client. The worst what could happen is that some attacker will either block the client from getting the trigger messages or that the attacker fakes trigger messages even though there is no actual command waiting from the server.
If the last case is seen as a problem it could be dealt with a rate limit, i.e. if server did not return any command although the client received a trigger message than the client will wait some minimum time before contacting the server again, no matter if a trigger message was received or not. The first case of the attacker being able to block messages from the server is harder to deal with since in this case the attacker is likely able to block further communication between client and server too - but this is a problem for any kind of communication between client and server.


text:
Q: New object with name in variable I am trying to initiate an object with a dynamic path. I have the variable $model with the model name.
$model = "foo";
$class = new \Path\To\$model();

I get the error
Parse error: syntax error, unexpected '$model' (T_VARIABLE), expecting identifier (T_STRING)

If I try $class = new \Path\To\{$model}();
I get the error
 Parse error: syntax error, unexpected '{', expecting identifier (T_STRING)

When I try
namespace \App\Models
$class = new $model();

I get the error Class 'foo' not found
When I try $class = new \Path\To\foo(); it works.
Any ideas?

A: Try:
$class = "\Path\To\foo";
$object = new $class();

Or:
use Path\To\foo;
$class = foo::class;
$object = new $class();

A: You can store path in variable:
$path = "\Path\To\\";

and then generate class name like this:
$className = $path.$model;
$class = new $className();


text:
Q: Transitions coupled to different baths in quantum thermodynamics I don't understand the general assumptions made during the separation of a single environment of the open system represented by the energy levels into two baths at two temperatures in the diagram below.
Is it assumed that the frequency $\omega_c$ is absent in the spectrum of the hot bath, $\omega_h$ is absent in the cold bath and $\nu$ absent in both?

This is how I picture it when the reservoirs are photon baths:

Is this corrent? Are these conditions the same for phonon baths, i.e. excitation by collisions?


text:
Q: mouse toggled event isn't responsive on element that supposed to act as nav drop down menu My navbar has 3 elements, image, burger-btn styling, and
 of 3 items.
When my browser width is 700px or below, I'm hiding my
 and the burger-btn element will be in its place. When I click the button I need a drop-down menu that lists out my unordered list. But, my button isn't doing what it's supposed to do.
I tried console.log to check whether my eventListner is picking up the mouse click or not, and my function is fired. I'm getting "clicked" when I click the hamburger element.

const hambrugerBtn = document.getElementById("hamburgur");
const nav_list = document.getElementById("nav_list");

function toggledevent() {
  hambrugerBtn.classList.toggle("show");
  console.log("clicked");
  // hambrugerBtn.style.backgroundColor = "red";
}

hambrugerBtn.addEventListener("click", toggledevent);
.hamburgur {
  border: 0;
  background-color: transparent;
  width: 10px;
}

.nav_list {
  display: none;
}

.nav_list.show {
  display: flex;
  flex-direction: column;
}

@media only screen and (min-width: 700px) {
  .hamburger {
    display: none;
    /* height: 0px; */
  }
  .nav_list {
    display: flex;
    justify-content: flex-end;
    list-style-type: none;
  }
}
<link href="https://use.fontawesome.com/releases/v6.2.0/css/all.css" rel="stylesheet" />

  <button class="hamburgur" id="hamburgur">

      </button>

       About Me

 Profile

 For Contact

A: You made a mistake in the dropdown selector. Give the button the show class, not the drop-down menu that is placed in the code immediately after the button. This is the .show + .nav-list selector.

const hambrugerBtn = document.getElementById("hamburgur");
const nav_list = document.getElementById("nav_list");

function toggledevent() {
  hambrugerBtn.classList.toggle("show");
  console.log("clicked");
  // hambrugerBtn.style.backgroundColor = "red";
}

hambrugerBtn.addEventListener("click", toggledevent);
.hamburgur {
  border: 0;
  background-color: transparent;
  width: 10px;
}

.nav_list {
  display: none;
}

.show+.nav_list {
  display: flex;
  flex-direction: column;
}

@media only screen and (min-width: 700px) {
  .hamburger {
    display: none;
    /* height: 0px; */
  }
  .nav_list {
    display: flex;
    justify-content: flex-end;
    list-style-type: none;
  }
}
<link href="https://use.fontawesome.com/releases/v6.2.0/css/all.css" rel="stylesheet" />

  <button class="hamburgur" id="hamburgur">

      </button>

       About Me

 Profile

 For Contact


text:
Q: Optimal number of components in a beta mixture model This is a well-written blog on how we can fit a mixture of beta distributions to a dataset:
http://varianceexplained.org/r/mixture-models-baseball/
However, it would have been excellent to identify the optimal number of beta distributions one can fit a beta mixture model. I think one could figure this out using AIC/BIC but I am not sure how to do this or if there is already a package (preferably in R) that could do this. Any insights will be much appreciated. Thanks.


text:
Q: Call ViewControllers Method or Segue from App Delegate (Swift) I have created an app that uses storyboard and have successfully created a tableview and detail page which all works.
I would like it so that users swiping the localNotifications can be sent to the correct detail page within the app.
It appears that I can call functions from the ViewController but whenever they refer to themselves to update any details or perform a segue the app crashes.
The code i have in my ViewController is as follows:
func handleMessageNotification (messageID:String)
{
    // this function should act as a conduit for the call from the delegate
    println("notif messageID: \(messageID)");
    self.performSegueWithIdentifier("showMessageDetail", sender: self);
    self.messageView.reloadData();
}

and this is called from my appDelegate
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
  if (application.applicationState == UIApplicationState.Background || application.applicationState == UIApplicationState.Inactive)
    {
        var rootViewController = self.window!.rootViewController
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
        rootViewController?.navigationController?.popToViewController(setViewController, animated: false)
        setViewController.handleMessageNotification(messageID);
  }
}

the println works correctly but performSegue fails (fatal error: unexpectedly found nil while unwrapping an Optional value) and the messageView.reload() fails (same error).
How do I get a notification to fire the app to the correct place upon opening?
This solution 'Get Instance Of ViewController From AppDelegate In Swift' uses much of the same but mine will not allow access to anything with the ViewController.
======= Update - Solution =======
For anyone else with this issue. Following on from what Gabuh had suggested below; the full solution for me was to do the following:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    if (application.applicationState == UIApplicationState.Background || application.applicationState == UIApplicationState.Inactive)
    {
        let navigationController = application.windows[0].rootViewController as UINavigationController;
        navigationController.popToRootViewControllerAnimated(false); // I need to push back to root before performing segue
        let rootViewController = navigationController.visibleViewController;
        rootViewController.performSegueWithIdentifier("showMessageDetail", sender: self);
    }
}

this also allows me to make calls on functions in the view such as in the original example e.g.
rootViewController.handleMessageNotificaion(messageID);

or
rootViewController.messageView.reloadData();

A: You are creating an instance of a new ViewController. And you are trying to call a function on that ViewController, that is trying to perform a segue, when the ViewController is not even displayed. I think that's not going to work...
If you want to perform a segue from your detail view, you have to access to the current instantiated view Controller and perform the segue from it.
If you want to know how to get the instance of the UIViewController that is being displayed, in this post there are several ways that show you how to do it:
Get the current view controller from the app delegate
In pseudo-code, in your appDelegate:
1- get current UIViewController instance (not new one)
2- perfom segue from that view controller (or present modally or whatever transition you want)

A: In Swift 3:
    guard let rvc = self.window?.rootViewController as? VCName else { return }
    rvc.methodInYourVC()

The above assumes

*

*That you don't want to create a whole new instance of VCName, just want a reference to it

*That you know the VC you want to reference is your root VC


text:
Q: Google Translate: Text-to-speech TTS output in mp3 from IME Pinyin input Using Google Translate, it is possible to generate TTS mp3 audio files from English or Chinese input using a simple URL. For example,
URL for English TTS for the word "English":
http://translate.google.com/translate_tts?tl=en&q=English
URL for Chinese TTS for the word 中文:
http://translate.google.com/translate_tts?tl=zh_CN&q=中文
How can I do the same using IME Hanyu Pinyin with tonal notations as input? For example, I want to generate the audio TTS file for zhōng wén (instead of 中文).
I have searched high and low on this website for a solution but was not successful. I do apologise if I have overlooked a solution previously offered here. Thanks


text:
Q: Formula to find out a $b_3, b_4, b_5$ coefficient independent variable for multiple linear regression I have been given this formula to find the coefficients $b_1$ and $b_2$ as in the following image :
$b_1 = \left(\dfrac{r_{y,x_1}-r_{y,x_2}r_{x_1,x_2}}{1-(r_{x_1,x_2})^2} \right) \left( \dfrac{SD_y}{SD_{x_1}}\right)$
$b_2 = \left(\dfrac{r_{y,x_2}-r_{y,x_1}r_{x_1,x_2}}{1-(r_{x_1,x_2})^2} \right) \left( \dfrac{SD_y}{SD_{x_2}}\right)$
My question is what would the formula for coefficient $b_3, b4$ and $b_5$ look like. I have been unable to find this whilst searching the web.
Thanks.


text:
Q: Firestore query with not-in and array-contains I would like to know if I can combine not-in and array-contains in a query in firestore?
I know it's impossible to combine not-in with array-contains-any.
This an example of what want to do:
await ref.where('User','not-in', [['uid']]).get()


text:
Q: Matching tag in HTML keyboard shortcut Is there a shortcut in Visual Studio (2008) that will allow me to jump to matching HTML tag... as CTRL+] does for matching braces when you are in code view?
Example:

Cursor is on closing table tag and I would like to press something like CTRL+] to jump to opening table tag.
Any ideas?

A: After http://www.jetbrains.com/resharper/ is installed CTRL+] for matching braces works in HTML edit mode...

A: I search and couldn't found direct short cut. But you can use..
If you want to go starting matching HTML tag, then follow below steps.

*

*Place cursor at ending matching HTML tag.

*Press Ctrl+M+M [To Collapse entire tag]

*Press Home Key [To place cursor at before starting tag]

*Press Ctrl+M+M [To Expand entire tag]

If you want to go ending matching HTML tag, then follow below steps.

*

*Place cursor at starting matching HTML tag.

*Press Ctrl+M+M [To Collapse entire tag]

*Press End Key [To place cursor next to ending tag]

*Press Ctrl+M+M [To Expand entire tag]

A: Ok here is the answer  as macro which i've built which does it (toggle ) including go to focus :
Here is the demo :

And here is the code  , enjoy !
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Windows.Forms

Public Module Module2
    Sub beginToEnd()

        'Place cursor somewhere in beginning tag, run macro, to select from beginning to End Tag

        DTE.ActiveDocument.Selection.SelectLine()
        Dim objSel As TextSelection = DTE.ActiveDocument.Selection
        Dim topPoint As TextPoint = objSel.TopPoint
        Dim lTopLine As Long = topPoint.Line
        objSel.GotoLine(lTopLine, False)
        '  DTE.ActiveDocument.Selection.StartOfLine()
        DTE.ActiveDocument.Selection.SelectLine()
        Dim line1 As String = DTE.ActiveDocument.Selection.Text()
        If InStr(line1, "</") Then

            ' MsgBox(line1)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ActiveDocument.Selection.EndOfLine()
            DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, True)
            objSel.GotoLine(lTopLine, False)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")

        Else

            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ActiveDocument.Selection.EndOfLine(False)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")

        End If
        DTE.ActiveDocument.Selection.SelectLine()
        Dim line2 As String = DTE.ActiveDocument.Selection.Text()
        Dim objSel3 As TextSelection = DTE.ActiveDocument.Selection
        Dim topPoint3 As TextPoint = objSel3.TopPoint
        Dim lTopLine3 As Long = topPoint3.Line
        objSel.GotoLine(lTopLine3, False)
        DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, False)

    End Sub

End Module

A: In Visual Studio 2012, in 'source' view, right at the bottom of the document window, there is a breadcrumb-trail-style description of the DOM. You can click at any point to select.
It's not a keyboard shortcut, but it does give you the selection behaviour you're looking for, and you don't need to match tags by eye any more.
(Edit)  If you hover over the breadcrumb, you will see a dropdown arrow. Click the down arrow and click  "Select Tag Content". Then you can just scroll up or down until you find text that is not highlighted.

A: This totally works when you open a HTML file with the XML Editor (Right click -> Open With... -> XML Editor).

A: In Visual Studio 2015, this is now supported with the usual bracket matching keystrokes;

*

*ctrl+] jumps from the start tag to the end tag.

*ctrl+shift+] selects everything between the start tag and the end tag.

It seems pretty sensitive, though, and to select an entire tag and its contents you need to start right on the < that opens the tag.

A: I am using Visual Studio Code in Windows 10. Currently version 1.34.0. To jump to the matching html tag, I set it up through File -> Preferences -> Keyboard Shortcuts. Look for "Matching Tag: Jump to matching tag" .. There's a + when you hover it, then I set keybinding Shift + ] .. you can set your own as long as it isn't used for another function. So now I am able to jump to the closing HTML tag. Hope this helps.

A: *

*SOLUTION WORK FOR ME:
press ctrl+shift+p this opens command pallete  , after that write emmet:go to matching pair in search bar.
Click on setting icon and set your shortcut key(if you want). I uses ctrl+shift+/ and press enter.
It definitely works.

A: No, you can't do that in Visual Studio 2010, not in the current version or in older ones. Maybe the next version will have this feature.

A: Jump to matching tag functionality is easily achieved with this simple extension: VSCode Highlight Matching Tag
Once installed, you may use Command Palette (Win/Linux: Ctrl+Shift+P; Mac: Cmd+Shift+P) and search command name: Jump to matching tag. Or configure keyboard shortcut for that command. Here is my example of key binding for shift+5 in my case:
  {
    "key": "shift+5",
    "command": "highlight-matching-tag.jumpToMatchingTag",
    "when": "editorLangId == html"
  }


text:
Q: Jquery This is Null When Used in Ajax Generated Content I have a jquery function with the following structure
function StartSong(e, sender) { }

I call it with the following html

When the page is loaded some of the songs are shown, and when clicked to play the sender object in the function contains this data, which is expected
({jQuery18307744602853717308:8, sizcache04790260167065139:"6 18 0", sizset:false})

Although when I load more songs through ajax and append the html to the page (the same html as above) and the function is called through a click the sender variable in the function is null.
Does anyone see any reason for this?

A: Try this, change onclick="StartSong(event, this)" to onclick="StartSong(event)" and function StartSong(e, sender) to function StartSong(e) and then use e.target instead of sender. Below is the snippet.
Your HTML,

And your js,
function StartSong(e) {
    var sender = e.target; //now use sender as you have been using.
}


text:
Q: How to undo drawing in paintComponent in Java Graphics Hello im making a simple web broswer and im using Java Graphics library to render the html elements,
by printing some 2D graphics on a JPanel (HTML Canvas) using the paintComponent methond
but the problem is each time I call my web page method (print on the jpanel) all the components are printed underneath what has been printed already, (let's say I change the url and load a differed web page it gets printed on underneath the previous one) but I want the HTML Canvas to be cleared every time before it gets printed on, I almost tried everything I found on the web nothing helped my case, please help me.
public class HtmlCanvas extends JPanel  {

    private boolean drawLineMark;
    private int lineMarkX;

    private List<HtmlComponent> htmlComponents;

    public void setHtmlComponents(List<HtmlComponent> htmlComponents) {
        this.htmlComponents = htmlComponents;
        drawLineMark = false;
        lineMarkX = 0;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.WHITE);
        // Turn on font aliasing (smoothing)
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
           RenderingHints.VALUE_ANTIALIAS_ON);

            if (htmlComponents != null)
                drawHtmlComponents(g);
            if (drawLineMark)
                drawLineMark(g, lineMarkX);
        }

    }

    private void drawHtmlComponents(Graphics g) {

        int xLoc = X_MARGIN;
        int yLoc = Y_MARGIN;

        try {
            for (HtmlComponent component : htmlComponents) {
                g.setColor(component.getColor());
                if (component instanceof HtmlTag) {
                    xLoc = Y_MARGIN;
                    drawTag(g, (HtmlTag) component, yLoc);
                    yLoc += component.getHtmlComponentHeight();
                } else if (component instanceof HtmlFragment) {
                    drawFragment(g, (HtmlFragment) component, xLoc, yLoc);
                    xLoc += component.getHtmlComponentWidth();
                } else if (component instanceof HtmlLabel) {
                    drawLabel(g, (HtmlLabel) component, xLoc, yLoc);
                }
                else if (component instanceof HtmlLink) {
                    drawLink(g, (HtmlLink) component, xLoc, yLoc);
                }

            }
        } catch (ConcurrentModificationException ignored) {
        }
    }

    private void drawFragment(Graphics g, HtmlFragment htmlFragment, int xLoc, int yLoc) {

    }... other drawing functions.

}


text:
Q: how to get the set of array_push data in real json format? This is my rest apis data binding from database which is bined data with array notations..
        $result = array('status' => "Success");
        $result['data']['skill'] = array();
            foreach($skill->processApi('user_skills',true) as $row_data){
                    array_push($result['data']['skill'],$row_data);
            }

        $result['data']['user_projects'] = array();
            foreach($project->processApi('user_projects',true) as $row_data){
                    array_push($result['data']['user_projects'],$row_data);
            }

        $result['data']['user_experience'] = array();
            foreach($experience->processApi('user_experience',true) as $row_data){
                    array_push($result['data']['user_experience'],$row_data);
            }

        $result['data']['user_education'] = array();
            foreach($education->processApi('user_education',true) as $row_data){
                    array_push($result['data']['user_education'],$row_data);
            }

        $result['data']['user_basic_details'] = array();
            foreach($basic_info->processApi('user_basic_details',true) as $row_data){
                    array_push($result['data']['user_basic_details'],$row_data);
            }

        $result['data']['user_contact_details'] = array();
            foreach($contact_info->processApi('user_contact_details',true) as $row_data){
                    array_push($result['data']['user_contact_details'],$row_data);
            }

        $this->response($this->json($result), 200);

It gives json data as like bellow which is contained array notation([,]) because of array_push method in php
{
  "status": "Success",
  "data": {
    "skill": [
      {
        "skill_id": "2",
        "skill_title": "Sports"
      }
    ],
    "user_projects": [
      {
        "project_title": "workless",
        "project_id": "1",
        "date_start": "2015-08-28",
        "date_end": "2016-01-23",
        "project_description": "online recruitment service",
        "is_ongoing": "1"
      }
    ],
    "user_experience": [
      {
        "experience_id": "5",
        "job_title": "Software Engineer",
        "job_des": "Currently developing a data locality aware virtual machine placement strategy in cloud based Hadoop deployments. ResponsibilitiesReview and research on large-scale data processing platforms, data analytic tools and algorithms, streaming process, and data management",
        "company_name": "Schrdinger",
        "date_start": "2015-08-28",
        "date_end": "2016-01-23",
        "current_work": "1"
      }
    ],
    "user_education": [
      {
        "coun_name": "Afghanistan",
        "uni_title": "UOR",
        "uni_logo": null,
        "school": "DS School",
        "grade": "12",
        "description": "Science Stream",
        "field_studied": "field_studied",
        "added_date": "2015-09-05 14:00:03",
        "date_start": "2015-08-28",
        "date_end": "2016-02-23",
        "degree": "Computer Science"
      }
    ],
    "user_basic_details": [
      {
        "basic_details": "With degree and 2 years experiences.",
        "user_fname": "Mohamed",
        "user_sname": "Nifras",
        "user_im": "nifrasbcs",
        "bday": "1991-12-29",
        "gender": "1",
        "marital_status": "1"
      }
    ],
    "user_contact_details": [
      {
        "user_email": "nifrasnx@yahoo.com",
        "user_address_1": "No 32, New Market Road",
        "user_address_2": "Oddamavadi-01",
        "user_im": "nifrasbcs",
        "phone_mobile": "752786188",
        "phone_land": "652257153"
      }
    ]
  }
}

how to get json data without this array([,]) notation ,it'l be like
{
  "status": "Success",
  "data": {
    "skill":
      {
        "skill_id": "2",
        "skill_title": "Sports"
      }
    ,
    "user_projects":
      {
        "project_title": "workless",
        "project_id": "1",
        "date_start": "2015-08-28",
        "date_end": "2016-01-23",
        "project_description": "online recruitment service",
        "is_ongoing": "1"
      }
    ,
    "user_experience":
      {
        "experience_id": "5",
        "job_title": "Software Engineer",
        "job_des": "Currently developing a data locality aware virtual machine placement strategy in cloud based Hadoop deployments. ResponsibilitiesReview and research on large-scale data processing platforms, data analytic tools and algorithms, streaming process, and data management",
        "company_name": "Schrdinger",
        "date_start": "2015-08-28",
        "date_end": "2016-01-23",
        "current_work": "1"
      }
    ,
    "user_education":
      {
        "coun_name": "Afghanistan",
        "uni_title": "UOR",
        "uni_logo": null,
        "school": "DS School",
        "grade": "12",
        "description": "Science Stream",
        "field_studied": "field_studied",
        "added_date": "2015-09-05 14:00:03",
        "date_start": "2015-08-28",
        "date_end": "2016-02-23",
        "degree": "Computer Science"
      }
    ,
    "user_basic_details":
      {
        "basic_details": "With degree and 2 years experiences.",
        "user_fname": "Mohamed",
        "user_sname": "Nifras",
        "user_im": "nifrasbcs",
        "bday": "1991-12-29",
        "gender": "1",
        "marital_status": "1"
      }
    ,
    "user_contact_details":
      {
        "user_email": "nifrasnx@yahoo.com",
        "user_address_1": "No 32, New Market Road",
        "user_address_2": "Oddamavadi-01",
        "user_im": "nifrasbcs",
        "phone_mobile": "752786188",
        "phone_land": "652257153"
      }

  }
}

how to achieve it please help ?

A: In JSON the syntax {} denotes a Class and [] denotes an array, so if you want to create the result you are after, you need to create the data in an approprite object initially i.e. a class or an array.
You can simply create a class using the PHP stdClass() so as a starter to get you going you could do
$result = new stdClass();

$result->status = 'success';

$result->data = new stdClass();

$result->data->skill = array();
foreach($skill->processApi('user_skills',true) as $row_data) {
    $result->data->skill[] = $row_data;
}

$result->data->user_projects = array();
foreach($project->processApi('user_projects',true) as $row_data) {
    $result->data->user_projects[] = $row_data;
 }

. . .

. . .

$this->response($this->json($result), 200);


text:
Q: How to process this string by regex in oracle plsql My string (varchar2): 1111 = 2222;3333 in 4444;5555 sum (6666;7777)
I want to replace in my string ";" through " ; " except the ";" in parentheses.
Expected result:
1111 = 2222 ; 3333 in 4444 ; 5555 sum (6666;7777)

How to handle this case with the regex_replace function?
I want my regex to say: target them; and exclude them; in parentheses
I know targeting a character is just indicating the character.
The syntax for excluding a character is [^character_list] so for me is => [^;]
I tried this: regex_replace (myString, ';([^\(.;.\)]', ';');
But it doesn't work
link for a documentation :
https://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_re.htm
Edit:
sorry guys I made some mistake in my request. I corrected the description above.
I only wish replace ";" trough with " ; " except ";" in parentesis. The regular expression for that in function regex_replace.
I already have a function to split after. Sorry for that.

A: You can use a recursive sub-query factoring clause without any regular expressions and which correctly handles nested braces (such as (abc; (def;fff); zzyzx)):
WITH char_groups (
  id, value, idx, len, grp, grp_start, is_end, brace_level
) AS (
  SELECT id,
         value,
         DECODE( SUBSTR( value, 1, 1 ), ';', 0, 1 ),
         LENGTH( value ),
         1,
         DECODE( SUBSTR( value, 1, 1 ), ';', 0, 1 ),
         CASE
         WHEN ';' IN ( SUBSTR( value, 1, 1 ), SUBSTR( value, 2, 1 ) )
         OR   value IS NULL
         THEN 1
         ELSE 0
         END,
         DECODE( SUBSTR( value, 1, 1 ), '(', 1, 0 )
  FROM   table_name
UNION ALL
  SELECT id,
         value,
         idx + 1,
         len,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN grp + 1
         ELSE grp
         END,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN idx + 1
         ELSE grp_start
         END,
         CASE
         WHEN (
                (
                  ( brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) <> '(' )
                  OR
                  ( brace_level = 1 AND SUBSTR( value, idx + 1, 1 ) = ')' )
                )
                AND
                SUBSTR( value, idx + 2, 1 ) = ';'
              )
         OR   idx + 1 = len
         THEN 1
         ELSE 0
         END,
         GREATEST(
           brace_level + DECODE( SUBSTR( value, idx + 1, 1 ), '(', 1, ')', -1, 0 ),
           0
         )
  FROM   char_groups
  WHERE  idx < len
)
SELECT id,
       grp,
       LTRIM( SUBSTR( value, grp_start, idx - grp_start + 1 ), ';' ) AS term
FROM   char_groups cg
WHERE  is_end = 1
ORDER BY id, grp

Which, for the sample data:
CREATE TABLE table_name ( id, value ) AS
SELECT 1, '1111 = 2222; 3333 in 4444; 5555 sum (6666; 7777)' FROM DUAL UNION ALL
SELECT 2, 'ABCD'                    FROM DUAL UNION ALL
SELECT 3, 'A;;C;D;;F(F;F;F);'       FROM DUAL UNION ALL
SELECT 4, NULL                      FROM DUAL UNION ALL
SELECT 5, 'abc; (e;f) = ( e; f)'    FROM DUAL UNION ALL
SELECT 6, '(abc; (def;fff); zzyzx)' FROM DUAL UNION ALL
SELECT 7, '(((abc)));(def));((ghi;jkl);mno);pqr' FROM DUAL UNION ALL
SELECT 8, ';'                       FROM DUAL UNION ALL
SELECT 9, ';A;'                     FROM DUAL UNION ALL
SELECT 10, '()(;);(;)(;)'           FROM DUAL;

Outputs (including NULL values for when you have two adjacent ; delimiters):

ID | GRP | TERM
-: | --: | :----------------------
 1 |   1 | 1111 = 2222
 1 |   2 |  3333 in 4444
 1 |   3 |  5555 sum (6666; 7777)
 2 |   1 | ABCD
 3 |   1 | A
 3 |   2 | null
 3 |   3 | C
 3 |   4 | D
 3 |   5 | null
 3 |   6 | F(F;F;F)
 3 |   7 | null
 4 |   1 | null
 5 |   1 | abc
 5 |   2 |  (e;f) = ( e; f)
 6 |   1 | (abc; (def;fff); zzyzx)
 7 |   1 | (((abc)))
 7 |   2 | (def))
 7 |   3 | ((ghi;jkl);mno)
 7 |   4 | pqr
 8 |   1 | null
 8 |   2 | null
 9 |   1 | null
 9 |   2 | A
 9 |   3 | null
10 |   1 | ()(;)
10 |   2 | (;)(;)

db<>fiddle here

Previous Version:
Will work if you have single, balanced parentheses:
WITH terms ( id, value, idx, term, spos, epos ) AS (
  SELECT id,
         value,
         1,
         REGEXP_SUBSTR( value, '(([^;(]|\(.*?\))*)(;|$)', 1, 1, NULL, 1 ),
         1,
         REGEXP_INSTR( value, '(([^;(]|\(.*?\))*)(;|$)', 1, 1, 1 )
  FROM   table_name
UNION ALL
  SELECT id,
         value,
         idx + 1,
         REGEXP_SUBSTR( value, '(([^;(]|\(.*?\))*)(;|$)', epos, 1, NULL, 1 ),
         epos,
         REGEXP_INSTR( value, '(([^;(]|\(.*?\))*)(;|$)', epos, 1, 1 )
  FROM   terms
  WHERE  epos > 0
)
SELECT id, idx, term
FROM   terms
WHERE  SUBSTR( value, -1 ) = ';'
OR     spos < LENGTH( value )
OR     value IS NULL
ORDER BY id, idx;

Which outputs:

ID | IDX | TERM
-: | --: | :---------------------
 1 |   1 | 1111 = 2222
 1 |   2 |  3333 in 4444
 1 |   3 |  5555 sum (6666; 7777)
 2 |   1 | ABCD
 3 |   1 | A
 3 |   2 | null
 3 |   3 | C
 3 |   4 | D
 3 |   5 | null
 3 |   6 | F(F;F;F)
 3 |   7 | null
 4 |   1 | null
 5 |   1 | abc
 5 |   2 |  (e;f) = ( e; f)
 6 |   1 | (abc; (def;fff)
 6 |   2 |  zzyzx)
 7 |   1 | (((abc)))
 7 |   2 | (def))
 7 |   3 | ((ghi;jkl)
 7 |   4 | mno)
 7 |   5 | pqr
 8 |   1 | null
 8 |   2 | null
 9 |   1 | null
 9 |   2 | A
 9 |   3 | null
10 |   1 | ()(;)
10 |   2 | (;)(;)

(Note: it doesn't work for examples 6 & 7 where there are multiple nested parentheses but does work or the simpler test cases.)
db<>fiddle here

Update

I only wish replace ";" trough with " ; " except ";" in parenthesis.

You can use:
WITH char_groups (
  id, value, idx, len, grp, brace_level
) AS (
  SELECT id,
         value,
         CASE SUBSTR( value, 1, 1 ) WHEN ';' THEN 0 ELSE 1 END,
         LENGTH( value ),
         1,
         CASE SUBSTR( value, 1, 1 ) WHEN '(' THEN 1 ELSE 0 END
  FROM   table_name
UNION ALL
  SELECT id,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN SUBSTR( value, 1, idx ) || ' ; ' || SUBSTR( value, idx + 2 )
         ELSE value
         END,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN idx + 3
         ELSE idx + 1
         END,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN len + 2
         ELSE len
         END,
         CASE
         WHEN brace_level = 0 AND SUBSTR( value, idx + 1, 1 ) = ';'
         THEN grp + 1
         ELSE grp
         END,
         GREATEST(
           brace_level
           + CASE SUBSTR( value, idx + 1, 1 )
             WHEN '(' THEN 1
             WHEN ')' THEN -1
             ELSE 0
             END,
           0
         )
  FROM   char_groups
  WHERE  idx < len
)
SELECT id,
       value
FROM   char_groups
WHERE  idx = len OR value IS NULL
ORDER BY id, idx

And, for the sample data:
CREATE TABLE table_name ( id, value ) AS
SELECT 1, '1111 = 2222; 3333 in 4444; 5555 sum (6666; 7777)' FROM DUAL UNION ALL
SELECT 2, 'ABCD'                    FROM DUAL UNION ALL
SELECT 3, 'A;;C;D;;F(F;F;F);'       FROM DUAL UNION ALL
SELECT 4, NULL                      FROM DUAL UNION ALL
SELECT 5, 'abc; (e;f) = ( e; f)'    FROM DUAL UNION ALL
SELECT 6, '(abc; (def;fff); zzyzx)' FROM DUAL UNION ALL
SELECT 7, '(((abc)));(def));((ghi;jkl);mno);pqr' FROM DUAL UNION ALL
SELECT 8, ';'                       FROM DUAL UNION ALL
SELECT 9, ';A;'                     FROM DUAL UNION ALL
SELECT 10, '()(;);(;)(;)'           FROM DUAL UNION ALL
SELECT 11, '(a ; b);(c ; d)'        FROM DUAL;

This outputs:

ID | VALUE
-: | :---------------------------------------------------
 1 | 1111 = 2222 ;  3333 in 4444 ;  5555 sum (6666; 7777)
 2 | ABCD
 3 | A ;  ; C ; D ;  ; F(F;F;F) ;
 4 | null
 5 | abc ;  (e;f) = ( e; f)
 6 | (abc; (def;fff); zzyzx)
 7 | (((abc))) ; (def)) ; ((ghi;jkl);mno) ; pqr
 8 |  ;
 9 |  ; A ;
10 | ()(;) ; (;)(;)
11 | (a ; b) ; (c ; d)

Or, for only single nested braces, you can use:
SELECT id,
       RTRIM( REGEXP_REPLACE( value, '(([^;(]|\(.*?\))*)(;|$)', '\1 \3 ' ) )
       || CASE SUBSTR( value, -1 ) WHEN ';' THEN ' ' END AS value
FROM   table_name

Which outputs:

ID | VALUE
-: | :---------------------------------------------------
 1 | 1111 = 2222 ;  3333 in 4444 ;  5555 sum (6666; 7777)
 2 | ABCD
 3 | A ;  ; C ; D ;  ; F(F;F;F) ;
 4 | null
 5 | abc ;  (e;f) = ( e; f)
 6 | (abc; (def;fff) ;  zzyzx)
 7 | (((abc))) ; (def)) ; ((ghi;jkl) ; mno) ; pqr
 8 |  ;
 9 |  ; A ;
10 | ()(;) ; (;)(;)
11 | (a ; b) ; (c ; d)

db<>fiddle here

I already have a function to split after.

Please check your split function against case #11.

A: Here is one way to do this. The idea is simple: for each token, collect either an opening parenthesis, then any number of non-closing-parenthesis characters, then a closing parenthesis, OR a single non-semicolon. Collect ANY NUMBER of consecutive occurrences of the fragments I just described, followed either by semicolon or by the end of the string. That's a "token".
Note that this will not work correctly if you may have nested parentheses. To illustrate that, I included an example in my sample data. I also included a row where the "value" is NULL from the outset; presumably that should still produce a row in the output, with NULL token.
If my testing is correct, this will produce the same answer as MT0's, except when the input string is NULL (his solution won't produce any output for such inputs).
Sample data
create table sample_data (id, value) as
  select 1, '1111 = 2222; 3333 in 4444; 5555 sum (6666; 7777)'
                                      from dual union all
  select 2, 'ABCD'                    from dual union all
  select 3, null                      from dual union all
  select 4, 'A;;C;D;;F(F;F;F);'       from dual union all
  select 5, 'abc; (e;f) = ( e; f)'    from dual union all
  select 6, '(abc; (def;fff); zzyzx)' from dual
;

Query and output
select i.id, t.ord, t.token
from   sample_data i
       cross apply
       (
         select  level as ord,
                 regexp_substr(i.value, '((\([^)]*\)|[^;])*)(;|$)', 1,
                               level, null, 1) as token
         from    dual
         connect by level <= regexp_count(i.value, '((\([^)]*?\)|[^;])*)(;|$)')
                             - case when i.value like '%;' then 0 else 1 end
       ) t
;

ID ORD TOKEN
-- --- ----------------------
 1   1 1111 = 2222
 1   2  3333 in 4444
 1   3  5555 sum (6666; 7777)
 2   1 ABCD
 3   1
 4   1 A
 4   2
 4   3 C
 4   4 D
 4   5
 4   6 F(F;F;F)
 4   7
 5   1 abc
 5   2  (e;f) = ( e; f)
 6   1 (abc; (def;fff)     -- NOT the required result, when there are
 6   2  zzyzx)             -- nested parentheses in the input!


text:
Q: Windows 10 ftp folder keeps opening in browser! How do I change it? I created a network location on my Windows explorer menu to open the ftp directory to my Nexus phone. At first it couldn't connect and it stupidly was asking me what app I wanted to open the folder with. So I just selected chrome but now it always opens in chrome even when I've deleted the ftp folder started a new one it still opens in chrome! This is really stupid how you don't have an Open With... option when you right click the ftp folder. Can anyone help to just open using Windows Explorer?
Screenshot

A: Search on your machine for Default Applications.
Choose at the bottom Default Apps by Protocol
Scroll down until you see ftp on the left column and change the app to Windows Explorer.

A:
Windows 10 ftp folder keeps opening in browser! How do I change it?

Go to the Control Panel, select Internet Options, go to the Advanced tab, and then ensure that you DO check the option labeled Enabled FTP folder view (outside of Internet Explorer), and then click Apply to save the setting change.
Afterwards, retry your Explorer shortcut pointing to the FTP server, and it should open up with Windows Explorer in a folder type view rather than with your web browser in the web browser type view.
Additionally, you can just create a shortcut to the FTP server with the below syntax  %windir%\explorer.exe ftp://<username>:<password>@<FTP Server Name or IP Address> and just double-click on it to access the FTP site.

A: I have changed the default protocol association of FTP to chrome.
Goto

Settings>(Serach)Default App>(Bottom)Choose Default App by Protocol > Select Chrome as a default association for FTP

And then uninstall chrome.


text:
Q: Upgrading MySQL 5.1 to 5.5 on Centos 6 without removing dependencies I'm trying to upgrade MySQL 5.1 to 5.5 using yum/rpm combo (yum to remove MySQL 5.1 and rpm to install MySQL 5.5). Most instructions I've found suggest to do first:
yum remove mysql mysql-server mysql-libs

However doing so will remove in my case lots of other packages which I definitely don't want to remove:
================================================================================
 Package              Arch        Version                   Repository     Size
================================================================================
Removing:
 mysql                x86_64      5.1.69-1.el6_4            @updates      2.4 M
 mysql-libs           x86_64      5.1.69-1.el6_4            @updates      4.0 M
 mysql-server         x86_64      5.1.69-1.el6_4            @updates       25 M
Removing for dependencies:
 cronie               x86_64      1.4.4-7.el6               @cr           166 k
 cronie-anacron       x86_64      1.4.4-7.el6               @cr            43 k
 crontabs             noarch      1.10-33.el6               @cr           2.4 k
 mysql-devel          x86_64      5.1.69-1.el6_4            @updates      388 k
 percona-toolkit      noarch      2.2.4-1                   @percona      5.7 M
 perl-DBD-MySQL       x86_64      4.013-3.el6               @base         338 k
 php-mysql            x86_64      5.3.3-23.el6_4            @updates      216 k
 postfix              x86_64      2:2.6.6-2.2.el6_1         @base         9.7 M
 sysstat              x86_64      9.0.4-20.el6              @base         807 k

Transaction Summary
================================================================================

How can I upgrade MySQL without removing those packages? Can I somehow remove MySQL 5.1 without dependencies (well, maybe besides mysql-devel) and get away with it? (without libraries mismatch). I've found one blog that suggest to upgrade MySQL in yum shell, however I'm not sure if it would change anything? :

A: You can remove MySQL without removing the dependencies with RPM:
rpm -e --nodeps mysql

Keep in mind that yum is going to complain next time you try to install a package about the rpm database being modified. You can correct that with yum clean all.


text:
Q: Jquery kendo grid prevent clicking only non edit rows when in edit mode I'm currently using a kendo grid. What I've been trying to do is that when I click on the add new row button the empty row(k-grid-edit-row) displays. I want to throw an alert message and saying complete the editing operation first when I click on other rows during the editing operation. But the key is, I don't want the alert message to be displayed when I click on the current inline editing row.
What I have done right now is that I also get an alert message when I click on current inline edit row.
    $('.k-grid-content').on("mousedown", function (e) {
        var grid = $('#Grid').closest(".k-grid");
        var editRow = grid.find(".k-grid-edit-row");
        if (editRow.length > 0) {
            alert("Please complete the editing operation before editing another row");
            e.preventDefault();
        }
        else return;
    });

A: You could try checking the Index of the row that has been clicked. When you are adding a row, the row goes to the top and has and index of 0.
In your if statement, also check if the index is not equal to 0.
It would look something like if grid.data("kendoGrid").select().index() != 0.
I haven't tested this, but I believe it should work.


text:
Q: twitter oauth must authorize user everytime they login I am adding twitter oauth login to my site . and so far i got it to work using oauth.
however every time i login i go through the whole authorization process. ( the prompt that allows the user to request or deny the application)
is there a way to by pass that once the user has authorized the app?
Perhaps i am misunderstanding the process also if so could you please clarify?
thank you

A: must use oauth_authenticate_url instead of oauth_authorize_url

A: I just had the same problem, after I solved it I made a template to set it all up. http://blog.ruedaminute.com/2010/12/everything-you-need-to-access-twitter-using-tweetr-api-and-air/


text:
Q: Firebase hosting deploy is not deployed to one of the free domains : my-project-id.web.app, not on my-project-id.firebsaseapp.com As I know firebase allows our website to be deployed to free hosting services on two free domains. Which are:

*

*my-project-id.firebaseapp.com,

*my-project-id.web.app

I am trying to upload my static website to firebase hosting using cmd firebase deploy. But it is only uploaded to web.app, while not uploaded to firebaseapp.com.
Earlier some days it was working well.
Please help how to resolve this problem.

A: I had faced something similar to this:
After a deploy, my site was not getting updated on web.app and when I used Chrome Dev tools, it turned out to be the old code. However, the code was updated on firebaseapp.com.
The actual reason is still unknown to me, but there are a high chance that this is some sort of cache issue. I was testing my site on 'web.app' like a lot of time, many refreshes and deploys..
I just Disabled Cache during testing thereafter.

I faced no such issue after that...
Try hard refresh or whatever it is called using Ctrl + Shift + R and Ctrl + F5

A: This is unexpected as all Firebase Hosting applications should behave identically on web.app and firebaseapp.com. I'd recommend reaching out to Firebase Support for help.

A: I faced the same problem when using Chrome.  I tried Edge and both URLs worked fine.  It's probably some setting in Chrome. I tried disabling cache but that didn't help.  Test with another browser.

A: Similar to: Firebase default hosting domains: only .firebaseapp.com works but .web.app fails
TLDR; [Solved] Ctrl+F5 to force hard reset (to clear cache)


text:
Q: What is the best way to compare tar archives in junit testing I am attempting to create jUnit tests for some code that generates tar files. During testing I will be creating a variety of tar files and comparing them to "Gold" tar images of the expected output. I have been struggling to create an assertTarEquals(String file1, String file2) function, and was hoping someone could provide guidance as to the best approach. It's not important to have the tar file entries in the same order, or with the same attributes. I just need to verify that they have all the same files and that those files contain the same content. I have created a assertZipEquals(String file1, String file2) based on the example provided here: http://www.java2s.com/Tutorial/Java/0180__File/Comparetwozipfiles.htm but the ZipFile.getInputSteam(EntryName) does not appear to have a parallel function in the Commons Tar classes, as they have not implemented markers in the TarInputStream.

A: I would typically agree that unit testing is no place for testing Archives, but the code that is being tested manages the creation of archives, so in my mind it is not only appropriate but necessary. The code below is pretty ugly, and I would never want to use something like this in production code, but for testing I guess it's ok.... here's the code I'm using for assertArchiveEquals, it supports both tar and zip files.... as always all feedback is welcome.
package com.foo.util.merge;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;

import static org.junit.Assert.*;

public final class CompareArchives {

    public static final void assertArchiveEquals(String type, String archive1, String archive2) throws NoSuchAlgorithmException, IOException {
        if (type.endsWith("zip")) {
            assertZipEquals(archive1, archive2);
        } else {
            assertTarEquals(archive1, archive2);
        }
    }

    /**
     * @param archive1
     * @param archive2
     * @throws ZipException
     * @throws IOException
     */
    public static final void assertZipEquals(String archive1, String archive2) throws ZipException, IOException  {
        // Get Archives
        ZipFile zipFile1 = new ZipFile(new File(archive1));
        ZipFile zipFile2 = new ZipFile(new File(archive2));

        // Get Member Hash
        HashMap<String, ZipEntry> files1 = getMembers(zipFile1);
        HashMap<String, ZipEntry> files2 = getMembers(zipFile2);

        // Compare Files
        assertMembersEqual(zipFile1, files1, zipFile2, files2);
    }

    /**
     * @param archive
     * @return
     * @throws IOException
     */
    private static final HashMap<String, ZipEntry> getMembers(ZipFile archive) throws IOException {
        HashMap<String, ZipEntry> map = new HashMap<String, ZipEntry>();
        @SuppressWarnings("unchecked")
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) archive.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            map.put(entry.getName(), entry);
        }
        return map;
    }

    /**
     * @param zip1
     * @param files1
     * @param zip2
     * @param files2
     * @throws IOException
     */
    private static final void assertMembersEqual(ZipFile zip1, HashMap<String, ZipEntry> files1,
                                                 ZipFile zip2, HashMap<String, ZipEntry> files2) throws IOException {
        if (files1.size() != files2.size()) {
            fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found " + Integer.toString(files2.size()));
        }

        for (String key : files1.keySet()) {
            if (!files2.containsKey(key)) {
                fail("Expected file not in target " + key);
            }
            String file1 = IOUtils.toString(zip1.getInputStream(files1.get(key)));
            String file2 = IOUtils.toString(zip2.getInputStream(files2.get(key)));
            assertEquals(file1, file2);
        }
    }

    /**
     * @param archive1
     * @param archive2
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static final void assertTarEquals(String archive1, String archive2) throws IOException, NoSuchAlgorithmException {
        // Get Member Hash
        HashMap<String, TarArchiveEntry> files1 = getMembers(archive1);
        HashMap<String, TarArchiveEntry> files2 = getMembers(archive2);

        // Compare Files
        assertMembersEqual(archive1, files1, archive2, files2);
    }

    /**
     * @param archive
     * @return
     * @throws IOException
     */
    private static final HashMap<String,TarArchiveEntry> getMembers(String archive) throws IOException {
        TarArchiveInputStream input = new TarArchiveInputStream(
                new BufferedInputStream(
                new FileInputStream(archive)));

        TarArchiveEntry entry;
        HashMap<String, TarArchiveEntry> map = new HashMap<String, TarArchiveEntry>();
        while ((entry = input.getNextTarEntry()) != null) {
            map.put(entry.getName(), entry);
        }
        input.close();
        return map;
    }

    /**
     * @param tar1
     * @param files1
     * @param tar2
     * @param files2
     * @throws IOException
     */
    private static final void assertMembersEqual(String tar1, HashMap<String, TarArchiveEntry> files1,
                                                 String tar2, HashMap<String, TarArchiveEntry> files2) throws IOException {
        if (files1.size() != files2.size()) {
            fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found " + Integer.toString(files2.size()));
        }

        for (String key : files1.keySet()) {
            if (!files2.containsKey(key)) {
                fail("Expected file not in target " + key);
            }
        }

        for (String key : files1.keySet()) {
            if (!files2.containsKey(key)) {
                fail("Expected file not in target " + key);
            }
        }
        for (String key : files1.keySet()) {
            String file1 = getTarFile(tar1, key);
            String file2 = getTarFile(tar2, key);
            assertEquals(file1, file2);
        }
    }

    /**
     * @param archive
     * @param name
     * @return
     * @throws IOException
     */
    private static final String getTarFile(String archive, String name) throws IOException {
        TarArchiveInputStream input = new TarArchiveInputStream(
                new BufferedInputStream(
                new FileInputStream(archive)));
        TarArchiveEntry entry;
        while ((entry = input.getNextTarEntry()) != null) {
            if (entry.getName().equals(name)) {
                byte[] content = new byte[(int) entry.getSize()];
                input.read(content, 0, content.length);
                input.close();
                return new String(content);
            }
        }
        input.close();
        return "";
    }

}


text:
Q: Create a has_many association where a condition applies to the primary table in ruby on rails? I've got authentications which have many groups using uid as the primary_key and organizer_id as the foreign_key, no problem.
But uid is unique scoped to the provider attribute. I want to make sure my association only fetches groups where authentication.provider == 'meetup'. I tried:
has_many :groups, :primary_key => "uid", :foreign_key => "organizer_id", :conditions => {:provider => "meetup"}

But this is just trying to find all groups with provider == "meetup"
How can I specify a condition on the primary table authentications?

A: Try:
has_many :groups, :primary_key => "uid", :foreign_key => "organizer_id", :include => :authentication, :conditions => {:authentication => {:provider => "meetup"}}

Updated:
If Group belongs_to Authentication with "organizer_id" as foreign_key then just:
Group.includes(:authentication).where(:authentication => {:provider => "meetup"})