text:
Q: different behavior: "sudo nmap" vs just "nmap"? I'm attempting to do a simple port scan with nmap:
$ nmap 192.168.56.101

Starting Nmap 6.47 ( http://nmap.org ) at 2015-03-10 19:30 IST
Nmap scan report for 192.168.56.101
Host is up (0.0048s latency).
Not shown: 998 closed ports
PORT      STATE SERVICE
5555/tcp  open  freeciv
24800/tcp open  unknown

Nmap done: 1 IP address (1 host up) scanned in 0.10 seconds

But when I attempt the same with sudo, it fails claiming the host is down:
$ sudo nmap 192.168.56.101

Starting Nmap 6.47 ( http://nmap.org ) at 2015-03-10 19:30 IST
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 0.48 seconds

NOTE:
I'm on OS X Yosemite.
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)
Thank you.

A: I have noticed the same behavior on my Mac. It is really strange.
It appears that NMAp with sudo privileges gets some informations from the ARP cache. And so, if you scan a device that is disconnected from the network but is still in the ARP cache (the cache is updated after 2 or 3 minutes on my computer), then it will appears as online for NMAP.
From NMAP man page :

If no host discovery options are given, Nmap sends an ICMP echo
         request, a TCP SYN packet to port 443, a TCP ACK packet to port 80, and
         an ICMP timestamp request. (For IPv6, the ICMP timestamp request is
         omitted because it is not part of ICMPv6.) These defaults are
         equivalent to the -PE -PS443 -PA80 -PP options. The exceptions to this
         are the ARP (for IPv4) and Neighbor Discovery.  (for IPv6) scans which
         are used for any targets on a local ethernet network. For unprivileged
         Unix shell users, the default probes are a SYN packet to ports 80 and
         443 using the connect system call..  This host discovery is often
         sufficient when scanning local networks, but a more comprehensive set
         of discovery probes is recommended for security auditing.

A: Basically, by default:

*

*A privileged user executes an -sS (TCP SYN scan).
This type of scan requires raw socket / raw packet privileges.

*An unprivileged user executes an -sT (TCP connect scan).
This type of scan does not require raw socket / raw packet privileges.

Adapted from Nmap's official docs:

PORT SCANNING TECHNIQUES
    Most of the scan types are only available to privileged users. This is because they are able to send and receive raw packets, which requires root access on Unix systems. Using an
    administrator account on Windows is recommended, though Nmap sometimes works for unprivileged users on that platform when WinPcap has already been loaded into the OS. Requiring root
    privileges was a serious limitation when Nmap was released in 1997, as many users only had access to shared shell accounts. Now, the world is different. Computers are cheaper, far
    more people have always-on direct Internet access, and desktop Unix systems (including Linux and Mac OS X) are prevalent. A Windows version of Nmap is now available, allowing it to
    run on even more desktops. For all these reasons, users have less need to run Nmap from limited shared shell accounts. This is fortunate, as the privileged options make Nmap far more
    powerful and flexible.

--privileged (Assume that the user is fully privileged).
    Tells Nmap to simply assume that it is privileged enough to perform raw socket sends, packet sniffing, and similar operations that usually require root privileges on Unix
    systems. By default, Nmap quits if such operations are requested but geteuid is not zero. --privileged is useful with Linux kernel capabilities and similar systems that may
    be configured to allow unprivileged users to perform raw-packet scans. Be sure to provide this option flag before any flags for options that require privileges (SYN scan,
    OS detection, etc). The NMAP_PRIVILEGED environment variable may be set as an equivalent alternative to --privileged.

-sS (TCP SYN Scan).
    TCP SYN Scan is the default scan option for privileged users. It can be performed quickly, scanning thousands of ports per second; when on a fast network, not hampered by any
    restrictive firewalls. It is also relatively unobtrusive and stealthy since it never completes TCP connections. A TCP SYN Scan works against any compliant TCP stack rather than
    depending on the idiosyncrasies of specific platforms (as Nmap's other scans do). It allows clear, reliable differentiation between the (open), (closed), and (filtered) states.
    This technique is often referred to as a Half-Open Scan, because it doesn't open a full TCP connection. You send a SYN packet, as if you are going to (open) a real connection
    and then wait for a response. A SYN/ACK indicates the port is listening (open), while a RST (reset) is indicative of a non-listener (closed). If a SYN/ACK is received, a RST is
    immediately sent to tear down the connection. The primary advantage to this scanning technique is that fewer sites will log it. Unfortunately you need root privileges to build
    these custom SYN packets. If no response is received after several retransmissions, the port is marked as (filtered). The port is also marked (filtered) if an
    ICMP unreachable error (type 3, code 0, 1, 2, 3, 9, 10, or 13) is received. The port is also considered (open) if a SYN packet (without the ACK flag) is received in response.
    This can be due to an extremely rare TCP feature known as a simultaneous (open) or split handshake connection. (https://nmap.org/misc/split-handshake.pdf)

--unprivileged (Assume that the user lacks raw socket privileges).
    This option is the opposite of --privileged. It tells Nmap to treat the user as lacking network raw socket and sniffing privileges. This is useful if testing, debugging, or
    the raw network functionality of your operating system is somehow broken. The NMAP_UNPRIVILEGED environment variable may be set as an equivalent alternative to —unprivileged.

-sT (TCP Connect Scan).
    TCP Connect Scan is the default TCP scan type for unprivileged users. This is the most basic form of TCP scanning. The connect() system call, provided by your operating system
    is used to (open) a connection to some interesting ports on the machine. If the port is (listening), then connect() will succeed, otherwise the port is (filtered). One strong
    advantage to this technique is that it doesn't require any special privileges. Usually, on most UNIX boxes, any user can make this call because it doesn't involve writing raw
    packets like most other scan types do. This connect() call is the same high-level system call that web browsers, P2P clients, and most other network-enabled applications use
    to establish a connection.
    When the TCP SYN Scan is available, it is usually a better choice. Nmap has less control over the high level connect() call than with raw packets, making it less efficient.
    Rather than performing the half-open (reset) that a SYN Scan does, the connect() system call makes complete connections to (open) target ports. This not only takes longer, it
    requires sending more packets to obtain the same information, and target machines are more likely to log the connection. A decent IDS will catch either. Most machines, however,
    have no such alarm system. Many services on your average Unix system will add a note to syslog, and sometimes a cryptic error message, when Nmap connects and then closes the
    connection without sending data. Truly pathetic services crash when this happens, though that is uncommon. An administrator who sees a bunch of connection attempts in her logs
    from a single system should know that she has been TCP Connect Scanned.

A: By default an unprivileged scan uses -sT (TCP Connect) while privileged (root) uses -sS (TCP SYN Stealth).
TCP Connect (-sT)
Connect scan uses the system call of the same name to scan machines, rather than relying on raw packets as most of the other methods do. It is usually used by unprivileged Unix users and against 1Pv6 targets because SYN scan doesn't work in those cases.
TCP SYN Stealth (-sS)
This is far and away the most popular scan type because it the fastest way to scan ports of the most popular protocol (TCP). It is stealthier than connect scan, and it works against all functional TCP stacks (unlike some special-purpose scans such as FIN scan).
1) To figure what is happening with  your machine I would suggest using the extra verbose mode (-vv) or --packet-trace to see what happens.
$ sudo nmap --packet-trace -vv 192.168.56.101

2) Another approach would be to force an unprivileged scan as privileged user using the following commands and see the result.
$ sudo nmap -sT -vv 192.168.56.101
$ sudo nmap --unprivileged -vv 192.168.56.101

3) Finally the reason why nmap stops the scan is because IMCP Type 8 (echo a.k.a ping) doesn't return an ICMP Type 0 (echo reply).
This command ignores ping and keep scanning:
$ sudo nmap -PN 192.168.56.101

Can you please try those commands and post the output ?


text:
Q: Virtual key code of ALT KEY I am making hooks and catching keyboard virtual key codes, according to MSDN,  these are the key codes that exist.
Every key code works fine as i will give an example down below of my code.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

HHOOK altKey;
KBDLLHOOKSTRUCT kbdHK;
MSG message;

LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar);

int main(int argc, char *argv[]) {
  altKey = SetWindowsHookEx(WH_KEYBOARD_LL, kbdProc, NULL, 0);

  while(GetMessage(&message, NULL, 0, 0) > 0){
    TranslateMessage(&message);
    DispatchMessage(&message);
  }
  return 0;
}

LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar){

  if(nCode >= 0){
    if(wPar == 256){
      kbdHK = *(KBDLLHOOKSTRUCT *)lPar;
      if(kbdHK.vkCode == 0x20){
        printf("spacebar pressed!!\n");
      }
    }
  }
  return CallNextHookEx(NULL, nCode, wPar, lPar);
}

But when I replace the virtual key code with 0x12 which is ALT KEY according to MSDN, I can't get a result back. What could be the problem?
Edit:
When I use this line of code, I can get the scanCode for every key but not for alt key again which is interesting.
printf("%d", kbd.scanCode);

A: I suggest hooking the WM_SYSKEYDOWN messages, and noting that the values correspond to constants that more often have identifiers (VK_MENU, in this case). After all, as programmers we're taught early on not to use magic numbers!

WM_SYSKEYDOWN message
Posted to the window with the keyboard focus when the user presses the F10 key (which activates the menu bar) or holds down the ALT key and then presses another key.

Another option, as pointed out in the comments, is to use GetAsyncKeyState. Your concerns that you won't be able to use vkCode seem strange, as GetAsyncKeyStates parameter is the virtual key code, after all, so the code you'd be using would be along the lines of:
short result = GetAsyncKeyState(VK_MENU);
if (!result) {
    // no alt keystrokes since last call
}

This is the only way you'll be able to distinguish between left alt (VK_LMENU) and right alt (VK_RMENU) keys, but it's not the window-loop way. Now you have both.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Program won't display answer of program after running it and typing in the correct input So I have my program, and it just won't run after the last question (which needs input).  My code is here:
import java.util.Scanner;

import javax.swing.JOptionPane;

public class HiConor
{

   public static void main(String[] args)
   {

      String result;
      int selection;
      int Entry;
      boolean isYes;
      System.out.print("Starting Program");
      System.out.print(".");
      System.out.print("");
      System.out.print(".");
      System.out.print("");
      System.out.print(".");
      System.out.print("");
      System.out.print(".");
      JOptionPane.showMessageDialog(null, "Hello there!");
      selection = JOptionPane.showConfirmDialog(null, "Are you doing good?");
      boolean isNo;
      boolean isCancel;
      isNo = (selection == JOptionPane.NO_OPTION);
      isYes = (selection == JOptionPane.YES_OPTION);
      isCancel = (selection == JOptionPane.CANCEL_OPTION);
      if(isYes){
      JOptionPane.showMessageDialog(null, "Yes?" + " That's nice to hear!");
         }
      if(isNo){
      JOptionPane.showMessageDialog(null, "No?" + " Well then, cheer up!");
         }
      if(isCancel){
      JOptionPane.showMessageDialog(null, "Fine then, don't respond");
         }
      Scanner keyBoard = new Scanner(System.in);
      Scanner input = new Scanner(System.in);
      JOptionPane.showInputDialog(null, "What is your name?",
      "Mlg recess poofs",
      JOptionPane.ERROR_MESSAGE);
      String userinput = input.next();
      if(userinput.equals("alex")){
         JOptionPane.showMessageDialog(null, "What a lovely name!");
         }

      JOptionPane.showMessageDialog(null, "I have a feeling you're trolling me " + ". This is the end of the program. Goodbye.");
      }}

