text:
Q: how to add child nodes in jquery nestable dynamically I am using jquery nestable plugin to show my application organization -> Venue and Location tree structure. By Default I want to load the parent organizations only and when I click the expand button of any parent organization, I want to load venue of that organization with Ajax. Same will be process for N level locations which are under venue and my organization nestable tree should get reloaded.
The expand button is visible only if the parent node has children.
{foreach $organizations_list as $organization}

        <button type="button" data-action="load-venue" id="load-venue-{$organization.id}">Load</button>

            {$organization.name} (ID: #{$organization.id})

                  {$organization.description}

{/foreach}


text:
Q: How to handle http_status_code in Kubernetes probe? I am trying to implement Probe in Kubernetes
I understand that the probe returns success if http_status_code >= 200 and <=399
  containers:
    - name: myimage
      image: myimage:45
      imagePullPolicy: Never
      readinessProbe:
        httpGet:
          path: /
          port: 5004

However, our application returns status code 404 (by design) in case of success.
How can I make the probe to succeed in this case?
Is there any way to achieve this?

A: Change the probe to execute a command instead of an http request. Kubernetes executes the command inside the container and determines the success based on the exit code of the command (0 for success, non-zero for failure)

*

*Create a script /health.sh that uses curl to call your health check endpoint through localhost. Include a condition that sets the exit code to 0 (success) if the return code is 404, and 1 (failure) otherwise

#!/bin/sh
if [ $(curl -s -o /dev/null -w "%{http_code}" http://localhost:5004) -eq "404" ]; then
  exit 0
else
  exit 1
fi

*Configure the probe with a command instead of a http request

readinessProbe:
  exec:
    command:
    - /bin/sh
    - -c
    - /health.sh

If you don't want to modify the container, you can define the script inline in the command section like below
readinessProbe:
  exec:
    command:
    - /bin/sh
    - -c
    - if [ $(curl -s -o /dev/null -w "%{http_code}" http://localhost:5004) -eq "404" ]; then exit 0; else exit 1; fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: SOAP fault with default WSDL from Magento Website I am using the WSDL (advertised in the Magento Website to be used with Java) in my Android Application.
For simulating the request/response i am using SOAP UI. I deployed Magento on a WAMP server on my local windows machine.
Now when i run any of the SOAP API's I am getting a SOAP fault. Upon analysis found that the below line present in all the internal WSDL files in magento is the cause of this problem -
<import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/" />

When I comment this line, everything seems to work fine.
But I don't think that this is the correct solution ...
Anyone who faced this issue , please help out !!!!!

A: I think the problem is the SoapUI application not the wsdl itself. I can confirm that the wsdl file is valid.
I don't know if this is the issue for you,  but I had an encoding problem related to SoapUI and it was solved by adding this:
-Dfile.encoding=UTF8

inside oapUI-4.6.4\bin\SoapUI-4.6.4.vmoptions. The folder and file name may depend on the SoapUI version.


text:
Q: Javascript namespace issue, how do i get this value within this function call im just not sure how to get the desired value within this function Thanks!
temp = exotics[i].split(',');

if ($.inArray(temp[0], tblProbables) != -1) {
    item = $("
" + temp[1] + "
");
    item.click(function () { GetProbable(temp[0]); });
}

temp[0] is blank because it doesn't exist within that function space.... so how can i setup the click event so that it calls the function with the proper param?

A: I have a feeling you're reusing the temp variable somehow.
If so, you can just create a new variable scope in a function that returns a function that references the proper scoped variable.
function createHandler( temp ) {
    return function () { GetProbable(temp); };
}

item.click( createHandler(temp[0]) );

A: Store the value in a temporary variable:
....
    var temp0 = temp[0];
    item.click(function () { GetProbable(temp0); });

If the the temp0 varible changes multiple times (e.g. in a loop), create a closure:
    (function(temp0){ //Inside this function, it doesn't matter if `temp` changes
        item.click(function () { GetProbable(temp0); });
    })(temp[0]);


text:
Q: Woo-commerce Update price as a Bulk from My offline software export I have a WordPress + woo commerce online shop.
In addition I have a local offline desktop software for my inventory products and pricing.
I define a common code between my shop and my local desktop software for each product to relate products in my offline desktop software and my online shop.
My requirement is that two times each day I export an Excel file including product, price, availability, and common code from my offline desktop software and import into my online shop to update the available number of each product and price.
is there any easy method or way to doing this?


text:
Q: Reset domain name redirect for a digitalocean droplet I used to have a domain for my digitalocean droplet. The domain expired. When I type my droplet IP address it redirect to that expired domain and gives an error ERR_NAME_NOT_RESOLVED.
I removed all of the domain records in digitalocean for my droplet.
How can I prevent this redirect from happening and get access to my droplet via IP?

A: Probably you have a redirect in the Apache or nginx config on the droplet to forward to your former domain name? or check .htaccess files in the configured web root folder


text:
Q: Tar daily files based on timestamp in name I have daily log files which are in the format:
abc-xyz.log.2019-10-01
abc-xyz.log.2019-10-02
abc-xyz.log.2019-10-03

What I'd like to do is have a bash script that tars and compresses each log file with it's associated timestamp and run in manually.
Could anyone point me in a good direction for this ?
so the output is :
abc-xyz.log.2019-10-01.tar.gz
abc-xyz.log.2019-10-02.tar.gz
abc-xyz.log.2019-10-03.tar.gz

So the script would read one file at a time and based on the timestamp in the name, would output the tared filename with the same timestamp.

A: With xargs and GNU tar:
printf "%s\n" *[0-9] | xargs -I {} echo tar -czf {}.tar.gz {}

If output looks okay, remove echo.

See: man xargs


text:
Q: Explaining something using second person point of view I am going to take the IELTS exam and if an examiner asks me:
"- Why exercise is important?"
Is it correct to answer:
"- It is important because it's good for your health"
or should i say:
"- It is important because it's good for people's health"

A: With a little more context, the question is likely directed at you, someone else, etc.  You can often avoid having to use a pronoun in such cases, for example, "It is important because it improves health."  The answers assumes the same subject as the original question.
With a pronoun however, "one" is the correct pronoun to use.  I don't agree with Ily, you won't sound like a prat, and the use of "one" is not obnoxious.  Yes, "you" is very commonly used.

A: a.
If an IELTS examiner asks you "Why exercise is important?" you need to ask for her supervisor and get her replaced. She's asking direct questions as if they're indirect and shouldn't be administering the exam.
b.
The proper answer to the intended question why is exercise important? is because it's good for your health but only in informal English. On tests, the generic you should be replaced by the obnoxious one's (alt. our) and everything should generally be in full sentences just to show that you can phrase things that way.
So your first answer makes you sound like less of a prat but the second is better for your test and It is important for one's health is better yet.


text:
Q: Тень вверху UITableView не появляется Пытаюсь сделать тень сверху tableView, вот код:
tableView.layer.masksToBounds = false
tableView.layer.shadowColor = UIColor.black.cgColor
tableView.layer.shadowOffset = CGSize(width: -5.0, height: -5.0)
tableView.layer.shadowOpacity = 1.0

Так же пробовал ставить CGSize.zero, но тень по прежнему не показывается.
Вот что я хочу:


text:
Q: How to get Current Logged Internet Explorer User Name and Domain Name I need to get user details before hitting the SharePoint Server page.
User hitting sharepoint page(https://spxy) then I redirect to https://spxy/_layouts/TestHandler.ashx via httpmodule.
I need to get IE User logged in Name in the http handler page.
Example:

XYZ Domain -- Test User -- John
ABC Domain -- Test User -- Alex
Contoso Domain -- Test User -- Tom

I just logged in windows login as Administrator, If I login in the  IE using john then I need to his domain name and user name.

A: You can use JSOM by javascript like two different ways:
Using sp.js _spPageContextInfo.userLoginName

Or you could use REST
function getCurrentUser() {
    var endpointUrl = _spPageContextInfo.webServerRelativeUrl + '/_api/web/currentuser';
    return $.ajax({
            url: endpointUrl,
            method: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
             "Accept": "application/json;odata=verbose"
            }
        }); }

A: There are many ways to get logged in user name
SPWeb site = SPControl.GetContextWeb(Context);
SPUser user = site.CurrentUser;
string strUserName = user.LoginName;

or you can use
SPWeb web = SPControl.GetContextWeb(this.Context);
string userName = web.CurrentUser.LoginName;

or you also can use
string userName = this.Context.User.Identity.Name;


text:
Q: Symfony - Call to a member function on array I have the following function:
public function getUserMediaAction(Request $request)
{
    $data = $this->decodeToken($request);
    $username = $data['email'];
    $user = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                 ->findOneBy(['email' => $username]);
    $idUser = $user->getId();
    $media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                  ->findNewbieAllData($idUser);

    return new JsonResponse(['media' => $media->getPath()]);
}

findNewbieAllData:
public function findNewbieAllData($id_newbie)
{
    $sql = "SELECT m
            FROM ApplicationSonataUserBundle:User u
            JOIN ApplicationSonataUserBundle:Media m
            WHERE u.id=?1";

    $query = $this->getEntityManager()

                    ->createQuery($sql)
                    ->setParameter(1, $id_newbie);

    $result = $query->getArrayResult();
    return $result;
}

which unfortunately returns the following error:
Call to a member function getPath() on array

Stack Trace

in src\CoolbirdBundle\Controller\UserController.php at line 97   -
        $media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
                      ->findNewbieAllData($idUser);
        return new JsonResponse(['media' => $media->getPath()]);
    }

Would anyone have any idea of how I can solve this problem, please?
thank you in advance

A: Try the following instead:
return new JsonResponse(['media' => $media[0]->getPath()]);

Edit: Looking at the var_dump output you should try this:
return new JsonResponse(['media' => $media[0]['path']]);

A: Method findNewbieAllData hydrates data with arrays.
$result = $query->getArrayResult();
    return $result;

Look at getArrayResult method here:
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php
Use getResult method instead.


text:
Q: Connecting 2 networks together via router I have a small size business where we have around 22 PCs.
At present, I have the internet connected directly to a switch1 (We use dedicated leased line and I have been provided with 5 static IPs by my ISP).
From the switch I have connected a line directly to my asterisk server with a static IP provided by my ISP.
Then, from switch1 another line is connected to a router (Netgear WNDR3700v2).
In the router, I have configured one live IP and enabled DHCP with IP range between 192.168.0.20 to 192.168.0.80.
From the router, I have connected a line to another 24 port switch which distributes internet to all the PCs. We use Windows 7 Pro for all the PCs.
Now, I have taken another office in the opposite building where I will be running around 20 PCs. From Swtich1, I am connecting a line to a router (Netgear WNDR3700v2) in the new office.
In the new office router, I am configuring another live IP provided by my ISP and enabled DHCP with IP range between 192.168.0.100 to 192.168.0.150.
From the router, I am connecting a line to a switch and distributing internet in the new office.
I do not have any Microsoft server at moment.
How do I connect this 2 network together, so that we can share files, printers and NAS. I do not want to connect via wireless.

A: The easiest thing is to connect your new router, to both switch1 and to your old router. In this way, all of your pcs will belong to the very same subnet, while the new router might very well route Internet traffic for the new pcs in the new building.
The connection should be established like this:
1.Enable DHCP on both routers, making sure the two ranges are separate. For instance, you might use 192.168.0.50-192.168.0.100 for the DHCP range of the old router, and 192.168.0.150-192.168.0.200 for the old router.
2.connect a cable from a LAN port of the old router to a LAN port on the new router.
3.connect a cable from switch1 to the WAN port of the old new router.
4.assign to the new router's LAN interface an address unused by either router, for instance 192.168.0.129.
5.configure advanced routing in the new router, so that it has a new routing rule: all packets to the subnet 192.168.0.0/25 (notice: 25, twentyfive, corresponding to netmask 255.255.255.128) is to be routed through 192.168.0.1.
6.do the equivalent thing on the old router, i.e., a new route for addresses 192.168.0.128/25 (same netmask, 255.255.255.128) through 192.168.0.129.
The last rule makes sure that the addresses for the old LAN are correctly reached through the old router, and viceversa.
7.just to avoid doubts, make sure that all other netmasks, except for the two mentioned above, are 255.255.255.0, .e., /24, so that all of your pcs can talk to each other.
This way, you have a single subnet, correctly managed by the two routers in non-overlapping chunks, but you are tking full advange of your two external IPs, and of your ISP's capabilities, without overworking either router.


text:
Q: Converting Map to graphics and annotations in ArcGIS for Desktop? i want to export a map for later editing before print, so i thought about converting all the annotations and and graphics and save them in the .mxd map.
when i export graphics after exporting labels , the graphics cover some labels, and there is no option to make the graphics in back level. but when i export the graphics before exporting labels, the labels makes some displacement due to some maplex config, despite making a maplex lock on labels, it cannot be fixed.
Is there a way to manipulate graphics and annotation as layers despite saving them in the map?
if there is an alternative solution to edit map in a CAD like style before print is welcome.
i'm using ArcMap 10.1.

A: " You can edit annotation - or setup a rule or two with the Maplex engine to not clash with other text,annotation or features"
Maplex Engine Rules
Preventing overlapping
http://resources.arcgis.com/en/help/main/10.1/index.html#/Preventing_labels_from_overlapping_certain_features/00s80000003t000000/
Reducing the label size
http://resources.arcgis.com/en/help/main/10.1/index.html#/Reducing_the_size_of_the_label_text/00s800000057000000/
When you happy with the results then you can convert into annotation.
Maplex is now standard with the Standard/Advance version of ArcGIS 10.1


text:
Q: Unintentional mouse movements, am I paranoid? I have noticed for a few months that my mouse will randomly jerk across the screen. I'm super paranoid about security. But this is just silly!
Has anyone else experienced this, and found out what causes it? It happens to me every couple of days. The cursor will jump across the screen about 1000+ pixels. I thought it was my mousepad - changed it, and that's not it.
I imagine it's just a hardware issue.
This is on a PC with a Razer Naga, wired mouse. The mouse worked for about a year before I started noticing these issues. They have persisted even after a reformat / reinstall.

A: *

*An optical mouse could cause some erratic behavior if there is a hair or something stuck underneath it and triggering the sensor; remove the hair.

*A ball mouse can cause erratic behavior if there is dirt stuck to the rollers; clean the roller and ball.

*An wireless mouse can cause erratic behavior if there is interference between the mouse and the sensor; try a different channel or clear a line-of-sight between them.

*A wired mouse can cause erratic behavior if there is a bad connection, for example a frayed cord or cold-joint/broken solder connection on the PS/2 or USB connector; replace cord/mouse or use a different port.
In your specific case, it sounds like a recent problem and an intermittent one at that. Does it usually happen on the same day and/or at the same time? It sounds like some new device that is causing interference when it turns on. Have you installed any new electronic devices or appliances in the past few months? Have you gotten new neighbors or was there any recent construction?

A: I would suspect, first of all, optical/mechanical issues with the mouse.
Firstly, the optical sensor needs to be clean and free of grease (including invisible fingerprints), fluff and hair - on the outside and inside.  This goes not just for the bit that lights up, but the sensor.
The optical unit is designed to focus at a specific distance, and if it is dislodged or adjusted in any way, then it can not work.  I had a mouse where two of the stuck-on "feet" of the mouse came off, placing the optical sensor a very slight distance (fractions of millimetres) closer to the table/mousepad surface, making the mouse highly unreliable.
It could just be a dodgy mouse.

A: Sometimes these kinds of mouse movements occur because the memory pointer that holds location information relative to the screen has become corrupt.
Drivers have these issues, and when they are problematic enough to effect enough people or enough situations are seen where the problem is linked back to said driver, the product manufacturer comes out with a Driver Update.
As from the bottom here: http://support.microsoft.com/kb/88543
pay additional attention to #5
Mouse Pointer Movement Is Erratic

*

*If the mouse is jumpy, lower the Sensitivity value in the Mouse
section of Control Panel.

*If the mouse is jumpy in Program Manager group windows, lower the granularity settings in the Desktop icon of Control Panel.

*If you are using the MS-DOS-based mouse driver MOUSE.COM or MOUSE.SYS version 7.04 or later, add the /Y switch to the end of the
mouse command line as follows:
    c:\windows\mouse.com /y

*Follow the troubleshooting steps in the above section, "Mouse Does Not Function in Windows."

*It is possible that the erratic mouse movement you are experiencing is highly specific to the application, video card,
machine BIOS, keyboard BIOS, or machine type you are using. For more
information about these specific issues, query on the following
words in the Microsoft Knowledge Base:
    mouse and erratic or jumpy or wild or jerky

PS don't bother searching microsoft's knowledge base, those terms aren't very helpful, its better if you just type in your video card makers name or the overall driver maker like Nvidia or ATI or Geforce ... with the name of the card identified and "mouse problem" and you'll usually find lots of stuff... or google: video driver causes mouse problem
lots of stuff out there.  I've had this happen off and on, most recently its been happening less after I updated my video driver (nvidia) to the most current.  In just 5 months the Nvidia drivers went from ver.266.58 to ver.280.26.  While they may not have released to the public 14 versions, that's the minimum they went through in 5 months time.  it happens..

A: Unplug the mouse - and observe is anything is happening. If it happens without the mouse, disconnect the network and then if it DOSEN'T happen, panic, and follow the handy superuser malware removal community wiki.
I'd also check the system for unknown devices, and processes and autorunning software for unknown ones, since this sounds almost like a prank -this device comes to mind but google has a lot of hits for random mouse movement pranks

A: I also experienced the same phenomena using a normal wired, optical Logitech-Mouse. Even if I was not connected to a network this happened. Changing the mouse made it better for a while.
Nowadays, my conclusion is, that there's only some problem with the optical unit of the mouse. Nothing to worry about.
If you were remote-controlled, many more strange things happened (e.g. targeted mouse-movement or flickering on your screen).

A: With a wired mouse, a very likely cause is a broken mouse cable.  Flexing of the cable eventually fatigues the conductors near the mouse body, and they become "touchy" to where they connect and disconnect erratically.  This can result in the cursor suddenly scooting across the screen, etc.
It's easy to test for this possibility -- simply hold the mouse steady while you flex the cable near it, and look for any motion of the cursor.

A: Turns out I was having this issue every now and again as well. Aside from making sure the optical sensor is clean of any hairs or grime, you should check if there is a second mouse plugged into your computer.
I sometimes have two mice plugged into my computer, both optical - one for when I'm at my desk, and a second for when I'm watching netflix from bed. Sometimes I forget to unplug my bedside mouse.
On a side note, sometimes the twitching cursor can also be caused by the surface you are using the mouse on. My bedside mouse often rests on a glass tabletop, causing the twitching problem.

A: Disconnect from all networks. Does it still happen? If it does, then it's not BB. Even the gov can't send information to a computer remotely if it's not connected to the internet.
Also, anybody with any remote sense of stealth is not going to RC a box when they can tell it's being used.
EDIT:  @Thomasrutter has a good point. If it is someone trying to mess with you, it is extremely trivial to write a program that will move the mouse across the screen. This little C++ segment will do exactly what you are describing:
int random;
// loop forever, 1 will always equal 1
while(1)
{
    // generate random number between 0 and 100
    random = Rand()%100;
    // if the random number is greater than or equal to 75...
    if(random >= 75)
    {
         // ...then generate random numbers and set the
         // mouse coordinates to them
         SetCursorPos(Rand()%1000,Rand()%500);
         // pause for 10 seconds
         sleep(10000);
    }
    // loop back to beginning
}

If that is the case, then open Task Manager (CTRL+ALT+DELETE) and check for any suspicious looking processes (such as joke.exe, hack.exe, prank.exe or duplicate entries of legitimate processes)
Also, if you suspect this, check your startup folder (Start -> All Programs -> Startup) for suspicious looking entries.
This kind of attack is unlikely, unless you know a programmer with a sense of humor, but that would definitely explain the kind of behavior you're describing. (I did this to one of my friends once :)

A: Besides the other comments on faulty optical sensor or trackball etc., I want to add that it can also happen if you have an optical mouse on a surface that doesn't have a lot of patterns (say glass or a uniformly white table etc.). If that is the case, try getting a mousepad - or maybe just try using newspaper page as a mousepad to test - and see if that fixes it.
And even if you're paranoid, you really should mention atleast your mouse type and OS for such a question.

A: As I have same issue with Samsung Laptop Touch Pad.
I unplugged the Power Adapter and Tested on Batteries,the Touch Pad worked fine.
No Issue.
 It is a Bad Power Adapter,
as Touch Pad working fine on battery.


text:
Q: Sign in Form not align to center I face an issue while I want to align my sign-in form of test website not align to center.
can anyone help me to resolve this issue?
for better understanding here I attached my js form and CSS file.

.form {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.form-container {
  display: flex;
  flex-direction: column;
  width: 32rem;
  padding: 2rem;
  border: 0.1rem #c0c0c0 solid;
  border-radius: 0.5rem;
  list-style-type: none;
}

.form-container li {
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
  margin-top: 1rem;
}

input {
  padding: 1rem;
  border: 0.1rem #c0c0c0 solid;
  border-radius: 0.5rem;
}
<form onSubmit={submitHandler}>

        Sign In

          Email

       Password

      <button>Signin</button>

      New to Tangail Saree?

      <Link to="/register"> Create your account</Link>

</form>

Edit: It solved. I use dot in front of form that's the reason it not working.

A: You applied css to .form instead of form
change .form to form
 form {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }

This works!

form {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.form-container {
  display: flex;
  flex-direction: column;
  width: 32rem;
  padding: 2rem;
  border: 0.1rem #c0c0c0 solid;
  border-radius: 0.5rem;
  list-style-type: none;
}

.form-container li {
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
  margin-top: 1rem;
}

input {
  padding: 1rem;
  border: 0.1rem #c0c0c0 solid;
  border-radius: 0.5rem;
}

<form onSubmit={submitHandler}>

        Sign In

          Email

       Password

      <button>Signin</button>

      New to Tangail Saree?

      <Link to="/register"> Create your account</Link>

</form>


text:
Q: Create mixed orientation PDF in iTextSharp I am merging PDF buffers using this code at http://web.archive.org/web/20111012184438/http://alex.buayacorp.com/merge-pdf-files-with-itext-and-net.html [Mirror]
My PDFs have mixed page orientation, some are portrait and some are landscape (but all are A4)
The code does not maintain the orientation of each page and uses the orientation of the first page throughout the document. How do I go about creating a mixed orientation PDF using this code.

A: The trick to using multiple page sizes is to call SetPageSize() just before calling NewPage(). Something like this should work (I didn't compile this but it should be pretty close):
PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
newDocument.SetPageSize(new iTextSharp.Text.Rectangle(0.0F, 0.0F, importedPage.Width, importedPage.Height));
newDocument.NewPage();
pdfContentByte.AddTemplate(importedPage, 0, 0);

A: Similar to @Chris Haas.  I needed page 3 to be landscape
        if (PageNumber == 3)
        {
           pDoc.SetPageSize(new iTextSharp.text.Rectangle(0,0,PageSize.LETTER.Height,PageSize.LETTER.Width));
        }
        pDoc.NewPage();


text:
Q: Why does my program return "Segmentation fault (core dumped)" when I remove a conditional in "else if"? I've written a program that allows me take a command argument of 26 alpha chars to be used as a key at a latter stage of my program to encipher text.
To do this, I had to (a) verify user input alpha chars (b) chars are 26 and (c) none of them repeat.
I decided to put this all in one function(as you'll see below).
This has been successful.
How ever, when I was trying to check whether the key is indeed 26 chars (in my main function) using an else if condition else if (argc != 2 || (is_valid_key(argv[1]) != 1 || is_valid_key(argv[2]) == 2)) I thought that (is_valid_key(argv[1]) != 1 may be useless here sinced I used it in if.
When I did this(regardless of my command argument) my program returned Segmentation fault (core dumped) and I am trying to understand why.
The line causing the problem is else if in my main function.
for context:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int is_valid_key(string verify);
int main(int argc, string argv[])
{
    // check whether the user passed a valid command line argument
    if (argc != 2 || is_valid_key(argv[1]) == 1)
    {
        printf("Usage: ./substitution key\n"); //re-prompt user if they didn't enter a digit
        return 1;
    }
    else if (argc != 2 || is_valid_key(argv[2]) == 2))
    {
        printf("Key must only contain alphabetic characters.\n");
        return 1;
    }

    string plain_text = get_string("plaintext: ");

    printf("%s\n", plain_text);
}

int is_valid_key(string verify)
{
    int i;

    for (i = 0; i < verify[i]; i++)
    {
        char ch = verify[i];

        if (!isalpha(ch))
        {
            return 1; //return for alpha
        }
     }

     if (i != 26)
     {
        return 2; //return for 26 chars
     }

     for (int a = 0; verify[a] != '\0'; a++)
     {
        for (int b = 0; b < a; b++)
        {
            // if 2 characters match, the key is not valid
            if (verify[a] == verify[b])
                return 3; // return for no repeat
        }
    }

    return 4; //return all correct
}

A: Segmentation fault means that you are trying to access a memory location which you shouldn't have. The indexing of arguments starts from 0. And there should be only 2 command-line arguments in this program. So, you are trying to access the index 2 which is out of bounds currently. So, your program exits saying 'Segmentation Fault'.

A: The code is not checking the correct argument in main().
It's testing is_valid_key(argv[2]) but in your test case of only a single command-line parameter:
# ./main qwertyuiopasdfghjklzxcvbnm

There is only:

*

*argv[0] which points to the string "./main"  (or whatever your executable is called)

*argv[1] which points to the string "qwertyuiopasdfghjklzxcvbnm"

The referenced argv[2] does not exist, and references "off the end" of argv, hence the segfault.
Changing this line to:
else if (argc >= 2 || is_valid_key(argv[1]) == 2)   // <<-- HERE
{
    printf("Key must only contain alphabetic characters.\n");
    return 1;
}

will fix it.


text:
Q: Error after deleting NSManagedObject "The operation couldn't be completed" so I'm having a Core Data & iCloud combined Database that is working fine for me.
Some users though had a certain crash after trying to delete NSManagedObject's that are respresented in an UITableView. In the debug-logs that I attach to the crashreports there is the following error-log before the crash:
2013-05-08 22:38:51.851 MyApp[11819:907] Unresolved error Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn't be completed. (Cocoa error 134030.)", {
}

Unfortunately the info about the error: {} is empty and I never had the error myself, so I don't know how to recreate it. It did occur at least 21 times for customers though.
(Whats even worse is, once they reopen the App, some NSManagedObject is in an invalid state and my tableview has problems loading it. But that just at the side)
The actual error is "SIGABRT" in " tableView:commitEditingStyle:forRowAtIndexPath:", here is the respective code:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        ICLog(@"Deleting the row %i,%i from the data source", indexPath.row, indexPath.section);
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        //Save the context
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    }
}

PS: From the Logs its also clear that this is all run from the main thread.
Anyone here who had this problem too?
UPDATE:
Luckily I had the same error in another App I'm working on just now, in a device I have access too (so far I had never saw this happening on any of my devices), so now I can investigate it while it happens. This is what I found out:
a) it still occurs after switching off icloud in the settings
b) the error occurs everytime I try to delete or insert any NSManagedObject, even if I do it in my Appdelegate right after starting, without ever accessing the data somewhere else
So it seems like something completely stops my databse from being updated. I can catch the above the exception, then the App at least isn't crashing. But of course no changes to the database are saved.

A: Errors on [context save:] often occur when you try to save an invalid state of your datamodel.
Since you have deleted an object before, i would suspect that this object was in a relation with some other object that still is present, but now has it's relation in an invalid state (nil for a relation that is non-optional)
Checking your delete rules could help, maybe some relation to the object you delete needs to be optional or you have to propagate the deletion correctly.

A: I will be making some assumptions here.
What I can see is that you delete the CoreData object using the object in fetchedResultsController but you never unset the object from whatever you use as your ViewController iVar fetch storage in numberOfRowsInSection and re-organise your table index after deletion.
Let say your original [indexPath.row count] is 7 then you go on and delete indexPath.row = 5 from your tableView. Then you go on and try to delete another object  at indexPath.row = 6 that item exists on your tableView index because you havent re-organised the indexs, but it wont exist in CoreData.... given that now the max count is 6 that the index value is now 5 of what originally was 6.... This could be what your users are experiencing...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [yourFetchedDataVariable count];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        ICLog(@"Deleting the row %i,%i from the data source", indexPath.row, indexPath.section);
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        //Save the context
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
        // the possible solution
        [yourFetchedDataVariable removeObjectAtIndex:indexPath.row];
        // also now you want to re-order your array index...
        [yourTable reloadData]; // and re order your table indexses aswell
    }
}

A: The optional relationship are you sure it is optional? and optional in what sense to Xcode? I ahd this issue once and it was due to a "optional" relationship.


text:
Q: Adding multiple children to the stage I'm a new flash developer.  I have read here http://www.flashandmath.com/intermediate/children/stage.html that I should avoid adding children to the stage itself and only add them to my MainTimeLine derived main document class (which is itself a child of stage).  However, the author does not give explanation/justification for this approach.
I am developing a project where I am considering adding UI popup windows to the stage directly rather than including them in my MainTimeline (it makes it easier to keep them above everything else and also makes it easier for me to know what I need to persist and what I don't when saving).
What are the downsides of this?  Is it a "bad practice" in Flash?  Why?

A: For quick demos and presentations I often use the Flash IDE's timeline to manage my depths. I create empty movieClips and put them on the different layers. For example, my top layer would be my Popup Layer, under that would be my Main Content Layer, under that would be my Background Layer. My main document class manages the adding and removing of popups, content and background instances.
I believe it is bad practice to add children directly to the Stage. Here is a decent thread explaining some differences between MainTimeLine vs stage.


text:
Q: Download Secure / SSL Heroku PG Backups? When you run heroku pgbackups:url, an Amazon S3 HTTP url is generated. It appears that if you download the database dump it will be sent in the clear? Is there anyway to download it via SSL?
Are pgbackups safe to download in the clear?

A: Perhaps you can put an s in between the http and the :// yourself.


text:
Q: Datalabels are missing in dynamic chart I am trying to create a dynamic chart but the data labels are missing. I add the data labels manually to all headers and then save and close the file. When I open the file and select a different header, they go missing again. Only the chart with the active "header" retains the data label. How do I solve this issue?
This is how my data, named ranges and chart connection looks like
Data

Named ranges

Chart connections

Output

A: The chart is treating the three columns as different series.
Use a formula to copy the data for the selected column into a single column that doesn't change. I have put this formula in G1:
=RIGHT($G$10,1)

And this formula in G2:
=OFFSET(A2:A4,0,G1)

I have list data validation in cell G10, similar to you:

Here, the chart is always using the same range for the data, so it treats it as a single series. As you have added the labels to that series, they are not lost when the data changes.


text:
Q: Magento 2: How to center the Related Products block in product pages? On Blank theme, Related Products block is aligned to the left.
How can I align the block so the products are aligned at the center of the page?
I tried using "text-align: center" but this causes the product name and price are also aligned to center. Product name and price should stay aligned left.

A: I'm finding it a bit dofficult to picture, but I think this article might help?
https://stackoverflow.com/questions/114543/horizontally-center-a-div-in-a-div
See, it sounds like you want to center your  and not the contents. See how you get on.

A: The quick solution to the problem would be to use the working code of:
.related .column.main .product-items {
    text-align: center;
}

And then correct the alignment of the product name and price here:
.block.related .product-item-details {
    text-align: left;
}

These classes are based on the use of the Luma theme in a Magento 2 install.
I did notice that there are some responsive issues with this solution. Once you get down to a mobile view the products aren't centered because of some rouge margins. That can be easily cleaned up with some playing of the values.

A: You could try something like this.
#category-items {
    display: inline-block;
    width: 100%;
#category-items li {
    display: table-cell;
    padding: 5px;
    width: 16.666666667%;
    text-align: center;
    background: #f3dce7;
    border-right: 1px solid #fff;

You'll have to use text-align:left on your product names, probable an
 tag and you might have to wrap you price in a div box and give it also text-align:left. I think it already is in div with "price-box" class.
Anyhow, give it a try.


text:
Q: Windows элемент для выбора из списка(поле раскрывающегося типа) Полистал книги, но не нашел. Как называется такой элемент? как с ним работать? где о нем можно почитать?

A: Это стандартный ListBox. Почитать можно в MSDN: класс ListBox. Пример использования ListBox и ComboBox.
A:  Элементы управления "ListBox" и "ComboBox"


text:
Q: Node.JS function the returns http response value I need to call a function that makes an http request and have it return the value to me through callback. However, when I try I keep getting null response. Any help?
Here is my code:
var url = 'www.someurl.com'
makeCall(url, function(results){return results})

makeCall = function (url, results) {
          https.get(url,function (res) {
           res.on('data', function (d) {
                    resObj = JSON.parse(d);
                    results(resObj.value)

                });
            }).on('error', function (e) {
                     console.error(e);
                });
        }

A: You need to restructure your code to use a callback instead of returning a value. Here is a modified example that gets your external IP address:
var http = require('http');

var url = 'http://ip-api.com/json';

function makeCall (url, callback) {
    http.get(url,function (res) {
        res.on('data', function (d) {
            callback(JSON.parse(d));
        });
        res.on('error', function (e) {
            console.error(e);
        });
    });
}

function handleResults(results){
    //do something with the results
}

makeCall(url, function(results){
    console.log('results:',results);
    handleResults(results);
});


text:
Q: Chrome Javascript Console: Get table data across mult. pages I am trying to collect data from a html <table> that extends across multiple pages using javscript in the chrome 'inspect element'>>'console'. So far I can successfully:

*

*Get data from page 1 into the array

*Open each page using window.open(...)

However, after opening the any of the other pages the appended data always corresponds to the 1st page. So instead of data from 13 pages I get data from page 1 repeated 13 times. Here is the code:
// 'mypage' contains 13 pages of tabular data. Each page is accessed with '&page='
var page = "mypage/?q=&page=";
var pages = 13;
var arr = [];

// loop through all pages
for( var i=1; i<=pages; i++){
    // this opens the next page on browser but the data corresponds to page 1
    var doc = window.open(page + i,"_top").document;
    var table = $(doc).find("table tbody")[0];

    // loops through each row of the table and takes only column 6
    $(table).find('tr').each( function() {
        var row = $(this).find('td');
        arr.push($(row[6]).text());
    });
}

// do something with arr, but it only contains page=1 data repeated 13 times.


text:
Q: Copying multiple files in gnuroot debian I was running GNURoot Debian on my android to get a debian environment (as I am a student and can't afford a PC). I have some image files in a directory and want to copy them all at the same time so I typed the following command
$ cp -v *.png destination

But I got the following error
cp: cannot stat '*.png' : No such file or directory

I understood the error but I can't understand why this happens.
I will be glad if someone can answer me and provide me with an alternate method or solution.

A: This error is being thrown when there are no files matching the wildcard.
Please check if you can see and access these files with ls.
In case you cannot, modifying their permission to be accessible should solve the problem.


text:
Q: JavaScript - modal window with given html how can I open a modal window using javascript only. I can't use own html-file so I have to pass html-data directly to method which will show window. Could you help me with this?

upd:
I can't use any own library.

A: Try a jQuery "lightbox-style" plugin. My favourite is ColorBox which does what you require. Example:
$.fn.colorbox({html:'
Hello
'});

A: Library-less solution:
Make a div filled with content, style it so that it floats over your content and has display:hidden on page load.  With javascript set myDialog.style.display = 'block' and behold your modal.
This javascript may also add a background element that is styled to be translucent and to span the entire screen height and width, and blocks interaction to the page element under it.
In concept it's pretty simple really.  It's more CSS than JS, and the logic is simply showing/hiding the modal dialog element.
And there is lots of edge case improvement you can do with animating the element in, sizing it to fit content better, etc.  This is the sort of polish the libraries give you.

A: Plenty of simple javascript libraries out there to do this sort of thing.  Thickbox is pretty cool.

A: Links found on google (only partially) related to the question that show this issue is not unique. They have not been reviewed.
http://choosedaily.com/1178/15-jquery-popup-modal-dialog-plugins-tutorials/
http://www.webdesignbooth.com/15-jquery-plugins-to-create-an-user-friendly-tooltip/
http://javascript.about.com/library/blmodald3.htm
http://www.digitalmediaminute.com/article/2021/css-and-javascript-modal-dialogs
http://okonet.ru/projects/modalbox/
http://msdn.microsoft.com/en-us/magazine/cc164247.aspx


text:
Q: Cast to a property reference to a subclass in Entity framework (TPT) I've got the following scheme: (not really the code, just to get the idea)
class Person;
class Employee : Person;

class Company
{
    public Person ContactPerson { ...}
    public EntityReference<ContactPerson> ContactPersonReference {....}
}

Employee type got it's own table in the database (Table-per-Type inheritance).
Lets say I've got a Company instance without the ContacePerson loaded.
How do I load the ContactPerson so it will load Employee fields as well (if needed)?
Is there a way to determine it on the select of all the companies as well?
Thanks

A: You should just be able to check by the type of ContactPerson.
if (company.ContactPerson is Employee)
     Console.WriteLine("I'm an Employee");
else
     Console.WriteLine("I'm a Person");

So if the Employee Class had a additional property of BadgeNumber.  You could access that property by casting Person into Employee.
if (company.ContactPerson is Employee)
    Console.Writeline("My badge Number is ", ((Employee)company.ContactPerson).BadgeNumber);


text:
Q: Get data from POSIX timezone files? IE: I'm on Ubuntu 18.04 And looking at /usr/share/zoneinfo, But all the files seem to be written with binary, I would like to get the actual information from the file so any help is greatly appreciated.
(For more info):
I have the goal of taking time zone information / history and putting them into a relational database, So I believe learning how to do this might help with that.


text:
Q: Store about 120 Column based flat data structure to Spark Parquet Scala I am trying to store a flat data structure with about 120 columns as Parquet file in Spark using Scala.
Here is how I have decided to go about it, need few suggestions or ideas to do it better, as for me it looks bit clumsy currently.

*

*Create logical segregation of case class based on the data

*Create one composite case class which would include all the above case classes

*Use Spark explode to split composite columns to individual entities (Looks like spark explode works only on Seq/Array/List, so I am forced to store the case class elements as Seq in step 2)

*Write to Parquet.

Ideas to do it better ?

A: You don't mean explode. Explode creates new rows. You can split a StructType column into multiple columns with a single select statement.
Like this:
case class Act(a: Int, b: Seq[String])
case class Boo(a1: Int, b1: String)
case class C(a: Act, b: Boo)

val df = Seq(C(Act(1, Seq("test")), Boo(2, "this is"))).toDF

df.show
+--------------------+-----------+
|                   a|          b|
+--------------------+-----------+
|[1,WrappedArray(t...|[2,this is]|
+--------------------+-----------+

df.printSchema
root
 |-- a: struct (nullable = true)
 |    |-- a: integer (nullable = false)
 |    |-- b: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |-- b: struct (nullable = true)
 |    |-- a1: integer (nullable = false)
 |    |-- b1: string (nullable = true)

df.select($"a", $"a.a", $"a.b", $"b", $"b.a1", $"b.b1").show
+--------------------+---+------+-----------+---+-------+
|                   a|  a|     b|          b| a1|     b1|
+--------------------+---+------+-----------+---+-------+
|[1,WrappedArray(t...|  1|[test]|[2,this is]|  2|this is|
+--------------------+---+------+-----------+---+-------+


text:
Q: YARN Containers and Spark Executors I currently have a functioning cluster of 1 Driver(8 cores and 32GB RAM) and 2 Workers (One of 8cores and 32gb RAM other of 8cores and 16gb RAM)
However I seem to have a little confusion between the Containers generated and Spark Executors in order to maximize efficiency.
My current Configs are the following:
Worker 1:

Worker 2:

and my SparkSession Configs are these:

I would expect to get 3 Containers running in Yarn, 1 for driver and 2 for Spark, however the output I'm getting is the following:

Only two Containers, which one is allocated for RM and the second one for Worker. However only one if my workers (the one with 16gb RAM) is creating an executor, why is the other one not creating an executor?
How can I achieve maximum resource usage to have a high speed Spark Application


text:
Q: Posting raw data with Python I'm playing around with the Google Checkout API and I want to pull it into a Django app. I need to post data to Google using basic http authentication. I've been testing this with curl like this:
curl -d "$(cat mytest.xml)" -u username:password https://url

And that posts the content of my test XML file to Google. And it works fine!
But I'm having problems porting that simple line to Python. I've managed several different ways (httplib2, urllib2, pycurl) of connecting with a password and posting something but the respose is always 400 BAD REQUEST.
Is there a python equivalent for posting block of text to a HTTP Basic auth server? I'm running out of walls to bang my head against.

Apologies for not adding any code. Here are some of my greatest hits. In each, DATA is an XML string. URL, USERNAME and PASSWORD are constant.
req = urllib2.Request(URL)
req.add_header("Authorization", "Basic %s" % base64.encodestring('%s:%s'%(USERNAME, PASSWORD)))
u = urllib2.urlopen(req, DATA)

Gives me a lovely HTTP Error 400: Bad Request

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, URL, USERNAME, PASSWORD)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(URL, DATA)

Gives HTTP Error 401: Unauthorized

pycurl.global_init(pycurl.GLOBAL_DEFAULT)
c = pycurl.Curl()
c.setopt(pycurl.URL, URL)
c.setopt(pycurl.USERPWD, "%s:%s" % (USERNAME,PASSWORD))
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.HTTPHEADER, ["Content-type: text/xml"])
c.setopt(pycurl.POSTFIELDS, DATA)
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()

Seems to struggle with passing the DATA string as a POSTFIELD. I've tried urllib.urlencode()ing DATA in several different ways but

h = httplib2.Http()
h.add_credentials(USERNAME, PASSWORD)
print = h.request(URL, "POST", body=base64.encodestring(DATA))

The credentials don't seem to do anything - I get an unauthorised message back from Google.
There are more but they're all based on these.

A: Voidspace has an excellent article on using basic auth with urllib2. I've copied the appropriate code snippet below, changed to use POST.
import urllib2

theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)

pagehandle = urllib2.urlopen(theurl, open("mytext.xml").read())

Without seeing your code it's hard to say why you would be getting a 400 response.

A: While editing my post to include some source, I thought I'd have another crack at httplib2 (mainly because it's comparatively small and pretty compared to the others) and noticed that there's a gaping bug in that its add_credentials(..) method doesn't actually do anything. You can work around this by specifying the header (as I did with urllib2) like this:
resp, content = httplib2.Http().request(URL, "POST", body=DATA, headers={
    "Authorization": "Basic %s" % base64.encodestring('%s:%s' %(USERNAME, PASSWORD)
})

And this works.

A: I've been having similar turmoils with the stdlib packages, until somoneone pointed to the awesome requests that supports basic Http Authentication and other authentication means straight out-of-the-box! And it has a beautiful and simple API it hurts!
requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))

It supports a host of other necessary features (e.g HTTPS, Digest Authentication, etc) Please check it out if u must...


text:
Q: How to convert a string to a double with 6-digit precision in C++? I want to know how to convert a string like "1234.123456" to double or float.
I need at least 3 digits precision (i.e. 3 digits after the decimal point, regardless of the number of digits before the point).

A: The exact value 1234.123456 isn't representable in any of the usual
machine floating point formats.  All you can do is choose how much
accuracy you need, and use it.  (On most modern machines, double has
16 digits precision.  But that still doesn't mean that all 16 digit
values are exactly representable.)
As for the conversion, just do what you would do to convert any type:
std::istringstream s( "1234.123456" );
double d;
s >> d;

And read
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html.  It will
explain the basic minimum you need to know in order to safely use
machine floating point.

A: #include<stdlib.h>

int main()
{
    double dnum = atof( "1234.123456" ) ;

    printf ( "%f\n" , dnum ) ;

    return 0 ;
}


text:
Q: How to create composite figures in draw2d.js I've looked through the collection of examples, that go with the library, but unfortunatelly, all examples, devoted to composite figures, are based on parsing json file.
reader.unmarshal(canvas, jsonDocument);

However, what I want to see is how to create composite figures from basic ones, something like:
var figure_1 = new draw2d.shape.basic.Rectangle(....);
var figure_1 = new draw2d.shape.basic.Diamond(....);
... then do something, so that figure_1 and figure_2 are now part of
... a composite figure

PS. I think what I need is StrongComposite, but I do not know how to use it. Hope someone can help!
EDIT
This is what I tried:
var baseRectangle =  new draw2d.shape.composite.StrongComposite({width: 200, height: 200, x: conf.x, y: conf.y});
var top = new draw2d.shape.basic.Oval({width: 120, height: 40, x: conf.x, y: conf.y});
var bottom = new draw2d.shape.basic.Oval({width: 120, height: 40, x: conf.x, y: conf.y + 60});
baseRectangle.assignFigure(top);
baseRectangle.assignFigure(bottom);
canvas.add(baseRectangle);

But it does not work. I only see a gray box. I also tried this:
var baseRectangle =  new draw2d.shape.composite.StrongComposite({width: 200, height: 200, x: conf.x, y: conf.y});
var top = new draw2d.shape.basic.Oval({width: 120, height: 40, x: conf.x, y: conf.y});
var bottom = new draw2d.shape.basic.Oval({width: 120, height: 40, x: conf.x, y: conf.y + 60});
baseRectangle.assignFigure(top);
baseRectangle.assignFigure(bottom);
canvas.add(top);
canvas.add(bottom);

But as a result, I got absolutely independent ovals.

A: You also have to add baseRectangle to canvas.
var baseRectangle = new draw2d.shape.composite.StrongComposite({
    width: 200,
    height: 200,
    x: conf.x,
    y: conf.y
});
canvas.add(baseRectangle);

var top = new draw2d.shape.basic.Oval({
    width: 120,
    height: 40,
    x: conf.x,
    y: conf.y
});
var bottom = new draw2d.shape.basic.Oval({
    width: 120,
    height: 40,
    x: conf.x,
    y: conf.y + 60
});

baseRectangle.assignFigure(top);
baseRectangle.assignFigure(bottom);

canvas.add(top);
canvas.add(bottom);

A: In addition to needing to put the child elements on the canvas (sorry, can't comment on existing answer yet): I found I need to wait a frame (nextTick with Vue) before assignFigure can work. Otherwise draw2d throws exception:
TypeError: Cannot read properties of null (reading 'paper')
    at Class.createShapeElement (null:23614:34)
    at Class.getShapeElement (null:8492:33)
    at Class.toFront (null:8351:22)
    at Class.toFront


text:
Q: Could not find default endpoint element that references contract using ConfigurationChannelFactory I want to consume an external webservice using MS Dynamics AX.
The normal way to do this is to create a C# class library, with a service reference in it. Then, back in the days, you could simply press a button "Deploy to AX" and your dll was installed And could be consumed.
Now:
Now I needed to implement some security protocol (TLS1.2) in that class library.
Now for TLS1.2 I needed to use .net Framework 4.7 and VS2010 does not support this.
So, I ended up creating a new class library in VS 2017, and deploying it manually in the bin folders of our AX.
So my solution was to add an extra class in this class library, that sets the security protocol before calling the service methods from the service reference. All the rest is similar to the old class library.
The problem is that I can consume my custom client in AX, but I keep getting the error System.InvalidOperationException: Could not find default endpoint element that references contract 'Messaging.Messaging'.
Here's what I have created:
My .net project using the service reference and one simple class, that I call from AX:

Then here is how I want to consume that service in the class.
I used the ConfigurationChannelFactory, but still getting the enpoint error in AX. When using a console application in .net it works perfectly fine.


text:
Q: Finding number of methods used in a java program after selecting the file Are there any specific methods or functions to calculate the number of methods and not the constructors in java?
Very important, please share if you know something.

A: Try this :
Method[] declaredMethods = YourClass.class.getDeclaredMethods();
for (Method method : declaredMethods) {
    System.out.println(method.getName());
}


text:
Q: Copy profile data using robocopy with permission I'm trying to copy the ChromeData subfolder with permissions that may or may not be inside user profiles. so the folder structure is as follows.
-user1
 -chromeData
 -contacts
 -desktop

-user2
 -chromeData
 -contacts
 -desktop

the destination should be like this.
-user1
 -ChromeData

-user2
 -ChromeData

My code is as follows. It does copy the content in the chromeData folder to the destination, but it does not copy the permissions. Please note that I have used /mir /secfix and /copyall with robocopy. None of them worked. I saw a post saying robocopy does not copy inherited permissions. If this is true I need a workaround.
@echo off
setlocal EnableDelayedExpansion
set Source=F:\DFSroot\Redirected Content\
set Target=H:\Redirected ChromeData\
rem dir /s /ad /b "%Source%*.*" | find /i "\ChromeData" > C:\Temp\dir.txt

for /F "tokens=*" %%a in (C:\Temp\dir.txt) do (
set T1=%%a
call set T2=!T1:%Source%=%Target%!
robocopy "%%a" "!T2!" /copyall
pause
)

UPDATE
Found that permission is being copied for the chromedata folder but not its parent folder.

A: Use the following command to copy with the ACLs
robocopy "source address" "destination address" *.* /sec

Use the following command to fix an existing tree.
robocopy "source address" "destination address" *.* /secfix /sec

Found this information on this blog


text:
Q: GLMMs for count data shows significant deviation according to DHARMa diagnostics qqplot I am making a GLMM to test for various aspects of grooming in primates. I have made 3 different models for the different species. For 1 of the 3 models, I am getting an issue with the qqplot.
The data fits well with poisson distribution according to diagnose() in glmmTMB (I also ran it with nbinom2 - gives errors, poisson does not).
m3 <- glmmTMB(Groom_giv ~ Grph+Receiver_rank+Rank_diff+
             (1|Group)+(1|Actor)+(1|Receiver)+
             offset(log(Hours)),
           family=poisson,
           data = ER_M)

But the qqplot in DHARMa shows deviation is significant according to both the KS test and the dispersion test.

Going through the FAQs page I found that this might be indicating Underdispersion. And looking at he coefficient estimates I believe it might be the case.
 Family: poisson  ( log )
Formula:          Groom_giv ~ Grph + Receiver_rank + Rank_diff + (1 | Group) +      (1 | Actor) + (1 | Receiver) + offset(log(Hours))
Data: ER_M

     AIC      BIC   logLik deviance df.resid
   275.0    293.5   -130.5    261.0       97

Random effects:

Conditional model:
 Groups   Name        Variance  Std.Dev.
 Group    (Intercept) 2.577e-12 1.605e-06
 Actor    (Intercept) 6.516e-11 8.072e-06
 Receiver (Intercept) 1.261e-10 1.123e-05
Number of obs: 104, groups:  Group, 4; Actor, 32; Receiver, 32

Conditional model:
                Estimate Std. Error z value Pr(>|z|)
(Intercept)   -1.9341019  0.1878505 -10.296   <2e-16 ***
Grph           2.0189943  0.1982866  10.182   <2e-16 ***
Receiver_rank -0.0018369  0.0178349  -0.103    0.918
Rank_diff     -0.0002208  0.0233696  -0.009    0.992
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

I am new to GLMMs, can someone suggest how I should proceed with this model?

A: Yes, the plot shows underdispersion, i.e. you fit your data much better than expected under a Poisson.
A common reason for underdispersion is overfitting, i.e. your model is too complex. I would have the suspicion that this could be the case, with 68 REs for 104 data points, although your RE SD is very low. Other possible explanations to check for include zero-inflation (best to check by comparing to a ZIP model), non-independence of the data (e.g. temporal autocorrelation, check via DHARMa:: testTemporalAutocorrelation), or that grooming is simply not a Poisson process (which I would also find easy to imagine).
From a technical side, underdispersion is not as concerning as over dispersion, as it will usually bias p-values to the conservative side, but if your goal is to see if there is an effect of rank, you may want to consider a simpler model. If that is not helping, you can move to a distribution for underdispersed count data (e.g. Conway-Maxwell-Poisson, generalized Poisson).
p.s.: glmmTMB::diagnose does not check model fit.

A: Maybe exploring a Quasi-Poisson regression might solve the issue. Nevertheless, be aware that, contrary to overdispersion which is a common problem with methods to deal with, underdispersion might have other impacts and implications about your data.
Take a look at this question for several links that may help you.


text: Q: Emulate USB as CD? So I am currently learning about computers and figured this would be a fun lesson: I own a game called Risk II. I need a CD to play it, I gave it to a friend for 2 weeks so he can play. I copied all the files in that CD to the computer cause I figured the CD was only there for the game to retrieve the files in case the user chose other than Maximum. Apparently I need it so anyway I can emulate a USB for a CD for the mean time?


text:
Q: How to return the return value of the Runnable or Callable passed to ScheduledExecutorService.schedule public Record task(Id id, Supplier<Record> elector) {
    // elector is: '() -> functionName(id, stats)'

    final long delayTime = calculateTimeToDelay();

    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

    // Cannot resolve method 'schedule(Record, long, TimeUnit)'
    return ses.schedule(elector.get(), timeToDelay, TimeUnit.MILLISECONDS);

    // try {
    //     Thread.sleep(delayTime);
    // } catch (final InterruptedException e) {
    //     log.error(e);
    // }
    // return elector.get();
}

As you can see, the commented out code returns what elector.get() returns, which is a Record. But instead of using Thread.sleep(delayTime), I'm trying to use ScheduledExecutorService to call elector.get() after a few milliseconds of a delay. Not sure what Runnable and Callable is and whether elector.get() would count as one of those.
Some direction here would be appreciated.

A: ScheduledExecutorService.schedule requires a Callable so you'll have to convert your Supplier into a Callable, for example, via the method reference syntax:
ses.schedule(elector::get, timeToDelay, TimeUnit.MILLISECONDS);


text:
Q: Explain the meaning of JPA Criteria API From class and its type parameters What is the purpose of class javax.persistence.criteria.From and what do its type parameters Z and X stand for ?
The documentation is not clear at all.
I became even more confused after I saw that the type javax.persistence.criteria.Root has the following definition:
public interface Root<X> extends From<X,X>

A: It is a common interface for: javax.persistence.criteria.Join and javax.persistence.criteria.Root to allow consistency when you call one of the methods:

*

*javax.persistence.criteria.Join#getParent

*javax.persistence.criteria.From#getCorrelationParent
Let's try explain using javax.persistence.criteria.Join#getParent
When You call javax.persistence.criteria.Join#getParent result can be another Join or Root and a common interface for both is javax.persistence.criteria.From
See example:
Root<User> user = query.from(User.class);
Join<User, Account> account = user.join(User_.account);
Join<Account, AccountRole> accountRole = account.join(Account_.accountRoles);

then
From<?, User> root = account.getParent();// here we have Root<User> extends From<User, User>
From<?, Account> join = accountRole.getParent();// here we have Join<User, Account> extends From<User, Account>

And as You can see in the above example Z and X stand for a type of left and right side of the join.


text:
Q: como separar numero php? Estoy haciendo un contador de regsistro
tengo el siguiente resultado :
codigo:

   {{count}}

Resultado:

Quiero hacer que cada 9> cree un nuevo span y me genere  esto:

A: Podrías probar algo así:
<?php
$count = 25;
// crea un array de números
$numeros = str_split($count);

// si el array de los números es < 5 agrega un 0 delante
while(count($numeros) < 5){
    array_unshift($numeros,0);
};

//print_r ($numeros);

// declara una nueva variable, una cadena de texto vaía
$html = "";
// para cada elemento del array de los números crea un elemento span
foreach ($numeros as $val) {
    $html .= ''.$val.'';
}

echo $html;


text:
Q: Get the auto id for inserted row into Redshift table using psycopg2 in Python I am inserting a record into a Amazon Redshift table from Python 2.7 using psycopg2 library and I would like to get back the auto generate primary id for the inserted row.
I have tried the usual ways I can find here or in other websites using google search, eg:
conn=psycopg2.connect(conn_str)
conn.autocommit = True

sql = "INSERT INTO schema.table (col1, col2) VALUES (%s, %s) RETURNING id;"

cur = conn.cursor()
cur.execute(sql,(val1,val2))
id = cur.fetchone()[0]

I receive an error on cur.execute line :
ProgrammingError: syntax error at or near "RETURNING"

Does anybody know how to fix this or accomplish the same thing?

I have to use psycopg2 in my code

A: Currently not possible with Redshift, as it doesn't support returning the last insert id via the RETURNING syntax. What you might need to do is use a SELECT MAX(id) FROM schema.table; inside a transaction, which probably not quite what you wanted to hear but appears to be the best you can do with the current state of Redshift.

A: At this moment, Redshift still doesn't support RETURNING syntax, and I couldn't find here a satisfying answer. So I'm posting a generic solution in case anyone needs it.
The only assumption for this solution is that you know how many records you've just inserted. Assuming x is the numbers of records inserted, you can run this query:
SELECT id
FROM table
ORDER BY id DESC
LIMIT {x}

Very important! you have to run this query together with the insert one in the same transaction. Otherwise, it won't work.

A: You can also query for the id in a select if you know how to uniquely find the row without id.

A: You could use following query to get the last inserted id from redshift.
SELECT top 1 id from sampletable where created < Getdate() order by created desc;

where 'id' is the field you are interested in and 'created' is the field having datetime information.
The reason being using the created date time information is, if the table is used for bulk insert there is a chance for having records with id's that are sequential like 1,33,35,56,103, etc.....
In the above scenario, using max(id) wont work as expected.
because the last inserted id could be any number which was not already inserted earlier.

A: Assuming that you aren't (potentially) inserting duplicates, you could do this with python. I'm assuming that your provided code is in a loop; the specifics of the loop don't matter, but put the # before the loop section before the loop.
# before the loop
# you probably have a list or dict of values that you're inputting. Re-use that if you can; if you can't, create a dict
sample_dict = {}
# end before the loop

/* existing code */
conn=psycopg2.connect(conn_str)
conn.autocommit = True

# use this query instead of your current one (just remove the RETURNING clause)
ins_sql = "INSERT INTO schema.table (col1, col2) VALUES (%s, %s);"

# this query will get the id of those last added values
sel_sql = "SELECT id FROM schema.table WHERE col1 = %s AND col2 = %s ORDER BY id DESC LIMIT 1;"

cur = conn.cursor()
cur.execute(ins_sql,(val1,val2))

# new stuff here!
cur.execute(sel_sql,(val1,val2))
id = cur.fetchone()[0]
sample_dict[val1 + '|' + val2] = id

Caveats:

*

*I haven't tested this exact script

*This will probably not work if you're inserting duplicate values

*You aren't sanitizing your input or using prepared statements (Not 100% sure that's an option, TBH)

*You know more about your database and code structure than I do; leverage that knowledge

*This is not the most efficient solution, but it should work for what you want.


text:
Q: Which xpath will work for the html code I have the following html code for a radio button

  <input id="gwt-uid-451" class="WLOW" type="radio" name="ViewModel_513" value="on" tabindex="0" checked="">
  Smart Calculation Based on Events

And I tried to use the following xpath:
//label[text()='Smart Calculation Based on Events']/preceding-sibling::input[@type='radio']

Which is not working.

A: As per the HTML you have provided you can use the following xpath :
//input[@class='WLOW' and starts-with(@id,'gwt-uid-') and starts-with(@name,'ViewModel_')]

Or you cab get more granular as follows :
//span[@class='gwt-RadioButton WPOW WCOW WJPW WAPW' and starts-with(@id,'ViewModel_')]/input[@class='WLOW' and starts-with(@id,'gwt-uid-') and starts-with(@name,'ViewModel_')]

A: Sometimes, if you click on the text, the checkbox will not be selected. Try using one mentioned below.
//input[@type ='radio'] (or)
//input[@type ='radio' and starts-with(@id,'gwt-uid-')]

/*If you have more than one checkbox, use value in an index as per selection */

 (//input[@type ='radio'])[index]
 (//input[@type ='radio' and starts-with(@id,'gwt-uid-')])[index]

For example, the page has two checkboxes and need to click on the second one.
(//input[@type ='radio'])[2]
(//input[@type ='radio' and starts-with(@id,'gwt-uid-')])[2]


text:
Q: How to initialise data in JPA, only if the Schema is generated Bonjour,
I am working on changing me Java application from using postgres to an embedded database. I would like the application to deploy with an initial set of data in the database. In the past during installation I have executed an sql script to fully generate the schema and insert the data in to my tables.
Ideally (becasue I don't really want to work out how to connect to the embedded database to generate it) I want to let JPA create my schema for the first time, and when it does I then want to be able to run my SQL to insert the data.
My search has turned up the obvious hibernate and JPA properties that allow running of an SQL script.
Firstly I found when using "hibernate.hbm2ddl.auto" you can define an import.sql file this made me very happy for a day until I realised it only works with create and not with update. My application when using postgres had this set to update. And what i would really like is for it to know if it's had to create the schema and if it has then run the import.sql. No Joy though.
I then moved on to using "javax.persistence.schema-generation.database.action" set to "create" I figured using the JPA specification was probably wiser anyway and so I defined "javax.persistence.sql-load-script-source" the spec says for "create"

The provider will create the database artifacts on application
  deployment. The artifacts will remain unchanged after application
  redeployment.

This lead me to believe it would do exactly what I wanted, only create the tables "on application deployment" however when I ran my tests using this, each test (creating a new spring context) tried to just create all the tables again and obviously failed, which made me realise application deployment didn't mean what i thought it meant (wishful thinking) and now I realise that JPA doesn't seem to even have an equivalent of Hibernates "update" property, so it's always going to generate the tables?
What I want is to have my tables and data generated when you first spin up the app and for subsequent executions to know the data is there and use it, I am assuming it's too much to hope for that this exists, but i'm sure that this must be a common requirement? So my question is what is the general recommended way to achieve the goal of allowing JPA to create my schema but being able to insert some data in to a db that persists between executions?

A: The answer is flyway. It is a database migration library, and if you are using Spring boot it is seamlessly integrated, with regular Spring you have to create a bean, which get a reference to the connection pool, creates a connection and does the migration.
Flyway creates a table so it keeps track of which scripts has already been applied to the database, and the scripts are simply part of the resources.
We normally use JPA to generate the initial script. This script becomes V1__initial.sql, if we need to add some data we can add V2__addUsers.sql and V3__addCustomers.sql etc.
Later when we need to rename columns or add additional tables, we simply add new scripts as part of the War file, and when the application is loaded Flyway looks at it's internal table, to see the current version, and then applies any new scripts to bring it up to de desired version.
In Spring the code would look like this
private void performFlywayMigration(DataSource dataSource) {
    Flyway flyway = new Flyway();
    flyway.setLocations("db/migration");
    flyway.setDataSource(dataSource);
    log.debug("Starting database migration.");
    flyway.migrate();
    log.debug("Database migration completed.");

    MigrationInfo current = flyway.info().current();
    if (current.getState() == MigrationState.FUTURE_SUCCESS) {
        log.warn("The Database schema is version " + current.getVersion() + ", this application expects version " + flyway.getBaselineVersion().getVersion());
    }
}

In general you should not JPA to create tables directly. because you sometimes need to modify the scripts, for instance on Sybase Varchar(255) means 255 bytes, so if you are storing 2 or 3 byte Unicode chars, you need more space - JPA implementation does not account for that (last time I checked).


text:
Q: Supplied parameters do not match any signature of call target (react-mock-store) Getting the following error and I don't understand because it seems like I am matching the signature

[ts] Supplied parameters do not match any signature of call target.
  const mockStore: (state?: {
      todo: string[]; } | undefined) => IStore<{
      todo: string[]; }>

import configureMockStore from 'redux-mock-store'

type MyStore = {
    todo: string[];
}

const mockStore = configureMockStore<MyStore>([]);

let storeVar : MyStore = {todo: ['one','two']};
const store = mockStore<MyStore>(storeVar);

The typedef for redux-mock-store is coming from DefinitivelyTyped:
// Type definitions for Redux Mock Store v0.0.6
// Project: https://github.com/arnaudbenard/redux-mock-store
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

///<reference types="redux" />

declare module 'redux-mock-store' {
    import * as Redux from 'redux'

    function createMockStore<T>(middlewares?: Redux.Middleware[]): mockStore<T>;

    export type mockStore<T> = (state?: T) => IStore<T>;

    export interface IStore<T> {
        dispatch(action: any): any;
        getState(): T;
        getActions(): any[];
        clearActions(): void;
        subscribe(listener: Function): Function;
    }

    export default createMockStore
}

A: You don't have to specify the type parameter when you call mockStore. createMockStore already returns a mockStore with the type filled:
const store = mockStore(storeVar);


text:
Q: Modules of algebraic integers Let $z \in \mathbb{C}$ be an algebraic integer. Is then $|z| \in \mathbb{R}$ also an algebraic integer?

A: With $z$ also $\overline{z}$ is an algebraic integer, because it is a root of the same minimal polynomial. Since the algebraic integers form a ring, also the product $z\cdot\overline{z}$ is an algebraic integer. Then also its square root, i.e., $|z|=\sqrt{z\overline{z}}$.


text:
Q: Polylang : Interverting languages after development My client asked me to switch French and English after the site was developed.
So I did two things:
Polylang > Languages: I selected English by default (asterisk on English)
Polylang > Settings: I disabled the option "Hide language information in web address for default language" to avoid rewriting hard URLs
Admin > Settings > Reading > The home page displays: I have selected the "home" which is my homepage in English.
Still, it does not work, It's always the French page that appears by default...
Best Regards


text:
Q: Fortran Sort Method Numerical recipies i m using C to Call Fortran,
my fortran is calling sort() method
 *-----------------------------------------------------------------------
 * SUBROUTINE sort(A,n)
 * Subroutine de la librairie "Numerical Recipes"
 * (C) Copr. 1986-92 Numerical Recipes Software
 *-----------------------------------------------------------------------
      SUBROUTINE sort(arr,n)
      INTEGER n,M,NSTACK
      REAL arr(n)
      PARAMETER (M=7,NSTACK=50)
      INTEGER i,ir,j,jstack,k,l,istack(NSTACK)
      REAL a,temp
      jstack=0
      l=1
      ir=n
1     if(ir-l.lt.M)then
        do 12 j=l+1,ir
          a=arr(j)
          do 11 i=j-1,1,-1
            if(arr(i).le.a)goto 2
            arr(i+1)=arr(i)
11        continue
          i=0
2         arr(i+1)=a
12      continue
        if(jstack.eq.0)return
        ir=istack(jstack)
        l=istack(jstack-1)
        jstack=jstack-2
      else
        k=(l+ir)/2
        temp=arr(k)
        arr(k)=arr(l+1)
        arr(l+1)=temp
        if(arr(l+1).gt.arr(ir))then
          temp=arr(l+1)
          arr(l+1)=arr(ir)
          arr(ir)=temp
        endif
        if(arr(l).gt.arr(ir))then
          temp=arr(l)
          arr(l)=arr(ir)
          arr(ir)=temp
        endif
        if(arr(l+1).gt.arr(l))then
          temp=arr(l+1)
          arr(l+1)=arr(l)
          arr(l)=temp
        endif
        i=l+1
        j=ir
        a=arr(l)
3       continue
          i=i+1
        if(arr(i).lt.a)goto 3
4       continue
          j=j-1
        if(arr(j).gt.a)goto 4
        if(j.lt.i)goto 5
        temp=arr(i)
        arr(i)=arr(j)
        arr(j)=temp
        goto 3
5       arr(l)=arr(j)
        arr(j)=a
        jstack=jstack+2
        if(jstack.gt.NSTACK)pause 'NSTACK too small in sort'
        if(ir-i+1.ge.j-l)then
         istack(jstack)=ir
         istack(jstack-1)=i
         ir=j-1
       else
         istack(jstack)=j-1
         istack(jstack-1)=l
         l=i
       endif
     endif
     goto 1
     END

And if i call sort method many times, i have a segfault in this method :(
It's legacy code but i'm trust in it because it come from numerical recipies.
But i'm suspicious about some things, in particular this line :
if(jstack.gt.NSTACK)pause 'NSTACK too small in sort'

If i'm in this case, my programm will in pause? how it's possible that a sort method do this?
And if this line is suspicious, how can i trust the entire code?
does anyone know a problem with this sort subroutine? does anybody know another method to doing sort in fortran? Because i can replace this sort method by another one but i'm new in fortran and i can't write another one.
I add that no problem if i run this method in mono thread, but if i run it in multi thread environement, problem is here. sorry to don't mentionned when i wrote my question but i see this after writing it.
DEBUG information
current thread: t@41
  [1] __lwp_kill(0x0, 0x6, 0x0, 0x6, 0xffbffeff, 0x0), at 0xff2caa58
  [2] raise(0x6, 0x0, 0xff342f18, 0xff2aa378, 0xffffffff, 0x6), at 0xff265a5c
  [3] abort(0x7400, 0x1, 0x0, 0xfcb78, 0xff3413d8, 0x0), at 0xff24194c
  [4] os::abort(0x1, 0x0, 0xff011084, 0xfefdc000, 0x7d94, 0x7c00), at 0xfee7d3cc
  [5] VMError::report_and_die(0x0, 0xff038640, 0xff031ff4, 0x1, 0xfee81b94, 0xff031ff4), at 0xfef0cd58
  [6] JVM_handle_solaris_signal(0xb, 0xacffefe0, 0xacffed28, 0x8000, 0xff030fa0, 0x2013d8), at 0xfea73d48
  [7] __sighndlr(0xb, 0xacffefe0, 0xacffed28, 0xfea7325c, 0x0, 0x1), at 0xff2c6e78
  ---- called from signal handler with signal 11 (SIGSEGV) ------
  [8] sort_(0xfe2b1350, 0xfe2b135c, 0xfe2b1000, 0x1c00, 0x443bfc7b, 0xfe292484), at 0xfe27e498
  [9] mediane_(0xa9c1624c, 0xacfff2ac, 0xa9c16060, 0xa9c05c34, 0x0, 0x19), at 0xfe27a38c

(dbx) frame 8
0xfe27e498: sort_+0x01d8:       ld       [%l4 + %l1], %f4
(dbx) disassemble
0xff2caa58: __lwp_kill+0x0008:  bcc,a,pt  %icc,__lwp_kill+0x18  ! 0xff2caa68
0xff2caa5c: __lwp_kill+0x000c:  clr      %o0
0xff2caa60: __lwp_kill+0x0010:  cmp      %o0, 91
0xff2caa64: __lwp_kill+0x0014:  move     %icc,0x4, %o0
0xff2caa68: __lwp_kill+0x0018:  retl
0xff2caa6c: __lwp_kill+0x001c:  nop
0xff2caa70: __lwp_self       :  mov      164, %g1
0xff2caa74: __lwp_self+0x0004:  ta       %icc,0x00000008
0xff2caa78: __lwp_self+0x0008:  retl
0xff2caa7c: __lwp_self+0x000c:  nop

in m in solaris with dbx=> gdb on
i try to inspect adress but what can i type to have interesting informations?
After adding -g option to f90 compiler, in dbx i can see value or var and see the result:
t@88 (l@88) terminated by signal ABRT (Abort)
0xff2caa58: __lwp_kill+0x0008:  bcc,a,pt  %icc,__lwp_kill+0x18  ! 0xff2caa68
Current function is sort
  578           temp=arr(k)
(dbx) print n
n = 19
(dbx) print arr
arr =
    (1)    725.0666
    (2)    741.5034
    (3)    730.8196
    (4)    754.3707
    (5)    741.718
    (6)    741.718
    (7)    741.8914
    (8)    745.9141
    (9)    744.6705
    (10)    741.718
    (11)    745.8358
    (12)    743.3788
    (13)    746.2706
    (14)    746.2706
    (15)    750.1498
    (16)    754.3707
    (17)    754.3707
    (18)    754.3707
    (19)    748.2084
(dbx) print istack
istack =
    (1)    7
    (2)    12
    (3)    17
    (4)    18
    (5)    8
    (6)    9
    (7)    1
    (8)    4
    (9)    0
    (10)    0
    (11)    0
    (12)    0
    (13)    0
    (14)    0
    (15)    0
    (16)    0
    (17)    0
    (18)    0
    (19)    0
    (20)    0
    (21)    0
    (22)    0
    (23)    0
    (24)    0
    (25)    0
    (26)    0
    (27)    0
    (28)    0
    (29)    0
    (30)    0
    (31)    0
    (32)    0
    (33)    0
    (34)    0
    (35)    0
    (36)    0
    (37)    0
    (38)    0
    (39)    0
    (40)    0
    (41)    0
    (42)    0
    (43)    0
    (44)    0
    (45)    0
    (46)    0
    (47)    0
    (48)    0
    (49)    0
    (50)    0
(dbx) print jstack
jstack = -31648
(dbx)

how its possible taht jstack have a -31648 val! istack have only 50 element and istack(jstack) retrun me a abd value! how its possible? :)
thanks by advance

A: Too large for a comment:
Unfortunately the stack trace does not show the exact line of failure. What is the evidence that the error is at the line you indicated. I could imagine there could be error in calling the run-time system, sou you should try to change the PAUSE statement to write, read *, or something similar.
I did some tests with your subroutine in gfortran:
  parameter (n = 100000)
  dimension b(n)

  do i=1,1000
    call random_number(b)
    call sort(b,n)
  end do
end

with different array sizes and loop bounds. This calls the sort with many different inputs. I enabled all checks and sanitizations and didn't encounter a single problem.
Edit:
It works with OpenMP too:
  parameter (n = 100000)
  real,allocatable :: b(:)

  !$omp parallel private(b)
  allocate(b(n))
  !$omp do
  do i=1,1000
    call random_number(b)
    call sort(b,n)
  end do
  !$omp end do
  !$omp end parallel
end


text:
Q: Segmentation Fault(core dumped) hey guys i have got this code: (im trying to read a string and put it inside the output file)
#include "structs.h"
#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE* input = fopen("journal.txt", "r");
  FILE* output = fopen("output.txt", "w");
  char date[9];

  if( ferror(input) || ferror(output) ) {
    perror("Error opening input/output file\n");
  }

  fscanf(input, "%s", date);
  fgets(date, 9, input);
  fputs(date, output);
  fclose(input);
  fclose(output);
  return 0;
}

it compiles properly but at runtime it shows the error
 Segmentation fault (core dumped)

i have no idea why :( please help

A: You need to check whether fopen returns NULL:
#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE * input;
  FILE * output;
  char date[9];

  input = fopen("journal.txt", "r");
  if(input == NULL){
    perror("Could not open input file");
    return -1;
  }

  output = fopen("output.txt", "w");
  if(output == NULL){
    perror("Could not open output file");
    fclose(input);
    return -1;
  }
/* ... snip ... */

Your input file probably doesn't exist. Calling ferror on NULL results in a segmentation fault.

A:  #include <stdio.h>
 #include <stdlib.h>

   int main ()
 {
 FILE* input = fopen("journal.txt", "r");
 FILE* output = fopen("output.txt", "w");
 char date[9];

 if(input)
 {
   fscanf(input, "%s", date);
    fgets(date, 9, input);
 }
else
 {
  printf("error opening the file");
 }

if(output)
{
   fputs(date, output);
}

 else
 {
  printf("error opening the file");

 }

You were receiving the Segmentation fault as you were reading from a non-existing file 'journal.txt' and calling Ferror triggers Segmentation Fault.


text:
Q: PyMongo + Scrapy = name must be an instance of basestring I'm trying to crawl a Spider with scrapy + MongoDB (PyMongo) and I'm receiving the error: name must be an instance of basestring.
Since my Spider is working, because it was scraping data to a json, I guess the error is in my new pipeline, here is the source code:
import pymongo

from scrapy import log
from scrapy.conf import settings
from scrapy.exceptions import DropItem

class MongoDBPipeline(object):
    def __init__(self):
        self.server = settings['localhost']
        self.port = settings['27017']
        self.db = settings['IngressoRapido']
        self.col = settings['Shows']
        connection = pymongo.Connection(self.server, self.port)
        db = connection[self.db]
        self.collection = db[self.col]

    def process_item(self, item, spider):
        err_msg = ''
        for banda, local in item.items():
            if not local    :
                err_msg += 'Faltando local %s da banda %s\n' % (banda, item['banda'])
        if err_msg:
            raise DropItem(err_msg)
        self.collection.insert(dict(item))
        log.msg('Item written to MongoDB database %s/%s' % (self.db, self.col),
        level=log.DEBUG, spider=spider)
        return item

A: Seems like you meant to connect to localhost port 27017, but instead you are using these values as keys to get values from settings. Did you mean this instead?
 def __init__(self):
    self.server = 'localhost'
    self.port = '27017'
    self.db = 'IngressoRapido'
    self.col = 'Shows'

A: The following code works perfectly and handles clean up resources properly. settings can be pulled up using the from_crawler method.
class MongoPipeline(object):
'''
    Saves the scraped item to mongodb.
'''
def __init__(self, mongo_server, mongo_port, mongo_db, mongo_collection):
    self.mongo_server = mongo_server
    self.mongo_port = mongo_port
    self.mongo_db = mongo_db
    self.mongo_collection = mongo_collection

@classmethod
def from_crawler(cls, crawler):
    return cls(
        mongo_server=crawler.settings.get('MONGODB_SERVER'),
        mongo_port=crawler.settings.get('MONGODB_PORT'),
        mongo_db=crawler.settings.get('MONGODB_DB'),
        mongo_collection=crawler.settings.get('MONGODB_COLLECTION'),
    )

def open_spider(self, spider):
    self.client = pymongo.MongoClient(self.mongo_server, self.mongo_port)
    self.db = self.client[self.mongo_db]

def close_spider(self, spider):
    self.client.close()

def process_item(self, item, spider):
    self.db[self.mongo_collection].insert(dict(item))
    return item

Note: please import pymongo in the piplines.py.
Kindly check the official docs for the same. http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-mongodb


text:
Q: How to drop/redefine inter-type declaration in AspectJ? I use parser generator, which generates java classes representing syntax nodes of a programming language, and AspectJ aspects for adding semantics to these classes.
I have extended/changed the grammar of the language and I want to reuse aspects of the old grammar and modify/extend them to cope with changes of node classes.
For example, an old node class and its aspect:
class A {
  public T a1;
  public U a2;
  ...
}

aspect Accessors1 {
  public T A.getT() {return a1;}
  public U A.getU() {return a2;}
}

With grammar modification, the class A is change followingly:
class A {
  public T a1;
  public V a2;
  public U a3;
  ...
}

I would like to reuse the Accessors1 aspect and add another one:
aspect Accessors2 {
  public V A.getV() {return a2;} // new accessor for new field
  public U A.getU() {return a3;} // modification of old accessor
}

I tried this:
declare precedence: *2, *1;

But I still get this error: Type mismatch: cannot convert from V to U from the first aspect. Even though the Accessors1.getU() is not used, it is still type-checked, which causes compilation to fail.
Why is that so? How can I override the original getU() with the new one? Is there a way to tell AspectJ to ignore/drop the Accessors1.getU()?

A: What if you try to use the following changes in second class:
class A {
  public T a1;
  public U a2;
  public V a3;
  ...
}

And the second aspect:
aspect Accessors2 {
  public V A.getV() {return a3;} // new accessor for new field
  public U A.getU() {return a2;} // modification of old accessor
}


text:
Q: Tracing source of access violation in unmanaged C# code I am currently working on some C# code that talks to a C++ dll. This is not an area in which I - or anyone else at my company - has any experience. It's been an eye-opener to say the least.
After a lot of reading, trial and error, and frustration, I've managed to iron out most of the kinks and get something that's largely functional. However, from time to time, it still throws this at me ...

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

.. and then dies. This error only appears when I run the call on parallel threads - it's fine single threaded. This dll is supposed to be thread safe and we've good reason to believe it ought to be, if handled correctly.
The cause of this error is always a call to the same function:
[DllImport(DLL, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern int QABatchWV_Close(IntPtr vi1);

I have the header file for the library, which defines this function as:
__declspec(dllimport) int __stdcall QABatchWV_Close(int);

From what I understand there are additional tools at my disposal like SafeHandle and MarshalAs. But, frankly, I'm unsure as to how to best deploy them in this situation.
This error tends to take several hours of use time to show up, so tweaking and hoping isn't going to be a productive approach here. Can anyone point me as to what I might be doing wrong in calling down to the C++ function?

A: Have a look at the following code which I use to call a c (not c++) dll. I know it is not really an answer to your question, but perhaps you can use some of this going foreward.
Note the "CallingConvention"-specifier in the dll declaration and also the "FreeGlobal" in the "finally" part of the try catch.
public class csInterface
{
    [DllImport(@"myDLL.dll", EntryPoint = "dllFunc", CallingConvention = CallingConvention.StdCall)]
    private static extern void dllFunc(IntPtr inp, IntPtr outp);

    public static int myDll(ref MyInput myInput, ref MyOutput myOutput)
    {
        int sizeIn, sizeOut;
        IntPtr ptr_i = IntPtr.Zero, ptr_u = IntPtr.Zero;

        sizeIn = Marshal.SizeOf(typeof(myInput));
        sizeOut = Marshal.SizeOf(typeof(myOutput));
        /* Calling C */
        try
        {
            ptr_i = Marshal.AllocHGlobal(sizeIn);
            ptr_u = Marshal.AllocHGlobal(sizeOut);

            Marshal.StructureToPtr(myInput, ptr_i, true);
            Marshal.StructureToPtr(myOutput, ptr_u, true);

            dllFunc(ptr_i, ptr_u);

            myOutput = (MyOutput)(Marshal.PtrToStructure(ptr_u, typeof(MyOutput)));
        }
        catch (Exception)
        {
            //Return something meaningful (or not)
            return -999;
        }
        finally
        {
            //Free memory
            Marshal.FreeHGlobal(ptr_i);
            Marshal.FreeHGlobal(ptr_u);
        }
        //Return something to indicate it all went well
        return 0;
    }
}

In C# I declare my types
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct MySubType
    {
        public int a;
        public double b;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct MyInput
    {
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 4)]
        public string aString; //A string of length 3
        public bool aBoolean;
        public int anInt;
        public char aChar;
        public double aDouble;

        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 12)]
        public MySubType[] aSubType; //Array of struct of length 12
    }

And something similar for the output.
Now in C (its probably the same or similar in c++) i declare my dll
__declspec(dllexport) void _stdcall dllFunc(MyCInput *myCInput, MyCOutput *myCOutput)
{
    //Code
}

And the corresponding C types which obviously have to mirror the C# types exactly
typedef struct
{
    int a;
    double b;
} MyCSubType;

typedef struct
{
    char aString[4];
    int aBoolean;   //This needs to be cast over to your C boolean type
    int anInt;
    char aChar;
    double aDouble;
    MyCSubType myCSubType[12];
} MyCType;

Now the types I have used in this example do not exactly match what I have used in my code, and i have not tested this code. So there may be typos and such, but the "principle" is ok.

A: Well, first of all you don't need setting Charset here, because there are no strings.
Second of all - function in cpp should be declared as exported not imported, so it should look like:
__declspec(dllimport) int __stdcall QABatchWV_Close(int);

Next, you should set calling convention in your C# code to stdcall:
[DllImport(DLL, SetLastError = true, CallingConvention=CallingConvention.Stdcall)]

Next you should have int instead of IntPtr in C# code. And I'm nearly sure that name of this function (in C++ dll) is mangled and it's not QABatchWV_Close but rather something like QABatchWV_Close@32. You should check it using "dll export viewer".