A: Change it to this
String userinput =  JOptionPane.showInputDialog(null, "What is your name?",
      "Mlg recess poofs",
      JOptionPane.ERROR_MESSAGE);

Remove:
Scanner input = new Scanner(System.in);
String userinput = input.next();

A: You are mixing your input methods. Do you want to get the user's response from a dialog box or from them typing in a console windows? You seem to be using JOptionPane so I'll assume you want the dialog. In that case you do not need to use a Scanner object at all.  The call to JOptionPane.showInputDialog is already returning whatever the user typed, but you're not saving it in any variable. Just do the following:
String userinput = JOptionPane.showInputDialog(null, "What is your name?",
    "Mlg recess poofs",
    JOptionPane.ERROR_MESSAGE);

and don't bother calling input.next().


text:
Q: Trying to keep the image size inside of the card FAILS I am making some cards with an image in the shape of a water drop...
I am not managing to keep the shape of the drop correct for all screen resolutions. Any help will be appreciated.
Working example: Demo

A: You can use MediaQueries package to work with different screen resoultions. Other choices are also available but it might help you.


text:
Q: Pushing features to external GeoJSON file I am working on a project which uses Leaflet and leaflet.draw to show and draw shapes on the map. I also have a data.json file which I use to display former features generated from geojson.io. What I want to do is, after I finish drawing a feature I want it to be saved in the data.json file. I am trying to do this by getting the newly created feature by leaflet draw and pushing it to the feature collection object in the json file. I am not quite understanding how I am supposed to do that. create a new object, how do I get the coordinates and the feature type inte the javascript object.
This is the code I use to get the features from the JSON file.
$.getJSON("http://192.168.15.79:8080/PathTO/data.json", function(data){
  L.geoJson(data,{
    style: featureStyles
  }).addTo(map);
});

And this is what I have tried so far
  var drawControl = new L.Control.Draw(drawPluginOptions);
  map.addControl(drawControl)
  var editableLayers = new L.FeatureGroup();
  map.addLayer(editableLayers)
  map.on('draw:created', function(e) {
    var type = e.layerType;
    var layer = e.layer;
    var newFeature = {
      "type": "features",
      "geometry": {
        "type": layer.type,
        "coordinates": layer.getLatLngs()
      //to be continued...
      }
    };
    editableLayers.addLayer(e.layer);

   //editableLayers.push(layer);
   // editableLayers.layers.push(serverResponse.featuresOnWs);
  });


text:
Q: It is possible move a specific file to the beginning of the disk? It is possible move a specific file to the beginning of the disk? I want to move my virtual machine disk files (virtual disk) to the beginning of the disk to improve disk access performance. I believe that this is possible because some defragmentation softwares use this technique to move system files to the beginning of the disk. What I want is a practical way (a script or a program) to do the same but moving the files that I choose.

A: I think the best way is to create a logical disk at the beginning of the separate physical HDD. There are programs that can move existent partitions and create a new one at the beginning of the disk (google for "partition magic free alternatives")

A: I think you should be able to do that with the scripting feature of MyDefrag. I haven't tried to do what you want, but AddGap and MoveDownFill are possibly among the actions you'd need to take within a FileSelect/FileAction clause.

A: As Dennis said you can use MyDefrag scripting for this task. Anyway I think you have to move the file to the end of the disk for performance improvement.

A: Some HDDs first cylinder si in the inner part, so less data stored per rotation, so lower speed on lower cylinders.
Most modern HDD (all that has park heads since i know) use the oposite, the first cylinder is on the outer part, so much more data stored per rotation, so higher speed on outer cylinders.
That is based in the concept that HDD rotates at a constant R.P.M., among not all HDD works like that.
I own a vry expensive HDD that can move each head to a different cylinder at the same time, so can read at same time from different cylinders, and it uses an internal Buffer not of 8MiB or 16MiB, it uses a full GigaByte Buffer. The disk is so fast that a Sata III controller is the one that limits the transfer sustained speed... physical disk could do a 10GiB/s read (from surface to Buffer) and 6GiB/s write (from Buffer to surface).
So the question of where to put files is simple, do a zone speed test (read and write), that way you will know where is better to put files.
Beware there are new HDDs that use another technique to 'fake' such different speed depending on the cylinder... they swap cylinders and heads, so if you ask it to write a whole cylinder it will use only one head and a lot of cylinders, that way the speed is more or less uniform along all the cylinders, so they 'fake' most tools to benchmark speed (speed seems to be constant all along the disk), what is the real is that the disk is storing what external is asked to be done in one cylinder, in multiply cylinders so the speed is (per external asked cylinder): fast, medium, slow
That trick is quite good for sustained performance... if copying a lot of GiB to it, the ETA (estimated time of arrive) is very well calculated, since speed goes as this: fast, medium, slow, fast, medium, slow, ... so the media is constant... but they are really as fast as a normal one... real time to end is quite similar, the difference is that you can calculate better the needed time to finish.
So as i insist, make fine speed tests, then move files to where you want.
And if you do not plan to use HDD in Windows XP or lower, neither on TV's, SetTopBoxes, etc... in other words, where a GPT partition is not understood... it is much better to create a GPT scheme of 20 or more Primary partitions, so you put only and only one file per partition (big files and of course, ones that will not change, like movies), and partition will be filled to 99.99% so no space left... for Virtual machine HDDs, the best is use a Fixed size (not dynamic) and since file will not grow use the same aproach as for movies, etc... i tend to use 20GiB per Windows System partition Virtual HDD.
How to do such thing (make 99.99%) is not easy, but it is easy to follow the steps... create a very small NTFS partition (1/100 the size that is needed) on GPT scheme (this will make a $MFT file to be really very small), defragment it while it is near empty, so $MFT etc will go to start of the partiton, enlarge the partition to the double of what will be needed (this does not change $MFT file size), copy there such file (only one file), defragment it, shrink it to the max so 99.99% is not free, the move it to the part of the disk you want.
It is much better to do such in order, from both sides to the middle, one by one.
Yes, it is too much work... but i do not know any tool that avoid Windows moving a file.
Yes, it is true, i have seen Windows fragmenting a file when such file is not even accesed... in other words, put, move, grow one file and Windows can make any other file on same partition to get fragmented... i had also tried marking at low level (with System account privileges, aka hacking) a non-fragmented file as not moveable, and i saw such file get fragmented while copying from another disk to that parttion a really hde file... yes it sound ridiculus, a non-moveable file that is not fragmented gets fragmented because there is another file written onto same partition... so never ever have a file on a partition with free space and hope it will not ever get fragmented or moved to another part of the partition...
The only trick i saw that works for makeing a file not be moved / fragmented is having it, and only that one, on its own partition... GPT allows a lot of partitions, but not so many (limit i think is 128).
Yes, the big problem, how i access such partitions, if only around 20 letters are free to use... easy, not using letter, using \??\ access.
Here is how, create a shotcut to start \\?\Volume{...}\, the {...} part can be obtained by running mountvol.exe without parameters.
That is also a very good trick to access partitions on USB strick or MemoryCards... windows only allow to mount (assign a drive letter) the first partition on the partition table... but you can access any of them with that trick, je je, at least that works where i had tested, i have messages from friends telling that they can not; obviously i create such parttion schemes as MBR under Linux with linux fdisk and re-writting the 'master', aka create a new scheme, i never use that one that cames on sticks among they seem a good MBR, i preffer to overwrite it with Linux fdisk tool, then create multiple partitions, format them, etc... with fdisk + mkfs... or with GParted, never ever with Windows (it will not allow you on USB stick / memory cards) and not on all USB sticks can be changed the Removable Bit.
So, use the trick of GPT with very small NTFS, grow to fit double size of file, put the file, shring to the max you can, move partition where you want (between steps defragment it, till step of shrink, after that one no future defragment will be ever needed). That works really great for files that do not change in size, no matter if they are only read or also write (for VirtualBOX not dynamic .VDI file is perfect).
Remember, only one file per NTFS partition is the big trick, creating the NTFS as small as possible is the other trick to make $MFT very small and do not loose/waste space).
The bad part... time to put each file, and access by .lnk (shortcuts) that opens explorer start \\?\Volume{...}\ instead of having a letter assigned.
Not to mention it is better on such NTFS to get rid of "$Recycle.Bin" and "System Volume Information" doing one by one: take owner of it (takeown /F ... /A /R /D [Y|S|... depends on language] command, see command parameters on google or by calling it with /?), then delete it (RD /S /Q ... command), then create a file with Notepad with such name (so size is exactly zero and so they fit inside the $MFT so take no space at all); that way Windows will not be able to re-create such folders, and if you do not want to see the two zero size files, mark them with +R +H +S ussing attrib +R +S +H ... command, so system will think they are system hidden read-only files and will not be shown on explorer (if hide system files is checked, of course); do not forget such commands must be run in an admin console.
Hope now you can, as i can, have files on the part of the disk we want, not where windows want or will want in the future, and ensure they will not get moved nor fragmented never ever again.


text:
Q: Html2canvas for each div export to pdf separately I have Page, It has 6 div with same class name "exportpdf", I am converting those div into pdf using jspdf and html2canvas
var elementTobePrinted = angular.element(attrs.selector),
iframeBody = elementTobePrinted.contents().find('div.exportpdf');

In html2canvas.....
html2canvas(elementTobePrinted, {
  onrendered: function (canvas) {
    var doc = new jsPDF();
    for(var i=1;i<elementTobePrinted.length;i++){
      doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40, 180, 160);
      doc.addImage(canvas.toDataURL("image/jpeg"),'JPEG', 0, 0, 215, 40)
      doc.addPage();
    }

    doc.save(attrs.fileName);
}

I converted page to canvas.its create same div contents for whole pdf. I need each div contents into same pdf with different pages.
Can anyone help me?
The problem is with html2canvas:
doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40,180, 160);

Here I need to pass elementTobePrinted list to addImage.

A: On angular 2(now 6) framework.
u can use the logic as below,

*

*On click execute generateAllPdf() function,

*gather all 6 id's from my html collection,

*iterate through each id and call html2canvas function,

*as html2canvas runs in background to process images, i m using
await on function,

*after the html2canvas completes its process, i ll save the
document,

*If suppose i wont use await i ll end-up in downloading an empty
page.

below is my code logic,
// As All Functions in js are asynchronus, to use await i am using async here
 async generateAllPdf() {
    const doc = new jsPDF('p', 'mm', 'a4');
    const options = {
      pagesplit: true
    };
    const ids = document.querySelectorAll('[id]');
    const length = ids.length;
    for (let i = 0; i < length; i++) {
      const chart = document.getElementById(ids[i].id);
      // excute this function then exit loop
      await html2canvas(chart, { scale: 1 }).then(function (canvas) {
        doc.addImage(canvas.toDataURL('image/png'), 'JPEG', 10, 50, 200, 150);
        if (i < (length - 1)) {
          doc.addPage();
        }
      });
    }
    // download the pdf with all charts
    doc.save('All_charts_' + Date.now() + '.pdf');
  }

A: I think the issue here is that elementTobePrintedis not what you think it is.
When you run the code:
var elementTobePrinted = angular.element(attrs.selector)

This will return you a list of every element that matches the conditions, so you said you have 6 of these elements ("It has 6 divs").
Have you tried replacing:
html2canvas(elementTobePrinted, {
  onrendered: function (canvas) {
    var doc = new jsPDF();
    for(var i=1;i<elementTobePrinted.length;i++) {
      doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40, 180, 160);
      doc.addImage(canvas.toDataURL("image/jpeg"),'JPEG', 0, 0, 215, 40)
      doc.addPage();
    }
    doc.save(attrs.fileName);
}

With...
for(var i=0; i<elementTobePrinted.length; i++){
  html2canvas(elementTobePrinted[i], {
    onrendered: function (canvas) {
      var doc = new jsPDF();
      doc.addImage(canvas.toDataURL("image/jpeg"), 'jpeg', 15, 40, 180, 160);
      doc.addImage(canvas.toDataURL("image/jpeg"),'JPEG', 0, 0, 215, 40)
      doc.addPage();
      doc.save(attrs.fileName);
    }
}

The reason I suggest this is that html2Canvas wants a SINGLE element as its first parameter and your example above passes a list of elements (I think, assuming angular.element(attrs.selector) finds all 6 divs you are trying to print).


text:
Q: Deploying Python FastAPI to AWS Beanstalk I have a small python FastAPI project which is completely working on my local computer. But when I try to deploy it to AWS Beanstalk (manually for now) I've always got a '502 Bad Gateway' error when open the application in a browser.
This is my project structure:
/project
   /html/
   main.py
   Procfile
   requirements.txt

the main.py contains the api endpoints that use some HTML files. These files are in the html/ folder.
The Procfile looks like this:
web: uvicorn main:app --host 0.0.0.0 --port 80

and the requirements.txt like this:
fastapi~=0.91.0
uvicorn

When I uploaded an example application from AWS to the same Beanstalk environment, it worked. And as I said, even if I execute the python project locally, it works fine. So I must have configured something wrong.
Does anybody know this problem and know how to fix it?


text:
Q: Can I use an extension method with a Structure in VB.NET? I am wondering whether I can use DataContractJsonSerializer to serialize a Structure type, or does it have to be a reference/Class type?
I have the following code:
<Extension()> Public Function ToJSON(ByVal target As Object) As String
    Dim serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(target.GetType)
    Using ms As MemoryStream = New MemoryStream()
        serializer.WriteObject(ms, target)
        ms.Flush()

        Dim bytes As Byte() = ms.GetBuffer()

        Dim json As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim(Chr(0))

        Return json
    End Using
End Function

And yet if I call it on a Structure type, such as a KeyValuePair(Of T1, T2), I get the following error:

Public member 'ToJSON' on type 'KeyValuePair(Of String,Object)' not found.

A: The error message does not have anything to do with DataContractJsonSerializer or anything inside your method. It cannot find the method itself. That suggests to me that you have forgotten to add a reference to the namespace in which this extension method is defined. I apologise I don't know the VB equivalent, but in C# it is the using clause I'm talking about.


text:
Q: Creating Executable File For Python 2.7 I want to make an executable file from a python file the python file is written for Python 2.7.
I tried pyinstaller but it gives me an error when installing. I'm guessing it does not have support for Python 2.7 anymore.
Are there any alternatives for pyinstaller that work with Python 2.7?
I tried installing cx_Freeze version 5.1.1 but it gives me the following error:
Cleaning up...
Command C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\win-10\\appdata\\local\\temp\\pip_build_win-10\\cx-Freeze\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\win-10\appdata\local\temp\pip-cn4sd_-record\install-record.txt --single-version-externally-managed --compile failed with error code 1 in c:\users\win-10\appdata\local\temp\pip_build_win-10\cx-Freeze
Storing debug log for failure in C:\Users\win-10\pip\pip.log

when I install from wheel
cx_Freeze-5.1.1-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform.
Storing debug log for failure in C:\Users\win-10\pip\pip.log

setup.py
from sys import executable
from cx_Freeze import setup, Executable

setup(name='server', version='0.1', description='reverse shell server')

A: I faced this problem some times ago, after a lot of googling I found the best solution for me.
Alternatives

*

*Py2Exe: Which is old, the last release on PyPi is on 21 October 2014.

*pyInstaller: Is a nice tool, but with some problem that we will see later.

*auto-py-to-exe: Use pyInstaller to build the .exe, so suffer the same problem, but has a nice GUI and is intuitive to use.

*cx_Freeze: I think the best solution, because it was the only one that works in my case, it is also recommended from python
Investigation
During this time I looked on google and StackOverflow for the best solution, each time that I found something it was out-dated or not well explained/documented, so I studied the official docs.
py2exe
As first try I installed py2exe it seems the best option, also recommended from python, so, give it a try.
All goes fine during the installation process, so I decide to follow the tutorial and get my .exe.
During the step 3 of the tutorial, running setup I received an error, looking on google I found this.
I gave up with py2exe.
auto-py-to-exe && pyInstaller
I have installed auto-py-to-exe and all went good, the program open without problems so I create my .exe file, that works!
The only problem was that, the program works only on my laptop, on all the other machine where I try to execute the antivirus delete it.
Looking on google I found the github repository where I found one issue like the mine, reading it I understand that the problem is pyInstaller.
Looking on the pyInstaller repository I found one issue where one contributors tells to contact the antivirus vendo, so I gave up again.
cx_Freeze
Looking the docs it seems to be overcomplicated realize a simple .exe, so I have studied the documentation and found what I need. If you need support for Python 2.x, cx_Freeze version 5.1.x should be used instead, to do it just run pip install cx-Freeze==5.1.1

*

*Open you project folder and create inside it a setup.py file with inside:
import sys
from cx_Freeze import setup, Executable

setup(  name = "myProgram",
        version = "0.1",
        description = "",
        executables = [Executable("myProgram.py")])

Setting up this file require a little bit of study, there are multiple options to set. You can set the option to create a simple .exe or also the create a windows/mac/linux installer.

*Once you have your file ready, with the options that you need, just open a shell/terminal/cmd in the directory where the setup.py file is located and execute: python setup.py build

*Now in your project folder you will see a folder where inside you can find your .exe file.


text:
Q: Configuring Proxmox Cluster Storage We are configuring proxmox on our servers at two locations
each location has;
1 x hp c7000 enclosures with 16 blades
1 x hp proliant dl585
We also plan to add a 24TB SAN to each location.
We are going to setup up two clusters per location, with the c7000 as a HA cluster that can failover to the other blades.
Each blade in the c7000 has 1x 1TB hdd, the default proxmox install takes up the majority of the space for the vz dumps. I want to partition the hdds at install and leave the proxmox install at around 50GB on one partition, and leave another partition to use as DRBD storage.
I can run this at boot install to set the proxmox install details
Linux ext4 maxroot=20 swapsize=30
if i add the flag
minfree=nGB
Will this create another partition i can configure as DRBD storage?
there is also this flag
maxvz=nGB
That sets the maximum data directory partition, how do i configure proxmox not to store data dumps on the local partition and only on the DRDB storage?
Thanks


text:
Q: Is there an algorithm (or set of algorithms) that finds optimal weights of variables for a function Current state: I have a dataframe with input states and results of the decision made. Currently, the decision is made based on the binary state (true/false) of the variable.
Goal:
Since each variable has a different weight on the outcome, we need to find the optimal weights that can replace the true/false condition to improve the probability score.
assumptions are

*

*Not all variables have strong correlation to end result (using pearson method).

*There exists a set of weight given state of two primary variables (var0, var1) that can improve prediction by few percent(at least better than hardcoded numbers).

I have looked at RL but that makes the process and computation too complex to start from beginning(I have just started this path) given number of variables.
Is there algorithm (M.L or otherwise) or method that can formulate the weights of given variables?
Any recommendations / knowledge sharing?
Dataframe looks like this,
result1 result2  var0   var1 var2  ..  var8
-3.79       8    -9.8     4    3      -34.61
 5.16       11   44       3    10     -80.81
-3.22       5    52.58    5    10     -13.5
-0.07       7    124.48   6    0      -75.14
13.75       32   44.76    8    8      -72.33


text:
Q: Sending Multiple Paramters in Template Column of MVC 4 Telerik Grid Below code sending only one parameter ( id = o.nopCategoryID ) to controller, how can i send another parameter along with this?
View
            @(Html.Telerik().Grid(Model.Mappings)
                .Name("Grid")
                .Scrollable(c => c.Height("200px"))
                .Columns(columns =>
                {
                    columns.Bound(o => o.ClockCategoryid).Hidden(true);
                    columns.Bound(o => o.nopCategoryID).Hidden(true);
                    columns.Bound(o => o.nopCategory).Width(100).Title("Category");

                    columns.Bound(e => e.ClockCategory).Width(200).Title("Mapped To").Template(t => t.ClockCategory.Replace(",", "<br />"));

                    columns.Bound(o => o.nopCategoryID)
                                        .Width(50)
                                        .Centered()
                                        .Template(o => Html.ActionLink("Edit", "EditProduct", new { id = o.nopCategoryID, category = o.nopCategory }))
                                        .Title("Edit");
                    columns.Bound(o => o.nopCategoryID)
                                        .Width(50)
                                        .Centered()
                                        .Template(o => Html.ActionLink("Delete", "DeleteMapping", new { id = o.ClockCategoryid }))
                                        .Title("Delete");
                })

                )

Controller:
    public ActionResult EditProduct(int id,string category)
    {
        return Configure(id, 0);
    }


text:
Q: adding a resource file manually in Dev-Cpp I am making a simple Win32 C++ game and when I made a header file and a resource file once I compiled it I had an error message from the compile log wich said "*** missing separator. stop"and it was from the make file in the line that had my new resource file.
This is not the first time I try to make a resource file as I did it with another simple apps and it worked fine but now with this application it didnt work also I checked the makefile from another aplication and they had the same syntax.
Any help would be appreciated.
And by the way im using Dev-Cpp ide and compiler if that may help you find a solution for my problem.
**Edit:**The makefile code is:
# Project: Win32 Game 1
# Makefile created by Dev-C++ 4.9.9.2

CPP  = g++.exe -D__DEBUG__
CC   = gcc.exe -D__DEBUG__
WINDRES = windres.exe
RES  = Win32_Game_#1_private.res
OBJ  = WinMain.o $(RES)
LINKOBJ  = WinMain.o $(RES)
LIBS =  -L"C:/Dev-Cpp/lib" -mwindows  -lgmon -pg  -g3
INCS =  -I"C:/Dev-Cpp/include"
CXXINCS =  -I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include"  -I"C:/Dev-Cpp/include/c++/3.4.2/backward"  -I"C:/Dev-Cpp/include/c++/3.4.2/mingw32"  -I"C:/Dev-Cpp/include/c++/3.4.2"  -I"C:/Dev-Cpp/include"
BIN  = "Win32 Game 1.exe"
CXXFLAGS = $(CXXINCS)   -pg -g3
CFLAGS = $(INCS)   -pg -g3
RM = rm -f

.PHONY: all all-before all-after clean clean-custom

all: all-before "Win32 Game 1.exe" all-after

clean: clean-custom
${RM} $(OBJ) $(BIN)

$(BIN): $(OBJ)
    $(CPP) $(LINKOBJ) -o "Win32 Game 1.exe" $(LIBS)

WinMain.o: WinMain.cpp
    $(CPP) -c WinMain.cpp -o WinMain.o $(CXXFLAGS)

Win32_Game_#1_private.res: Win32_Game_#1_private.rc Settings.rc
    $(WINDRES) -i Win32_Game_#1_private.rc --input-format=rc -o     Win32_Game_#1_private.res -O coff

Settings.rc is the resource file that im trying to add


text:
Q: string.replace seriously broken with \ "C://test/test/test.png" -> blub

    blub = blub.Replace(@"/", @"\");

result = "C:\\\\test\\test\\test.png"

how does that make sense? It replaces a single / with two \
?

A: It's actually working:
string blub = "C://test/test/test.png";
string blub2 = blub.Replace(@"/", @"\");

Console.WriteLine(blub);
Console.WriteLine(blub2);

Output:
C://test/test/test.png
C:\\test\test\test.png

BUT viewing the string in the debugger does show the effect you describe (and is how you would write the string literal in code without the @).
I've noticed this before but never found out why the debugger chooses this formatting.

A: No, it doesn't.
What you're seeing is the properly formatted string according to C# rules, and since the output you're seeing is shown as though you haven't prefixed it with the @ character, every backslash is doubled up, because that's what you would have to write if you wanted that string in the first place.
Create a new console app and write the result to the console, and you'll see that the string looks like you wanted it to.
So this is just an artifact of how you look at the string (I assume the debugger).

A: The \ character in C# is the escape character, so if you are going to use it as a \ character you need two - otherwise the next character gets treated specially (new line etc).
See What character escape sequences are available? (C#)

A: The character \ is a special character, which changes the meaning of the character after it in string literals. So when you refer to  \ itself, it needs to be escaped: \\.

A: Look up "escape characters".

A: Its done what it should.
"\\" is the same as @"\"
"\" is an escape character. Without the verbatim indicator "@" before a string a single \ is shown as "\\"

A: You should think twice before saying something like that....
The string.Replace function is basic functionality that has been around for a long time.... Whenever you find you have a problem with something like that, it's probably not the function that is broken, but your understanding or use of it.


text:
Q: Solr logging with Logback I try to log the solr output with logback.
Using maven I build a new webapp and excluded any references to commons-logging and slf4j-jdk14 e.g.
<dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-core</artifactId>
    <version>3.3</version>
    <exclusions>
        <exclusion>
            <artifactId>commons-logging</artifactId>
            <groupId>commons-logging</groupId>
        </exclusion>
        <exclusion>
            <artifactId>slf4j-jdk14</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency>

I ended up with no dependencies to any other logging framework but solr still logs to standard out:
12.07.2011 16:43:31 org.apache.solr.servlet.SolrDispatchFilter init
INFO: SolrDispatchFilter.init()
12.07.2011 16:43:31 org.apache.solr.core.SolrResourceLoader locateSolrHome

Has anyone any suggestions?

A: There was a hidden (masked) dependency of an older version of slf4j on an other dependency used by an other library.
In my case it was netcdf used by apache tika.
I excluded that dependency on tika and now solr uses logback for logging.
<dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers</artifactId>
  <version>${tika.version}</version>
  <exclusions>
    <exclusion>
        <artifactId>commons-logging</artifactId>
        <groupId>commons-logging</groupId>
    </exclusion>
    <exclusion>
        <artifactId>netcdf</artifactId>
        <groupId>edu.ucar</groupId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
    <exclusions>
        <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency>


text:
Q: Return Column Name for column with largest value and criteria Return Column Name for column using  largest value and criteria
=INDEX(MIP!$BZ$3:$CG$3,0,MATCH(MAX(MIP!$BZ$1:$CG$1),MIP!$BZ$1:$CG$1,0))
Not able to put in a criteria for the same


text:
Q: If I rebuild a dll that my project references, do I have to rebuild the project also? I've been writing this program(FOO), and it includes a reference to a dll(BAR).  All BAR contains is methods which perform various different calculations.  FOO will be able to be installed and deployed on multiple computers.  My question is, if I change a formula in one of the methods(i.e. change x + y to x - y), will I need to rebuild FOO against the new BAR?  More importantly, is it safe to just deploy the new version of BAR?

A: If you change a formula contained in a method, there is no need to rebuild the program.  However if you modify the signature of a method by changing the calling arguments it will be necessary to rebuild the program.

A: You just have to make sure the dll for the Bar project is in the bin for the Foo project. As long as the method signatures haven't changed you're good.

A: Concerning the case where the referenced assembly is strongly named: Suppose A is any assembly, B is a strongly-named assembly, and A references B. Then (in contrast to claims made above?) it is possible to change the contents of B without recompiling A. I just tried this, with a trivial console application for A and a class library for B. Changes to the strongly-named B caused no runtime error in A. There is a special case, however: If B makes the transition from not-strongly-named to strongly-named, then A needs to be recompiled, otherwise the will be runtime errors.

A: @vcsjones's comment raises an important point here.
You can drop in a new DLL as a replacement if and only if the assembly version does not change and you are not using strong named assemblies.
If the version does change then you may receive runtime errors because your program tries to load a specific version and gets a different version than it expects.  This may however work fine if no method signatures have changed but I wouldn't guarantee it and would always recommend a recompile.
This is even more of a problem when using strong named assemblies since the strong name encodes both the version and a digital signature of the assembly.  So if any code has changed in the assembly then the digital signature will change even if the version has not, hence the strong name changes.
Again this will cause runtime errors because the strong name your program expects will not match the assembly strong name.  So in this case a recompile is always required.
To summarize:

*

*Code Change, No Version Change and No Strong Names - OKs

*Version Change and No Strong Names - May require recompile, recommended

*Code Change and Strong Named - Requires recompile

*Version Change and Strong Named - Requires recompile

A: Nope - you can drop in a new DLL as needed. As long as the new DLL doesn't break any old functionality, there is no need to rebuild the referencing project.


text:
Q: iOS JMImageCache: Use Default Image I just started using JMImageCache which is really nice and easy to use.  There is just one issue, it doesn't support using a default image until the remote image loads.
Does anyone know how this can be done?

A: If imageForURL:delegate: returns nil, simply set your default image, which you can replace when the delegate method cache:didDownloadImage:forURL: is called.


text:
Q: httpd failed due to SSLProtocol: Illegal protocol 'TLSv1.1' on centos 6.7 I am trying to update TLS1 to TLS1.1 or higher but after doing below changes, Getting error "SSLProtocol: Illegal protocol 'TLSv1.1'"
My Apache and openssl version are :-

httpd -v

Server version: Apache/2.4.2 (Unix)
Server built:   Jul 16 2012 21:11:37

openssl version -a

OpenSSL 1.0.1e-fips 11 Feb 2013
built on: Tue Sep 27 12:27:19 UTC 2016
Centos-version (6.7)

rpm --query centos-release

centos-release-6-7.el6.centos.12.3.x86_64
Did changes for ssl :-

SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256
SSLProtocol -all +SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2
SSLHonorCipherOrder on

I am not sure what is missing here, can anybody help me here,
Thanks in advance.


text:
Q: NoMethodError: undefined method `stringify_keys' for "/auctions/2/comments/9":String Rails I am trying to build a comment system. and update the partials with ajax. Each comment belongs to an auction. Now I have this error since hours.. and cant figure it out:

NoMethodError in Auctions#show

"undefined method `stringify_keys' for /auctions/2/comments/9":String

Extracted Source (Around Line 12):

     <%= link_to 'Destroy Comment', auction_comment_path(comment.auction, comment), id: "#{comment.id}_delete", remote: true, method: :delete,  data: { confirm: 'Are you sure?' } do %>
       <button class="btn btn-flat grey lighten-2 grey-text text-darken-2 waves-effect waves-light">delete</button>
     <% end %>
     <%= link_to 'Edit Comment', edit_auction_comment_path(comment.auction, comment), remote: true do %>

comments_controller.rb:
class CommentsController < ApplicationController
  before_action :all_comments, only: [:index, :create, :update, :destroy]
  before_action :set_comments, only: [:edit, :update, :destroy]
  respond_to :html, :js

  # New Comment (Form)
  def new
    # find Auction related to new Comment
    @auction = Auction.find(params[:auction_id])
    @comment = Comment.new
    @auction.comments.build
  end

  def index
    # created in order to handle renders from this controller, which produce URL 'root/auctions/:id/comments'
    auction = Auction.find(params[:auction_id])
    redirect_to auction
  end

  # Create Comment
  def create
    # find Auction related to new Comment
    @auction = Auction.find(params[:auction_id])
    @comment = @auction.comments.build(comment_params)
    @comment.user_id = current_user.id
    @comment.save
    redirect_to auction_path(@auction), :notice => "Comment sent"
  end

  # Edit Comment
  def update
    @comment = Comment.find(params[:id])
    @comment.update_attributes(params[:body])
  end

  # Delete Comment
  def destroy
    @comment = Comment.find(params[:id])
    @auction = comment.auction
    @comment.destroy
    #redirect_to auction_path(@auction), :notice => "Comment deleted"
  end

  private
  def all_comments
    @comments = Comment.all
  end

  def set_comments
    @auction = Auction.find(params[:auction_id])
    @comment = @auction.comments.find(params[:id])
  end

  def comment_params
    params.require(:comment).permit(:body)
  end
end

views/auction/show.html.erb:

Questions & Answers

    <%= link_to new_auction_comment_path(@auction), remote: true do %>
        <button class="btn">New Question</button>
    <% end %>

<%= render @auction.comments %>

views/comments/_comment.html.erb

  Commenter:
  <%= comment.user.name %>

  Comment:
  <%= comment.body %>

  <%= link_to 'Destroy Comment', auction_comment_path(comment.auction, comment), id: "#{comment.id}_delete", remote: true, method: :delete,  data: { confirm: 'Are you sure?' } do %>
    <button class="btn btn-flat grey lighten-2 grey-text text-darken-2 waves-effect waves-light">delete</button>
  <% end %>
  <%= link_to 'Edit Comment', edit_auction_comment_path(comment.auction, comment), remote: true do %>
      <button>Edit</button>
  <% end %>

views/comments/_form.html.erb
<%= simple_form_for [@auction, @auction.comments.build], remote: true do |f| %>
      <%= f.input  :body %>
      <%= f.button :submit %>
<% end %>


text:
Q: gnuplot: Is there a way to plot vertical lines spatially? I am trying to plot several vertical lines of a variable, say velocity (m/s), against a x-axis of distance (m) and a y-axis of height(m). Each of the velocity profiles come as a function of height measured at different locations. So the aim is to observe how these profiles change spatially.
I have thought to approach this by shifting the vertical profiles by the x-component corresponding to the location where each profile was measured. So if we suppose that the second x-axis depicts velocity I want it to reset to 0 at every point of measurement.
Sketch of desired outcome (ignoring black colour):

Does anyone have any idea of what the right course of action would be? I am using gnuplot but any alternatives are welcome. Thanks in advance.
EDIT:
Below you may have a look at the data I use (file verProfiles in the code snippet)

z(m)
U_1(m/s)*
U_4(m/s)*
U_8(m/s)*

0.50
1.66
1.82
1.95

0.75
1.85
2.04
2.11

1.00
2.00
2.20
2.18

1.25
2.12
2.34
2.21

1.50
2.23
2.36
2.22

1.75
2.33
2.37
2.22

2.00
2.41
2.38
2.22

*The numbers 1, 4 and 8 in the names of U variables in the table above denote the location where the measurements are taken hence each U profile should start and the respective x point in the graph.
The gnuplot code that I've written so far and generates a false graph is:
outName="U_test.png"

set terminal pngcairo font "helvetica,20" size 800, 1000
set xtics nomirror
set x2tics
set xrange [0:10] noreverse nowriteback
set autoscale x2fix
set yrange [0:2.5]
set grid
set mxtics 4
set mx2tics 4
set mytics 4
set key left top
set key samplen 2
set key spacing 0.75
set xlabel  "x"
set x2label "Ux [m s^{-1}]"
set ylabel "z"
set output "$outName"

inp0="verProfiles"

plot \
    inp0 u 2:1 t "U_1" axes x2y1 w lp ps 2 lw 2 lc rgb "#009E73", \
    inp0 u 3:1 t "U_4" axes x2y1 w lp ps 2 lw 2 lc rgb "#3F8B77", \
    inp0 u 4:1 t "U_8" axes x2y1 w lp ps 2 lw 2 lc rgb "#7EA99E"

The generated false graph is:

A: Assuming I've understood your intention correctly, this would be my suggestion.
You want to offset your x-data by 1,4, and 8, so you have to add these values to your columns $2, $3, $4.
If I understood your sketch with 0 m/s correctly, you also want to subtract the first velocity value from it.
Please correct me if I'm wrong.
So, you take the pseudocolumn 0 (check help pseudocolumns), which is basically the line number starting from 0. If $0==0 (check ternary operator help ternary) you assign the current value (only the first value) of your column to a variable, e.g. xoff=$2and subtract it from all following values in your column. Since you have a header you have to skip one line, i.e. skip 1.
In case you want several x-axes on top all starting from 0, this could be either done with arrows and labels or depending on what exactly you need maybe with multiplots (check help multiplot).
Check the following as starting point:
Code:
### plotting with different offsets
reset session

$Data <<EOD
z(m)  U_1(m/s)*  U_4(m/s)*  U_8(m/s)*
0.50       1.66       1.82       1.95
0.75       1.85       2.04       2.11
1.00       2.00       2.20       2.18
1.25       2.12       2.34       2.21
1.50       2.23       2.36       2.22
1.75       2.33       2.37       2.22
2.00       2.41       2.38       2.22
EOD

set xrange[0:10]
set xtics 1
set yrange [0.3:2.4]
set grid xtics, ytics

vs = "1 4 8"
set for [v in vs] arrow from v, graph 0 to v, graph 1 lw 1.5 lc "black" dt 2 nohead

plot $Data u ($0==0?xoff=$2:0, $2+1-xoff):1 skip 1 w lp ps 1.5 lw 2 pt 7 lc "red"   ti "U_1", \
     ''    u ($0==0?xoff=$3:0, $3+4-xoff):1 skip 1 w lp ps 1.5 lw 2 pt 7 lc "green" ti "U_4", \
     ''    u ($0==0?xoff=$4:0, $4+8-xoff):1 skip 1 w lp ps 1.5 lw 2 pt 7 lc "black" ti "U_8"
### end of code

Result:

Addition:
Maybe now I have a better idea about what you probably want.
I guess you "simply" want to have subplots at defined locations within a "Main"plot.
gnuplot offers the feature of multiplot (check help multiplot) which will place several plots next to or on top of each other.
You can define the origin (check help origin) and the size (check help size) of each subplot.
However, the coordinates and sizes of the subplots are given in screen coordinates.
The problem is now: how to place the plot at the desired location relative to the first plot?
With labels, arrows, and objects you can use screen, graph and axes coordinates (check help coordinates), but I am not aware that you can use axis coordinates of the previous plot.
So, you have to calculate these positions yourself using some internal gnuplot variables GPVAL_.... It looks complicated but is just some coordinate transformation.
Code:
### plotting with different offsets
reset session

$Data <<EOD
z(m)  U_1(m/s)*  U_4(m/s)*  U_8(m/s)*
0.50       1.66       1.82       1.95
0.75       1.85       2.04       2.11
1.00       2.00       2.20       2.18
1.25       2.12       2.34       2.21
1.50       2.23       2.36       2.22
1.75       2.33       2.37       2.22
2.00       2.41       2.38       2.22
EOD

set for [v in "1 4 8"] arrow from v, graph 0 to v, graph 1 lw 1.5 lc "black" dt 2 nohead

XFirstToGrphRel(x) = (x-MainXMin)/(MainXMax - MainXMin)   # relative position to graph
YFirstToGrphRel(y) = (y-MainYMin)/(MainYMax - MainYMin)
PosX(x) = XminScrRel+GraphInScrSizeX*XFirstToGrphRel(x)   # screen positon of the subplot
PosY(y) = YminScrRel+GraphInScrSizeY*YFirstToGrphRel(y)
SizeX(dx) = GraphInScrSizeX*dx/(MainXMax - MainXMin)      # screen size of a subplot
SizeY(dy) = GraphInScrSizeY*dy/(MainYMax - MainYMin)

set multiplot

    set xlabel "x / m"
    set xrange[0:12]
    set xtics 1
    set ylabel "z / m"
    set yrange [0.3:2.4]
    set ytics 0.5
    set grid xtics, ytics

    plot 0 w p ps 0 notitle    # plot nothing, just background plot
    # store the current terminal values for later use
    MainXMin = GPVAL_X_MIN
    MainXMax = GPVAL_X_MAX
    MainYMin = GPVAL_Y_MIN
    MainYMax = GPVAL_Y_MAX
    GraphInScrSizeX = real(GPVAL_TERM_XMAX-GPVAL_TERM_XMIN)/GPVAL_TERM_XSIZE*GPVAL_TERM_SCALE  # real() to avoid integer division
    GraphInScrSizeY = real(GPVAL_TERM_YMAX-GPVAL_TERM_YMIN)/GPVAL_TERM_YSIZE*GPVAL_TERM_SCALE
    XminScrRel = real(GPVAL_TERM_XMIN)/GPVAL_TERM_XSIZE*GPVAL_TERM_SCALE
    YminScrRel = real(GPVAL_TERM_YMIN)/GPVAL_TERM_YSIZE*GPVAL_TERM_SCALE

    unset arrow
    set margins 0,0,0,0
    unset xlabel
    unset xtics
    set x2label "v / m/s"
    set x2range [0:2.5]
    set x2tics 0.5 offset 0.5
    unset ylabel
    set format y ""
    set yrange [0.5:2.0]
    set grid x2tics, ytics

    set object 1 rect from graph 0, graph 0 to graph 1, graph 1 behind fc "white"
    set size SizeX(2),SizeY(1.5)

    set origin PosX(1),PosY(0.5)
    plot $Data u 2:1 axes x2y1 w lp pt 7 lc "red" notitle

    set origin PosX(4.0),PosY(0.5)
    plot $Data u 3:1 axes x2y1 w lp pt 7 lc "green" notitle

    set origin PosX(8.0),PosY(0.5)
    plot $Data u 4:1 axes x2y1 w lp pt 7 lc "blue" notitle

unset multiplot
### end of code

Result:


text:
Q: Performance issue with Apache, PHP and Symfony Updated:
================================================================
I finally found the reason with oprofile. It was because the routing cache of Symfony. We have lots of pages with different urls and symfony caches them in one file (serialized data). So the cache file grows large and it needs more CPU to serialize and unserialize data.
Everything went well after I disabled the routing cache
================================================================
We have three web servers with LVS (Apache 2.11 + PHP 5.26), and we use Symfony 1.0 for our products development.
But recently we have updated our products with Symfony 1.2.7 and we got a critical performance issue.
We use Ganglia to monitor our servers. Before the updates, the average load of web servers is under 1. After the updates, the load increases dramatically with load 80 at top (I can see CPU usage increases much from Ganglia).
I can't find the reasons. Is it because the Symfony framework? (But according to Ganglia, the load shouldn't increase so rapidly).
By the way, in our new products lots of AJAX are used, which means there are at least 5-7 PHP requests to open one page. Is this the reason?
Can anyone help me to find all the possible reasons? Or what else information should I offer to diagnose?
Thanks in advance and looking forward to your reply~

A: I finally found the reason with oprofile. It was because the routing cache of Symfony. We have lots of pages with different urls and symfony caches them in one file (serialized data). So the cache file grows large and it needs more CPU to serialize and unserialize data.
Everything went well after I disabled the routing cache


text:
Q: Closing an iframe Video that is fullscreen on mobile, closes entire tab I have an iframe element in my HTML:
<iframe style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;" class="embed-responsive-item" src="images/b.mp4" frameborder="0" allowfullscreen=""></iframe>

If I view the video in full screen on mobile, when I press the button to close full screen, my whole tab closes and I have to navigate back to my website.
Thanks in advance for your help!


text:
Q: Parse Json from Facebook I have been trying to integrate with Facebook SDK to login then get the user's data. so I'm using this method after authentication to get the user's details.
if ([FBSDKAccessToken currentAccessToken]) {
    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
         if (!error) {
             NSLog(@"fetched user:%@", result);
         }
     }];
}

And the data I'm getting is :
2015-07-08 14:02:40.502 Auth-App[whatever] fetched user:{
    "first_name" = Lol;
    gender = male;
    id = 12345;
    "last_name" = Ak;
    link = "https://www.facebook.com/...../....";
    locale = "en_US";
    name = "Lol Ak";
    timezone = 4;
    "updated_time" = "2015-07-08T10:22:32+0000";
    verified = 1;
}

i need to read this array and then display it in text fields.
i tried using results[0] to get the first element in the array but it didn't work.

A: try this way to access data from dictionary
NSLog("%@",[result objectForKey:@"id"]);
NSLog("%@",[result objectForKey:@"first_name"]);
NSLog("%@",[result objectForKey:@"name"]);

same as read all the fields(key/value) pairs. And set your textFields

A: Please put two lines your code
NSDictionary *array=[request.responseString JSONValue];
yourtextfield.text=[array valueForKey:@"first_name"];


text:
Q: Unable to set User Selected Sound to Push Notification Hi I'm working on Push Notification in my app.
In that I'm able to get Notification successfully.
I'm trying to set user selected sound to Push notification.
For that I'm storing user selected sound file path in preferences
 NotificationCompat.Builder  mBuilder =  new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.drawable.ic_launcher);
    mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.notif_icon));
    mBuilder.setContentTitle(context.getString(R.string.app_name));
    mBuilder.setTicker("Message from " +context.getString(R.string.app_name));
    mBuilder.setWhen(System.currentTimeMillis());
    mBuilder.setAutoCancel(true);
    Uri uri = Uri.parse(CommonUtilities.sp.getString("PUSHNOTIFICATIONTONE", "Null"));
    Log.d("Path: ", uri.toString());
    mBuilder.setSound(uri);

I'm getting exact path in Log as I selected before
09-19 16:14:45.511: D/Path:(17832): content://com.estrongs.files/mnt/sdcard/Ringtones/bbm_tone.wav

Can Any one tell me, where I'm getting wrong??


text:
Q: Codeblocks outputs broken executable I have downloaded plenty of different versions of code blocks, and none of them compiles quite right. My hello world runs within code blocks just fine. However, when I run the executable outside of codeblocks, it says "Hello.exe has stopped working". There isn't anything wrong with my code (I don't think.) and my mingw compiles fine outside of codeblocks. What does codeblocks do to my executable? Is there some option to fix this? I am on windows 7 64 bit, and my current code blocks version is 10.05. My program:
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    cin.ignore();
    return 0;
}

A: I solved the problem. I had a broken compiler (or something like that). My suggestion for other people with this problem is to experiment with different versions of the minGW compiler. Also, change the version of code blocks you are using, or even uninstall everything and restart. The problem with mine was I downloaded a bad compiler. [The truth is, codeblocks isn't the best ide.]


text:
Q: Laurent Series of $\frac{1}{z^2(z-2)}$ Expand Laurent series $f(z)=\frac{1}{z^2(z-2)}$ at $|z-2|>2$
Before starting, why isn't it Taylor series? we do not have singularities.

A: We can write
$$f(z) = \frac 1{z^2(z-2)} = \frac{1}{z-2}\frac d{dz} \left( -\frac 1z \right) = \frac{1}{z-2}\frac d{dz} \left( \frac {-1}{2+(z-2)} \right)\\ = -\frac{1}{2(z-2)}\frac d{dz} \left( \frac 1{1+\frac{z-2}2} \right) $$
so it is enough to find Laurent series of $\frac 1{1+\frac{z-2}2}$. Since $|z-2| > 2$, it follows that $\left|\frac{2}{z-2}\right|<1$ and thus
$$\frac 1{1+\frac{z-2}2} = \frac{\frac{2}{z-2}}{\frac{2}{z-2}+1} = \frac{2}{z-2}\sum_{n=0}^\infty \left( -\frac{2}{z-2}\right)^n,$$
where we used that appropriate geometric series converges.
Differentiate it and multiply by $-\frac{1}{2(z-2)}$ to obtain Laurent series of $f$ on the annulus $|z-2|>2$.


text:
Q: Application Needs Fiddler to Execute Properly on Some PCs I have a VB6 application that only runs under certain conditions. When it fails (on the send statement below), it generates a
Run-time error '-2147012867 (80072efd)': A connection with the server could not be established
The funny thing is that it always runs when Fiddler is running. On some machines it runs whether or not Fiddler is running, but on other machines it will only run when Fiddler is running. Fiddler doesn't even have to be capturing traffic for it to run.
The request is to an https site.
The code looks like this:
Set xhr = CreateObject("WinHttp.WinHttpRequest.5.1")
xhr.open "POST", sUrl, bAsync
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xhr.setRequestHeader "Content-Length", Len(sBody)
xhr.send sBody

I've read the Telerik article, Help! Running Fiddler Fixes My App???, but none of the suggested solutions seems to work.
Can anyone provide me with any insight on what might be wrong or how I can solve this?

A: Setting the Proxy to HTTPREQUEST_PROXYSETTING_DIRECT solved the problem.
' Important Note: The setProxy setting of 1 corresponds to HTTPREQUEST_PROXYSETTING_DIRECT
' (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa384059(v=vs.85).aspx)
' Without this, the app would only work on the dev machine when Telerik Fiddler was also
' running. Oddly, the app would run correctly on all other machines.

Set xhr = getRequestObject()
xhr.setProxy 1
xhr.open "POST", sUrl, bAsync
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xhr.setRequestHeader "Content-Length", Len(sBody)

The Microsoft article cited above gives three values for the constants that the Proxy can be set to. I don't understand why the "Direct" setting worked, but it did.
Thanks to Jeandey and anyone else that looked at this.

A: Could you check your WinHttpSettings registry key settings?

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet
  Settings\Connections\WinHttpSettings

Default value (no proxy) is

I suppose that Fiddler modified this configuration in order to act as proxy.
If Fiddler is not running => no proxy => connection error.
In WinHttpRequest, if setProxy is not explicitly called => HTTPREQUEST_PROXYSETTING_DEFAULT => HTTPREQUEST_PROXYSETTING_PRECONFIG

HTTPREQUEST_PROXYSETTING_PRECONFIG
Indicates that the proxy settings should be obtained from the
  registry.


text:
Q: Find certain value and add new value I've got a dictionary in a mysql db with international words in it. I want to find these words and insert a new version. Not replace.
IE when a user runs a PHP query for the value "currencies", both spellings below comes up in the search results.
¥en -
Yen
I had an idea on searching for all rows containing ¥ and replace them with Y and export to a new db/tabel and then import them again to the old DB but there must be a easier solution, right?
mysql> SELECT * FROM money WHERE name LIKE '%¥%';

A: I think something like this should work for your specific example:
INSERT INTO money (Field1, Field2, Name)
SELECT Field1, Field2, REPLACE(name, '¥', 'Y') n
FROM money
WHERE name LIKE '%¥%';

This will insert a new record in your Money table replacing the ¥ with a Y.
Good luck

A: http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
e.g.
   INSERT INTO money
      SELECT REPLACE(name,'¥','Y') FROM money WHERE name like '%¥%';


text:
Q: Android - Material EditText I have created a material edittext( I think it's called so I am new to Android App development). And it is in an Dialog but I it always is focused on start but I don't want it to be focused on start. Can someone help me please??
My code :
final android.support.design.widget.TextInputLayout Tlay=new android.support.design.widget.TextInputLayout(MainActivity.this); Tlay.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linear1.addView(Tlay); final android.support.design.widget.TextInputEditText EditText1=new android.support.design.widget.TextInputEditText(MainActivity.this); EditText1.setHint("Material EditText"); EditText1.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)); Tlay.addView(EditText1);

A: I guest that you want to hide the softkeyboard when the dialog is shown.
If I'm right then you should try to set the android:focusableInTouchMode="true" in the View root
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:focusableInTouchMode="true"
              android:padding="16dp"
              tools:context=".MainActivity">
<!-- Child views -->
</LinearLayout>

If you want to move the pointer from a EditText to the others. You should watch the tutotial (at 16:00).
Hope it helps.


text:
Q: returning different datatypes from a function in python How do we return a sparse matrix and an array data from a function. My sparse matrix is
sparse_mat
<540x5550 sparse matrix of type ''
    with 9068 stored elements in COOrdinate format>
and the other data is session_id:
array([['192.168.113.111_timesofindia.indiatimes.com_1', 'User'],
     ['192.168.113.111_timesofindia.indiatimes.com_2', 'User'],
      dtype='|S46')

I want to return both these data from a function.Thanks

A: Use a tuple:
 def foo(x, y):
   sum = x + y
   return (x, y, sum)

See? I returned 3 items. And what is more, if I know the airity of the tuple, then I can use an extractor to capture them:
 (m, n, total) = foo(4, 5)

wherein m is assigned 4, n is assigned 5 and total is assigned 9.

A: You can return more than one value from a Python function by returning a tuple:
return sparse_mat, session_id

The caller can get the returned value by something like:
m, id = your_function()

Oh, and it doesn't make any difference if there are two different data types. You can return two values of the same type too of course.

A: Examples
def return2():
    a = {1:1}
    b = 'b'
    return a,b

def anotherReturn2():
    a = {1:1}
    b = 'b'
    return {'a' : a, 'b' : b}

a_1, b_1 = return2()
a_2 = return2()[0]
b_2 = return2()[1]
print a_1, b_1, a_2, b_2

a_1, b_1 = anotherReturn2()
a_2 = anotherReturn2()['a']
b_2 = anotherReturn2()['b']
print a_1, b_1, a_2, b_2

>>>
{1: 1} b {1: 1} b
a b {1: 1} b
>>>


text:
Q: how to copy all source jars using gradle We have an old playframework 1.2.x version where we copy all the jars to project/lib so playframework can consume them.  We would LOVE to copy all the source jars as well so that when runnig play eclipsify, we can view all the third party source.  Is there a way to do this with gradle?
and I mean all the source jars that were downloaded when I ran gradle eclipse as I saw them download the cache locations.  We have gradle eclipse calling play eclipsify for us on the one project as well so we can 100% just use gradle.
thanks,
Dean

A: this is not that straight forward as expected. The following snippet copies the source jars for all dependencies (runtime + compile) of a java project into a specific folder:
    task copySourceJars(type:Copy){
        def deps = configurations.runtime.incoming.dependencies.collect{ dependency ->
            dependency.artifact { artifact ->
                    artifact.name = dependency.name
                    artifact.type = 'source'
                    artifact.extension = 'jar'
                    artifact.classifier = 'sources'
                }
            dependency
        }
        from(configurations.detachedConfiguration(deps as Dependency[]).resolvedConfiguration.lenientConfiguration.getFiles(Specs.SATISFIES_ALL))
        into('sourceLibs')
    }

The reason we use a lenientConfiguration here is, that we don't want to fail if a source artifact cannot be resolved. There might be a more elegant way, but I havn't looked deeper into that.
hope it helps,
René

A: Rene answer will download sources jars of direct dependencies, not sources jars of all transitives dependencies.
Here is a task that will do the trick:
task copySourceJars( type: Copy ) {
  def sources = configurations.runtime.resolvedConfiguration.resolvedArtifacts.collect { artifact ->
    project.dependencies.create( [
      group: artifact.moduleVersion.id.group,
      name: artifact.moduleVersion.id.name,
      version: artifact.moduleVersion.id.version,
      classifier: 'sources'
    ] )
  }
  from configurations.detachedConfiguration( sources as Dependency[] )
    .resolvedConfiguration.lenientConfiguration.getFiles( Specs.SATISFIES_ALL )
  into file( 'some-directory/' )
}

One can then do the very same for javadocs jars by changing the classifier to javadoc.

A: Here eskatos solution translated in Kotlin DSL:
tasks {
    "copySourceJars"(Copy::class) {
        val sources = configurations.runtime.resolvedConfiguration.resolvedArtifacts.map {
            with(it.moduleVersion.id) {
                dependencies.create(group, name, version, classifier = "sources")
            }
        }
        from(
            configurations.detachedConfiguration(*sources.toTypedArray())
                .resolvedConfiguration.lenientConfiguration.getFiles(Specs.SATISFIES_ALL)
        )
        into(File("some-directory"))
    }
}


text:
Q: Silverlight and Windows Workflow Foundation Can I make a Silverlight application communicate with a Windows Workflow Foundation (WF) application? If yes, how can I do that?
I tried to add a reference from my Silverlight application to a WF application and it doesn't work.

A: If your application was a service application, then yes.
Silverlight won't host a workflow, but it could call a workflow service if the workflow you need to run is hosted within a service rather than an application.
It should be a matter of adding the service reference within the Silverlight application.


text:
Q: Why is .each() not working in D3? I have a column of buttons. When a user clicks a button I want to show a message, and hide it after a few seconds.
Jsfiddle
HTML

    Add

    Add

</div

D3
d3.select(".add")
  .on("click", function() {
    d3.selectAll(".message")
      .each(function() {
        d3.select(this)
          .transition()
          .duration(500)
          .style("opacity", 1)
          .text("added");
     })
   })

I have 2 issues:

*

*When the 'add' button is clicked all the messages show, instead of the one beside the clicked button. Is there something wrong with the way I've used .each?

*I can't hide the message after some duration. I tried using delay and fadeOut but it broke the entire function.
Any help greatly appreciated.
Snippet

d3.selectAll(".add")
  .on("click", function() {
    d3.selectAll(".message")
      .each(function() {
        d3.select(this)
          .transition()
          .duration(500)
          .style("opacity", 1)
          .text("added");
      })
  })
.wrapper {
  display: inline-block;
  margin: 50px;
  width: 200px;
}
.wrapper div {
  padding: 16px 32px;
  background-color: grey;
  color: #FFF;
  font-family: sans-serif;
  cursor: pointer;
  text-align: center;
  margin-bottom: 5px;
  position: relative;
}
.wrapper span {
  position: absolute;
  right: -60px;
  bottom: 10px;
  background-color: lightblue;
  color: black;
  font-size: 12px;
  padding: 8px 16px;
  opacity: 0;
}

    Add

    Add

    Add

    Add

    Add

A: Here's how I would code it:
d3.selectAll(".add")
    .on("click", function() {
      var m = d3.select(this.children[0]);
      m.text("added")
        .style("opacity", 1);
      m.transition()
        .delay(500)
        .duration(1000)
        .style("opacity", 0);
   });

Running:

d3.selectAll(".add")
  .on("click", function() {
    var m = d3.select(this.children[0]);
    m.text("added")
      .style("opacity", 1);
    m.transition()
      .delay(500)
      .duration(1000)
      .style("opacity", 0);
  })
.wrapper {
  display: inline-block;
  margin: 50px;
  width: 200px;
}
.wrapper div {
  padding: 16px 32px;
  background-color: grey;
  color: #FFF;
  font-family: sans-serif;
  cursor: pointer;
  text-align: center;
  margin-bottom: 5px;
  position: relative;
}
.wrapper span {
  position: absolute;
  right: -60px;
  bottom: 10px;
  background-color: white;
  color: black;
  font-size: 12px;
  padding: 8px 16px;
  opacity: 0;
}

    Add

    Add

    Add

    Add

    Add


text:
Q: how can i change list with custom tag in jsp? I faced following problem with custom tag in JSP.
html content list generated by div custom tag when page loading end.
after that, i want to replace the list with ajax`s new data.
first, I emptied old list. and i made a html string(pdListHtml), append it.
but I cant get any new list at all.
please point me out if there is something wrong with the code.
thanks.
html.jsp

    <c:forEach var="goods" items="${goods}">

            <pt:product prdNm="${goods.goods_name}" dispPrc="${goods.goods_origin_price }"/>

    </c:forEach>

Ajax JS
const filterParam = $("#submitForm").serializeArray();

$.ajax({
    type : "post",
    url : "/ctgrSearchFilter.do",
    data : filterParam,
    dataType : "json",
    success : function(data) {
        $(".pdImgType").empty();
        const goods = data.result.goods;

        for(let i=0 ; i < goods.length ; i++){
            let pdListHtml = "";
            pdListHtml += '
';
            pdListHtml += '<pt\:product prdNm=\"'+ goods[i].goods_name +'\" dispPrc=\"'+ goods[i].goods_origin_price +'\"/>';
            pdListHtml += '
';
             $(".pdImgType").append(pdListHtml);
        }
     },
     error : function(err) {
         alert("error");
     }
});

data from java
@RequestMapping(value = "/ctgrSearchFilter.do" , method = equestMethod.POST)
@ResponseBody
public JSONObject ctgrSrhFilter(HttpServletRequest request) throws Exception {
    JSONObject json = new JSONObject();
    ModelAndView mv = commSearchService.callSearchAllNewAPI(request);
    logger.info(">>>> ctgr result mv : "+ mv);
    json.put("result",  mv.getModel());

    return json;
}

console log in java
ctgr result mv : ModelAndView: materialized View is [null]; model is {cateCntTot=0, cate=[], brand1List=[], delryList=[], total=1254, goods=[{goods_name=nice, goods_origin_price=109000}]}

A: You need to get goods using data.goods and then loop over it .Also ,check if your json is valid or not .
Demo Code :

//your json response
var data = {
  "cateCntTot": 0,
  "cate": [],
  "brand1List": [],
  "delryList": [],
  "total": 1254,
  "goods": [{
    "goods_name": "nice",
    "goods_origin_price": 109000
  }]
};
var pdListHtml = "";
///fetching data->goods
var goods = data.goods;
for (let i = 0; i < goods.length; i++) {

  //your html
  /*pdListHtml += '
<pt\:product prdNm=\"' + goods[i].goods_name + '\" dispPrc=\"' + goods[i].goods_origin_price + '\"/>
';*/

  //demo data to append
  pdListHtml += '
prdNm :' + goods[i].goods_name + '
dispPrc :' + goods[i].goods_origin_price + '
'

}
//add data under pdImgType class
$(".pdImgType").html(pdListHtml);

  <c:forEach var="goods" items="${goods}">

      <pt:product prdNm="${goods.goods_name}" dispPrc="${goods.goods_origin_price }" />

  </c:forEach>


text:
Q: how to get the number of occurrence of an expression in a file using python I have a code that read files and find the matching expression with the user input and highlight it, using findall function in regular expression.
also i am trying to save in json file  several information based on this matching.
like :

*

*file name

*matching expression

*number of occurrence

the problem is that the program read the file and display the text with  highlighted expression but in the json file it save the number of occurrence as the number of lines.
in this example the word this is the searched word it exist in the text file   twice
the result in the json file is = 12 ==> that is the number of text lines
result of the json file and the highlighted text
code:
def MatchFunc(self):

    self.textEdit_PDFpreview.clear()
    x = self.lineEditSearch.text()
    TextString=self.ReadingFileContent(self.FileListSelected())
    d = defaultdict(list)
    filename = os.path.basename(self.FileListSelected())

    RepX=''+x+''

    for counter , myLine in enumerate(filename):

        self.textEdit_PDFpreview.clear()
        thematch=re.sub(x,RepX,TextString)
        thematchFilt=re.findall(x,TextString,re.M|re.I)

        if thematchFilt:
            d[thematchFilt[0]].append(counter + 1)

            self.textEdit_PDFpreview.insertHtml(str(thematch))

        else:
            self.textEdit_PDFpreview.insertHtml('No Match Found')

    OutPutListMetaData = []
    for match , positions in d.items():

        print ("this is match {}".format(match))
        print("this is position {}".format(positions))

        listMetaData = {"File Name":filename,"Searched Word":match,"Number Of Occurence":len(positions)}
        OutPutListMetaData.append(listMetaData)
        for p in positions:
            print("on line {}".format(p))

    jsondata = json.dumps(OutPutListMetaData,indent=4)
    print(jsondata)

    folderToCreate = "search_result"
    today = time.strftime("%Y%m%d__%H-%M")
    jsonFileName = "{}_searchResult.json".format(today)

    if not(os.path.exists(os.getcwd() + os.sep + folderToCreate)):
        os.mkdir("./search_result")
    fpJ = os.path.join(os.getcwd()+os.sep+folderToCreate,jsonFileName)
    print(fpJ)

    with open(fpJ,"a") as jsf:
        jsf.write(jsondata)
        print("finish writing")

A: It's straightforward using Counter. Once you pass an iterable, it returns each one of them along with the number of occurrences as tuples.

A: As the re.findall function returns a list you can just do len(result).


text:
Q: VBA matching Pairs without Duplicates What I have been asked to do is take a users input as an integer. For example, 6 is the input. 6 gets passed into an equation (6 - 1)*(6)/2 this equates to 15 pairs. I then call another sub that processes the input into a set of {for next} loops. I have an If statement that checks duplicates but it is limited. I have tried passing in the iterative variable into the if statement but this will not work properly.
Here is the code:
For intOuter = 1 To options - 1

    'The intInner loop cycles through and sets up the loop for the combination and determines if
    'the combination has been made already

        For intInner = 1 To options

    'If statement tests if a combination has already been made if it has it will not be printed
    'if it has not been combined then it will be printed to the immediate window

                If intOuter <> intInner And intOuter <> value + 1 And intOuter <> value + 2 And intOuter <> value + 3 _
                And intOuter <> value + 4 Then
                       Debug.Print intOuter & " vs " & intInner & "  Actual"
                End If

        Next intInner

    Next intOuter

The output for this example correctly displayed would be (with a user input of 6)
1vs2
1vs3
1vs4
1vs5
1vs6
2vs3
2vs4
2vs5
2vs6
3vs4
3vs5
3vs6
4vs5
4vs6
5vs6

Thanks in advance I really Appreciate it.

A: Looks like you were close!  Try this:
   Dim intInner As Integer
   Dim intOuter As Integer

   For intOuter = 1 To Options - 1
       For intInner = intOuter + 1 To Options
          Debug.Print intOuter & "vs" & intInner
       Next
   Next


text:
Q: Incorrect syntax near GOTO label in SQL Server stored procedure I am using a GOTO statement inside a try block and also in catch block in a stored procedure.When it comes to the definition of GOTO label after END catch, it shows incorrect syntax error. below is the procedure. Error comes at 'AuditLog :' in the procedure. please help me with this.
ALTER PROCEDURE [dbo].[Proc_PIP_Employee]
    @Flag int = 1,
    @Empid int = 0,
    @Name nvarchar(500) = '',
    @Designation nvarchar(200) = '',
    @Department nvarchar(200) = '',
    @DateofJoin datetime = '' ,
    @Phone nvarchar(3000) = '',
    @Isactive int = 1,
    @LoginUser nvarchar(500) = ''
AS
BEGIN
    SET NOCOUNT ON ;
    DECLARE @r int;

    BEGIN TRY
    BEGIN TRANSACTION
        DECLARE @errorMessage VarChar(8000),
                @errorSeverity Int,
                @errorState Int,
                @ReturnId Int,
                @AlCode varchar(50),
                @AlDesc varchar(1000),
                @AlOp varchar(50),
                @AlStatus varchar(50)

        IF (@Flag = 1)
        BEGIN
            IF EXISTS (SELECT 1 FROM dbo.PIP_Employee
                       GROUP BY Name, Phone
                       HAVING COUNT(ID) > 0
                          AND Name = @Name AND Phone = @Phone)
            BEGIN
                SET @ReturnId = 0
                SET @AlCode = 'ERROR_1001'
                SET @AlDesc = CONCAT('Add Record of ',@Name,' failed due to duplicate entry')
                SET @AlOp = 'ADD'
                SET @AlStatus = 'ERROR'
                GOTO AuditLog
            END
            ELSE
            BEGIN
                INSERT INTO dbo.PIP_Employee (Name, Designation, Department, DateofJoin, Phone, IsPresent)
                VALUES (@Name, @Designation, @Department, @DateofJoin, @Phone, @Isactive)

                SET @ReturnId = 1
            END
        END

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SET @AlCode = ERROR_SEVERITY()
        SET @AlDesc = ERROR_MESSAGE()
        SET @AlOp = 'SQL TRANSACTION FAILURE'
        SET @AlStatus = ERROR_STATE();
        GOTO AuditLog

        IF (@@trancount > 0)
            ROLLBACK TRANSACTION
    END CATCH

AuditLog :
    INSERT INTO dbo.PIP_AuditLog (Aud_Code, Aud_Desc, Aud_Operation, Aud_Status, Aud_Createddate, Aud_ActionBy)
    VALUES (@AlCode, @AlDesc, @AlOp, @AlStatus, GETDATE(), @LoginUser)

    SET NOCOUNT OFF
END

AuditLog : seems to be an incorrect syntax.

A: If you are not using an IDE with syntax checking like SQL Server Management Studio, you might want to check out some free tools like https://ubitsoft.com/t-sql-beautilyzer/.
This indicates that line 68 is bad.  Namely that labels should NOT have a space between the label and the ':'


text:
Q: Объединение данных двух таблиц по общему значению ячейки Есть таблица с двумя листами в Google Docs. Как объединить их данные по общему полю "Артикул" при совпадении значений? Т.е если в обоих таблицах есть общий артикул "BL001" то задача их объединить. Моя попытка решения заключалась в использовании =IMPORTRANGE("google_docs_url"; "Лист2!A1:D4") но она не производит сопоставление SKU

В результате нужно получить такую таблицу

A: Данные подтягивать с помощью функции  ВПР (VLOOKUP)
=ВПР(артикул;диапазон_второго_листа;столбец;0)

артикул - ссылка на ячейку с артикулом в этой строке;
диапазон_второго_листа - диапазон, первый столбец которого содержит артикулы;
столбец - номер столбца с нужными данными (номер считается от столбца с артикулами);
0 указывает на поиск точного соответствия артикула.
Формулу можно сделать протягиваемую для всех четырех столбцов, закрепив диапазоны в нужных местах:
=ВПР($A2;Лист2!$A$2:$D$25;СТОЛБЕЦ(B1);0)

Но при небольшом количестве столбцов не составит труда копировать формулу и указать номер столбца константой (2, 3 или 4)


text:
Q: Create Custom SQL Server Role in SQL 2008 Server I want to add new custom SQL Server Role and assign the new users to these appropriate roles respectively.  I try to find how to create role, but I could not find the place to add that.  Could you please guide me how to achieve my requirement?

A: You cannot do this in the 2008 version just yet - this is a new feature that you'll get with SQL Server 2011 (a.k.a. "Denali") sometime in 2011/2012.
See some resources:

*

*Create your own fixed server roles

*Custom server roles in SQL Server Denali

*Add your OWN server role in Denali

A: You'd simply GRANT the rights you want to a login rather than a role pre SQL Server 2011. Not ideal of course but it works.
We use this to enable app teams to see what is going on without hassling the DBAs.
For example,
CREATE LOGIN [MyDOmain\FolkITrustGroup] FROM WINDOWS;
GO
GRANT VIEW SERVER STATE TO  [MyDOmain\FolkITrustGroup]
GRANT VIEW ANY DEFINITION TO  [MyDOmain\FolkITrustGroup]
GO

Edit: This achieves your requirement without using server roles which don't exist yet...

A: You can create Database level roles see Create Role and the links on the page for more detail.

A: Well I don't have SQL server installed right now so I can't check. But my knowledge of SQL tells me :
creating a role :
create role <rolename>;

granting privilages :
grant <privilages> on <relation> to <rolename>;

revoking privilages :
revoke <priv> on <rel> from <rolename>;

grant role to user :
grant <rolename> to user;

You can also create the hierarchy of it :
e.g.>
create role supervisor;
grant select, insert on db.table to supervisor;
create role manager;
grant supervisor to manager;

grant manager to John;

This is the standard SQL way. It is not available yet in current versions of some DBMS. Not sure about SQL server.

A: ****A. Creating a server role that is owned by a login****

****The following example creates the server role buyers that is owned by login BenMiller.****

USE master;
CREATE SERVER ROLE buyers AUTHORIZATION BenMiller;
GO

****B. Creating a server role that is owned by a fixed server role****

****The following example creates the server role auditors that is owned the securityadmin fixed server role.****

USE master;
CREATE SERVER ROLE auditors AUTHORIZATION securityadmin;
GO


text:
Q: Writing equations that represent 3D and 2D objects I want to represent a speed-breaker that I find in road in the form of an equation. Let's call it 3D speed-breaker.
3-Dimensions
The following is the speed-breaker that I can draw on a piece of a paper. Let's call it 2D speed-breaker.
2-Dimensions
The 2D speed-breaker can be built by inputting numbers into a function which is in terms of 'x'.
y = f(x) lets me represent 2-dimensional speed-breakers in the form of an equation.
'x' is input. 'y' is output to build a 2D speed-breaker.
How to represent a 3-dimensional speed-breaker in the form of an equation?
I want to represent a 3D speed-breaker in the form of an equation.
Should I have 'x' as input and y,z as output to form this 3D speed-breaker?
In 2D speed-breaker I have only 'y' as unknown. In 3D speed-breaker I have two unknowns and 1 known?
Hence the question - how to represent a 3-dimensional speed-breaker in the form of an equation? Out of x,y,z how many are known and how many are unknown? What is the variable into which I need to plugin numbers to form 3D speed-breakers?

A: There are some different options. For example:

*

*You can try to fit a function to your speed-breaker $$z=f(x,y)$$

*Or you can write it as a level set of some function $$f(x,y,z)=0$$

The second one is the most general one, but it is also often the most difficult one.
An example of 1) is $z =f(x,y)= \cases{1-\sqrt{(x^2+y^2)}, \text{ if } x^2+y^2<1\\0\phantom{1-\sqrt{(x^2+y^2)}}, otherwise}$
which will be a cone.

A: Let $f$ the function representing the $2$D speed-breaker.
Then define $$g(x,y)=\begin{cases} f(x) & \text{if } |y| \le L \\
 0 & \text{otherwise}\end{cases}$$
With $L$ the width of the $3$D speed-breaker.
Then just draw $z=g(x,y)$.


text:
Q: How to remove list of array from another using one line of code javascript I have two arrays in angular, products and productsGreen. Where product contain all the product and productsGreen has only success products.
When someone uncheck green checkbox I want to remove productsGreen from products. I have seen many answers they are using loops and writing multiple lines of code.
Is that possible to do in one line of code like products.remove(productsGreen).
This is my array products
{
    "color": "green",
    "loc": "L1"
},
{
    "color": "green",
    "loc": "L2"
},
{
    "color": "red",
    "loc": "L5"
},
{
    "color": "red",
    "loc": "L6"
},

This is my array productsGreen
{
    "color": "green",
    "loc": "L1"
},
{
    "color": "green",
    "loc": "L2"
},

I need output
{
    "color": "red",
    "loc": "L5"
},
{
    "color": "red",
    "loc": "L6"
},

Edit 1:
This is my code
OnChangeGreen($event)
{
if(this.CheckboxGreen==true)
{
  this.CheckboxGreen=false;
  this.chartData.pop(this.mapDatagreen)
  this.mapImageSeries.data=this.chartData;
  this.chartData.validateData();
}
}

A: You can filter an array of objects by properties. Basic idea:

var data = [{
    "color": "green",
    "loc": "L1"
  },
  {
    "color": "green",
    "loc": "L2"
  },
  {
    "color": "red",
    "loc": "L5"
  },
  {
    "color": "red",
    "loc": "L6"
  }
];

const selectItems = filters =>
  data.filter(item => filters.includes(item.color))

console.log("red", selectItems(["red"]));
console.log("green", selectItems(["green"]));
console.log("red green", selectItems(["red", "green"]));
console.log("blue", selectItems(["blue"]));


text:
Q: Weird MySQL encoding issue I have a column in the pages table with arabic data.
If I do this...
@mysql_query( "select title from pages where web_id = '$id'" );

I get correct data, in arabic.
But if I call the same function again, in fact, it's in a loop, the second time it brings me garbage data. Looking something like this
"تنظيم الأوقا٠العامة اقرأ قطاع

Also, if before that query, I do either of this:
@mysql_query("SET NAMES 'utf8'");
@mysql_set_charset( 'utf8' );
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'" );

I always get garbage data, even on first call. What's happening here?
Note that database, table and field collations are set to utf8_bin

A: Some random hints:
Try not use the @ operator. It will suppress any error message.
You need to escape input parameters properly:
mysql_query("SELECT title FROM pages WHERE web_id = '" . mysql_real_escape_string($id) . "'");

You need to check the return value of mysql_query():
$res = mysql_query("SELECT title FROM pages WHERE web_id = '" . mysql_real_escape_string($id) . "'");
if(!$res){
    die('Could not fetch page title'); // See mysql_error() for error message
}

Make sure your PHP source code is saved as UTF-8. Any decent editor will allow you save as UTF-8 and will display current encoding in the status bar.
Check your table definition. MySQL allows to set per table and column encodings.
Set the connetion encoding with mysql_set_charset().
Make sure the browser renders your page as UTF-8. In PHP, you can generate the appropriate HTTP header with:
header('Content-Type: text/html; charset=utf-8');

A: You should verify whether your field actually contains UTF-8 data.  Even if it's set to UTF-8 you may have imported data incorrectly or that data might be corrupt.  You can look at the specific byte stream using:
SELECT hex(myfield) FROM mytable;

If you've imported data you should note that the data file might have been interpreted as being in a different encoding - indeed it might even have been do.  You'd need to ensure that the file is correctly recognised, e.g.:
mysql --default-character-set=utf8 database < mydbbackup.sql


text:
Q: Reading text using a function like sprintf in R Suppose I have the following text:
"    7.7597     4.7389     3.0058     0.0013"

I know it's format:
" %9.4f  %9.4f  %9.4f  %9.4f"

I want to extract variables out of it. I want something like sprintf/gettextf function but does does the reverse:
??????(" %9.4f  %9.4f  %9.4f  %9.4f", v1, v2, v3, v4)

How can I do that? (without loading any packages, if possible)
The unreliable method I use right now is:
temp <- as.numeric(unlist(strsplit("    7.7597     4.7389     3.0058     0.0013"," ")))
temp[!is.na(temp)]

A: I would do:
scan(text="  7.7597     4.7389     3.0058     0.0013")
#Read 4 items
#[1] 7.7597 4.7389 3.0058 0.0013

It correctly reports NAs:
scan(text="   7.7597  NA   4.7389     3.0058     0.0013")
#Read 5 items
#[1] 7.7597     NA 4.7389 3.0058 0.0013

It breaks on malformed input (non-numeric). So you can control it with a tryCatch:
tryCatch(scan(text=" abc  7.7597  4.7389"), error= function(e) cat("Malformed input\n"))
#Malformed input

Under the hood
How come that scan gets the floats properly? The function has an argument, what, to set the data type you are scanning for. The default parameter is
scan(...,  what=double())

So it parses pretty well the floats required in the question. Anyway, should you change your needs and looking for different data types, try:
scan(text="  7  4  3  0 ", what=integer())
#Read 4 items
#[1] 7 4 3 0

As usual you can check for data consistency:
tryCatch(scan(text=" 1 2.3", what=integer()), error= function(e) cat("Non-integer value(s) passed!\n"))
#Non-integer value(s) passed!

A: Why not make your method more reliable, instead of searching for something that may not even exist.
> x <- "    7.7597     4.7389     3.0058     0.0013"

> unlist(read.table(text = x, strip.white = TRUE), use.names = FALSE)
# [1] 7.7597 4.7389 3.0058 0.0013

> as.numeric(sapply(strsplit(x, "\\s+"), "[", -1))
# [1] 7.7597 4.7389 3.0058 0.0013

> as.numeric(strsplit(x, "\\s+")[[1]])[-1]
# [1] 7.7597 4.7389 3.0058 0.0013

> library(stringr)
> as.numeric(strsplit(str_trim(x), "\\s+")[[1]])
# [1] 7.7597 4.7389 3.0058 0.0013

> as.numeric(str_extract_all(x, "[0-9][.][0-9]+")[[1]])
# [1] 7.7597 4.7389 3.0058 0.0013