text:
Q: tomcat не считывает данные из контекста Настроил проект. Собрал его мавеном. Настроил томкат.
Почему то в файл который он создает себе для дальнейшего считывания
"C:\{user}\.IntelliJIdea2018.1\system\tomcat\Unnamed_sk"

содержит только <Context path=...>, а прочие настройки из моего файла конфигурации не скопировались.

A: ошибка заключалось в том что при поиске контекста томак автоматически проверяет синтаксис файла configUser.xml и если синтаксис содержит ошибки томкат его не видит. но название файла может в памяти сохраниться. и получается словно файл подключен.
решение - открыть файл в ИДЕ и проверить синтаксис. я забыл поставить /.
после этого все отработало.


text:
Q: How to Access List's elements in c# I have a list of lists like : List<List<int>> a ;
How can I initialize it like this:
<2 1> <3 0> <5 1>

I mean the list "a" has three lists that each one has 2 elements
And then how can i access each element or change the value of them?

A: You can initialise your list like this:
var list = new List<List<int>>()
{
    new List<int>() {2, 1 },
    new List<int>() {3, 0 },
    new List<int>() {5, 1 }
};

And then you can access each element like this:
var x = list[0][1]; // 1
var y = list[1][0]; // 3

And you can access each inner list like this:
var inner = list[0];// List<int> (2, 1)

And you can update the list like this:
list[0][1] = 42;

or
list[0] = new List<int>() { 10, 11 };

EDIT: How to initialise the list with 10 lists of 1, 1
var list = new List<List<int>>();
for(var i=0;i<10;i++)
{
    list.Add(new List<int>() {1, 1});
};

A: he needs a list of 3 lists of 2 elements each.
List<List<int>> a = new List<List<int>> { new List<int>() { 2, 1 }, new List<int>() { 3, 0 }, new List<int>() { 5, 1 } };

redpajama_set_name: RedPajamaStackExchange


text:
Q: Different types doesnt write to file I am creating three text files, and try to write to them from a list. When I have the code like in the first example, nothing is written to the first file, only second or third. If written like in the second code, nothing is written to the first or second file, only third. What is wrong and how can I correct this code so it writes to all three files? The files are created successfully.
class Operasjonsleder{
    PrintWriter skriver=null;
    public void ferdig(ArrayList<Melding> meldinger) throws FileNotFoundException, UnsupportedEncodingException, IOException, NullPointerException{
        ArrayList<Melding> andreMeldinger=new ArrayList<Melding>();
        andreMeldinger=sortere(meldinger);
        int id=0;
        for(int i=0; i<andreMeldinger.size(); i++){
            if(andreMeldinger.get(i).hentID()!=id){
                if(id>1){
                    skriver.close();
                }
                id=andreMeldinger.get(i).hentID();
                String n=String.valueOf(id);
                skriver = new PrintWriter(n+".txt", "UTF-8");
            }
            skriver.println(andreMeldinger.get(i).hentInnhold());
            skriver.println("");
            skriver.println("");
        }
        skriver.close();
    }

    class Operasjonsleder{
        PrintWriter skriver=null;
        public void ferdig(ArrayList<Melding> meldinger) throws FileNotFoundException, UnsupportedEncodingException, IOException, NullPointerException{
            ArrayList<Melding> andreMeldinger=new ArrayList<Melding>();
            andreMeldinger=sortere(meldinger);
            int id=0;
            for(int i=0; i<andreMeldinger.size(); i++){
                if(andreMeldinger.get(i).hentID()!=id){
                    if(id>1){
                        skriver.close();
                    }
                    id=andreMeldinger.get(i).hentID();
                    String n=String.valueOf(id);
                    skriver = new PrintWriter(n+".txt", "UTF-8");
                }
                skriver.println("Whatever");
                skriver.println("");
                skriver.println("");
            }
            skriver.close();
        }


text:
Q: Installing local package with pip install . doesn't work without -e flag I have written a small python package that I would like to install locally through pip. I used to do this by navigating to the package directory with the setup.py file, and then running pip install . after which the pip installer goes through the cycle and notifies me that it succesfully installed the package. When I check pip freeze, it is indeed listed there. However, when I then launch the Python interpreter and try to import my package, it throws a ModuleNotFoundError.
However, when I install through pip install -e ., this is not the case and it imports without problem.
I have used this approach already multiple times with other packages, but I can't seem to find why it keeps failing this particular time. I have already tried it with 2 different virtualenv's, verified I was using the right interpreter each time, but to no avail.
Thanks for the help!

A: I've been able to address the problem! It is based on this solution.
I wrote a setup.py file, but in the setup part I did not include packages=find_packages(). Therefore, it only installed some information about the package, but nothing of the package itself. That was the reason why it showed up in pip freeze, but failed to import.
my setup now looks like this
setup(
    name='package name',
    version=__version__,
    description='package description',
    long_description=readme,
    author='my name',
    author_email='my mail',
    url='https://link_to_github_site.com',
    packages=find_packages(),
    license=license
)


text:
Q: Enforce rails to close image_tag I'm rendering an image_tag in a html.erb page, but the  tag is not closed. I'm getting
 instead of
The code looks like <%= image_tag( 'my_src.png') %>
Is there a way to enforce rails to close it?

A: Rails (both 3 and 4) closes the img tag by default. You must be doing something wrong. Anyway, you can use below method to generate img tag if image_tag was not working properly.
tag("img", {:src => "my_src.png"}, false)


text:
Q: When i try to name my array i get an error but if i don't name it its fine for some reason I am trying to use json to hold a simple array of customers and I want to be able to loop through it later. My problem is when I give the array a name i.e. "var customs" it throws an error and says "Expected a JSON object, array or literal" however when there is no name it's fine.
So something like this is fine:
[
  {
    "id":1,
    "name":"John",
    "address":"210 downing street",
    "phone":1158765309, "email":"Customer1@gmail.com",
    "BD":"12121990"
  }
]

and something like this is throwing an error
var Customer = [
  {
    "id":1,
    "name":"John",
    "address":"210 downing street",
    "phone":1158765309, "email":"Customer1@gmail.com",
    "BD":"12121990"
  }
]

What I've gathered from the documentation and W3 this should be fine but I'm new to json so any help to understand what's going wrong is appreciated, thanks.

A: From what I know about JSON, you cannot name the root element. The root array or object should be unnamed. Also, var or = do not exist in JSON syntax. You are probably trying to do something like this.
{
    "Customers": [
        {
        "id":1,
        "name":"John",
        "address":"210 downing street",
        "phone":1158765309, "email":"Customer1@gmail.com",
        "BD":"12121990"
         }
    ]
}


text:
Q: Is 0.4 GHz of extra processor speed worth €300? (about $430) I'm planning on buying a new macbook pro 13inch and I've got the choice between a 2.3ghz intel core i5 or an 2.7ghz intel core i7 for an extra €300 (= $430).
Can someone explain me what the difference is between i5 and i7? Would it be worth it to updgrade (eg will the performance be better)?
I would mainly use the laptop for matlab simulations (and other simple 3D simulations) and data processing. Some of these calculation are highly recursive and take a long time (fractal computation etc) on my current machine.

A: The two processors in question are the i5-2415M and the i7-2620M. The nitty-gritty tech-spec details can be compared here.
The main difference, besides clock speed, is that the i7 has a bigger cache and includes Intel vPro Technology which theoretically provides faster AES decryption and other magical buzzwords.
Of course, what you really want are benchmarks, and then decide if the 3 seconds you save on a one minute photoshop action is worth three hundred Euros.

A: The speed differences aren't very important -- the big difference is that the i7 had Intel VT-D technology, which improves VM IO performance, especially if you use multiple VMs simultaneously.
If you see alot of work with VMs in your future and have the money, go for it. Otherwise, the i5 is more than adequate.
The i7 also has hardware AES acceleration.

A: There is no simple answer. IMHO, the question is not about 0.4 GHz. (BTW, it is 17% above 2.3).
The real questions are:

*

*do you have external USB or any other backup solution?

*

*no - consider buying an external HDD first!

*yes, I have - next question :)

*have you already max. memory in your config?

*

*no - consider investing into more memory first

*yes, already max. memory - go to the next question

*is there a config with better graphics performance?

*

*yes - consider it first

*no - next question

*are you a heavy emulated Windows user (Parallels, VMware, VirtualBox etc)?

*

*yes, go for the 2.7

*no - next

*do you need every millisecond of power (because of, for example, gaming, video editing, etc.)?

*

*yes - buy the high-end one

*no - next question

*are you a bit paranoid (meaning, planning to use the FileVault encrypting for your $HOME folder)?

*

*yes - buy the high-end one

*no - next

*how often are you upgrading your Mac?

*

*every 18 months (one generation) - don't buy the high-end one, because usually they are a bit overpriced

*every 2 years or more? - buy the high-end

misc. ;)

*

*do you already own an iPad?

*

*no?! - consider saving another 300 euros on notebook and buy an iPad - trust me, it is much better for browsing in the bed... ;)

*is your girlfriend a technical geek?

*

*yes - the high-end is a MUST! :)

*no, bring her to somewhere for 300 EUR :)

misc 2 :)

*

*Have iPad, no girlfriend - and have you decided to save 300 euros based on this answer? Consider sending me 50% ;) :)

A: To keep it for "human beings":
i7 is better for video editing.
If you do not plan to make it everyday the i5 will make you happy.


text:
Q: activating a delete button after being created in jquery I've been trying to activate a delete button I created using jQuery
I have tried moving the code inside and out of the $(document).text();
I have tried targeting a class on the created button
I am not even getting an error from in my console.
What am I doing wrong?
var day = '';
var time = '';
var task = '';

$(document).text(function() {
  $("#saveButton").on("click", function() {
    //Save day, time & task to footer.
    day = $("#day").val();
    time = $("#time").val();
    task = $("#task").val();
    $("#inputData").append("
" + day +
      " | " + time + " | " + task +
      " | " + "<button class='btn btn-success edit'>Edit</button>" +
      " | " + "<button class='btn btn-danger delete'>Delete</button>
" + "
");
  });
});
$(".delete").on("click", function() {
  day = $("#day").empty();
  time = $("#time").empty();
  task = $("#task").empty();
});

A: From what I see, you just need to move the $(".delete").on("click", ...) inside the $("#saveButton").on("click", ...) handler (after you append the new elements to  #inputData), otherwise it will fire at page load (when your .delete button does not yest exist).

$("#saveButton").on("click", function () {
    //Save day, time & task to footer.
    day = $("#day").val();
    time = $("#time").val();
    task = $("#task").val();
    // append the buttons to the dom...
    $("#inputData").append("
" + day +
        " | " + time + " | " + task +
        " | " + "<button class='btn btn-success edit'>Edit</button>"
        + " | " + "<button class='btn btn-danger delete'>Delete</button>
" + "
");
    // ...then add the click handler to the new button
    $(".delete").on("click", function() {
       day =  $("#day").empty();
        time = $("#time").empty();
        task = $("#task").empty();
    });
});

Suggestion: if you don't want to gat lost with this scenario, you can also add your buttons in the beginning, with a CSS class that hides them, then just show them.


text:
Q: How to better performance In one of my interviews I was asked a vague question, I'm still not sure of the answer. We have a client and a server they are placed apart. The network that connects them has high latency, which is dominating the performance. How can we improve the performance. Note that we can't change the network's topology. I was thinking of caching, breaking the request to multiple smaller requests and opening multiple connections with the server. Any ideas?
Please note that the question description is vague and I wasn't supplied with more information about the situation.
Clarified question: How should the client-server communication be designed in order to get the best performance on a network that has big latency?

A: If high latency is screwing up performance, I'd do the exact opposite of what you're suggesting: find ways to combine multiple requests into a single request.
Let's say latency is 1 second, and you need to process 100 items, and the actual processing time is 0.01 seconds per item.
100 requests
============
Processing time = 0.01 * 100 =   1 second
Latency         = 1 * 100    = 100 seconds
Total time                   = 101 seconds

But if you can find a way to send two items in a single request:
50 requests
============
Processing time = 0.01 * 100 =  1 second
Latency         = 1 * 50     = 50 seconds
Total time                   = 51 seconds

Congratulations! You just cut the runtime for this batch in half.  Or, if you can find a way to send all 100 items in a single request:
1 request
============
Processing time = 0.01 * 100 = 1 second
Latency         = 1 * 1      = 1 second
Total time                   = 2 seconds

As a few commenters have noted, this only makes sense if the problem actually is latency, and not other network-related issues.  But since that's what you were asked about, this is the right way to handle it.

A: A few ideas that come to mind:

*

*Compression - is the data being sent back and forth compressed to make it as small as possible?

*Caching - could there be caches set up on the client to try to make things appear faster?  Could the system be set up so the client can operate disconnected from the server for a time?

*Network connectivity - While you can't change the topology, it may be worth identifying if there is something else here that could be changed?
While it is an open question, there is something to be said for what is in this client/server system. Are there database calls?  Is there synchronization to be set up?  Are there alternative architectures that may work better?

The question then becomes how much can compression affect things.  If the compression can mean that 100th or 1000th as much data has to be sent on the wire, I'd think that could be a factor as sending so much less may change things.  The issue with the question is that there are many unknowns.

A: Either load more data up front so you dont need to go back again until there's an update.
Use a local data store and sync when appropriate if it's mostly local data
Make lots of targeting small requests, small data going across the wire
and compression.
I probably would've thought of a funny answer... personality goes a long way.
"I'll just use my iPhone, i've got unlimited data and these 4g speeds are GREAT!"

A: Latency and bandwidth are two different things; high latency means there's a time overhead in sending messages back and forth, while low bandwidth means that the pipeline has a limit restricting synchronous data transfer. Both of these can mean it will take a while to get data, but for different reasons.
The solution for high latency if bandwidth is not an issue is to use larger requests for data; as much as you know you'll need, to minimize the additive impact that the overhead delay will have. The solution for low bandwidth if latency is not an issue is to use smaller requests for data, as little as you can get away with at one time, to reduce the delay that completely retrieving a large dataset can add. In addition, for both cases, you should work as asynchronously as possible, so that you can give the user feedback while the data pull is occurring. Caching is an option if the data is relatively static and is not sensitive (i.e. anyone else who could get into the system could see exactly the same data; stock ticker = cache, bank account balances = don't cache).

A: On the network with big latency, at first place you have to organize you protocols asynchronously. That means that you have to try to work without waiting for the response of the server.
You have to send the requests and to not wait for response. Then you have to organize separate thread or something that to process the responses when they come.
This way you will use the whole speed of the network and will get the respective responses only delayer in time with double the latency time.
Of course, it is possible only if the requests does not depends on each other and this is your task to design such workflow of the application.


text:
Q: Fails to generate Insert,Update,Delete methods on the client-side in ria services I've added insert/update methods to the domain service class.
They start with the appropriate words Insert/Update and are marked with the correspondent attributes.
Yet, they fail to get generated at the client-side so they are unavailable
from the domain context.
Is it a bug, a known by-design feature, or am I missing something?
Thanks in advance

A: These methods are not exposed on the client side. They are used when SubmitChanges() is called to insert, update and delete entities in the entity collection. You can add and update entities in the entity collection and they will be marked as changed or added. Then when SubmitChanges() is called, your server side code will be used.
I found this article helpful:
How SubmitChanges works in .NET RIA Servies


text:
Q: Error during GENERAL_REQUEST_ENTITY for POST request causes ASP .NET session state to never get unlocked (Cross posting from Server Fault where I wasn't getting any traction):
I have been trying to chase down the root cause of a condition where ASP .NET session state remains locked after a web request has been terminated due to an unexpected error. We use the SQL Server session state provider for session because we have several servers in a web farm. This issue first presented itself in the form of many requests getting stuck on the 'AcquireRequestState' event of their lifecycle for no apparent reason. I was able to finding corresponding entries for these requests in the session state database in SQL server that were all locked (column Locked = 1). I was also able to correlate these requests to entries in the IIS log with HTTP status codes of 500 (with a sub status of 0). These findings lead me to believe that, in some cases, a request was erroring out but was NOT releasing its lock on session state like it should.
I enabled Failed Request Tracing in IIS for the website in question for status code 500 with all available providers selected each with the 'Verbose' setting for verbosity. I've since gathered several failed traces that have caused permanently locked ASP .NET sessions. They all share the same characteristics:

*

*They are all 'POST' requests where the browser is posting data to be processed/saved.

*They all have events indicating that the 'Session' module was invoked during the REQUEST_ACQUIRE_STATE event. At this point the request would have marked the row in the session state database as being "locked". This is normal and expected.

*They all have GENERAL_READ_ENTITY_START, GENERAL_READ_ENTITY_END, and GENERAL_REQUEST_ENTITY entries that appear to be reading in the data that was posted to the server as part of the request. This appears to be a buffered operation as these events get repeated over and over with each one reading in some subset of the posted data.

*At some point during the 'read entity' related events an error occurs. Some have the error code "Incorrect function. (0x80070001)" and others have "The I/O operation has been aborted because of either a thread exit or an application request. (0x800703e3)".

*Once the error has been encountered, they all jump directly to the END_REQUEST events.

The issue here is that, under normal circumstances, there should be a RELEASE_REQUEST_STATE event that will allow the Session module to release the lock it has on the session. This event is being skipped in this scenario. Just to be sure, I enabled failed request tracing for the '200' status code as well and generated several traces of successful requests that do have the RELEASE_REQUEST_STATE event being handled by the Session module.
A co-worker pointed out that you can also cause a request to skip directly to the 'END_REQUEST' event by calling HttpContext.Current.ApplicationInstance.CompleteRequest(). I tested this out and saw that using this method during a post request creates a trace very similar to the ones I've been capturing when this issue has been happening, but session does still get cleaned up properly. This lead to me to running SQL Profiler on the SQL Server database where the session is stored to trace all calls to stored procedures. When we skip directly to END_REQUEST due to calling CompleteRequest(), a call is made to update the session state (and release the lock) as expected. When we skip to END_REQUEST as a result of an error during GENERAL_REQUEST_ENTITY, the call to update or release the lock on session state is never made.
My theory at this point is that some kind of network issue is causing the 'Incorrect function' and 'I/O operation has been aborted because of either a thread exit or an application request' errors, but I don't understand why this seems to be causing the request handling to skip over the releasing the lock on session state. If the request went through REQUEST_ACQUIRE_STATE it seems like it should also release the lock at some point toward the end of the request as well. I'm loathe to say that this is a bug in IIS or ASP .NET, but it certainly appears that way to me at this point.
Are there any known conditions under which errors will lead to a session state lock not being released?

A: As it turns out, this was related to this question: ManagedPipelineHandler for an AJAX POST crashes if an IE9 user navigates away from a page while that call was in progress
The workaround specified in the accepted answer on that question does work, but Microsoft has also since released a hotfix (not yet publicly available as of this writing) that patches the session handling logic to avoid the issue all together.


text:
Q: What is the x variable used for in the example commands below In this post: Count files and directories using shell script, DogBane gave this reply on December 5, 2012:
FILECOUNT="$(find . -type f -maxdepth 1 -printf x | wc -c)"
DIRCOUNT="$(find . -type d -maxdepth 1 -printf x | wc -c)"

Can anyone please tell me what the x after -printf means or is used for?
Thank you.

A: -printf x will simply print one x for each match, with no new-line or anything else (esp. not the filename).
These find commands just print one character for each file (or directory) found, and then count the number of characters (wc -c).


text: Q: Parent level does not display users with 'limited access' SharePoint 2013 - I've granted a user permission to a specific folder within a library.  When I look at the permissions of that library, I do not see that user having 'limited access'.  They are able to access that folder navigating through the library but owners cannot see who might have 'limited access' within that library.  How do I get the 'limited access' users to display in the permissions list?


text:
Q: query inbound / outbound IPv4 packet count statistics of network card programatically in c# I want to get statistics about sent and received packet counts (IP level :  including TCP, UDP, etc) of a network card.
How can I query that information from windows?

A: WMI.
Not easy to use from C#, but possible.
Documentation for the needed class is at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_perfformatteddata_tcpip_networkinterface.asp

A: First you have
using System.Net.NetworkInformation;

Next you have:
var iFaceArr = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface iface = iFaceArr[0];
IPv4InterfaceStatistics iFaceStats = iface.GetIPv4Statistics();

Then you have these variables:
iFaceStats.UnicastPacketsReceived;
iFaceStats.UnicastPacketsSent;
iFaceStats.NonUnicastPacketsReceived;
iFaceStats.NonUnicastPacketsSent;

Reference

A: You can take a look at Pcap.Net.

Getting the list of Live Devices on the local host.
Reading packets from Live Devices (Network Devices) and Offline Devices (Files) using the different WinPcap methods.
Receiving statistics on the entire capture.
Receiving statistics of packets instead of the full packets.
Using different sampling methods.
Applying Berkley Packet Filters.
Sending packets to Live Devices directly or using WinPcap's send queues.
Dumping packets to Pcap files.
Using Enumerables to receive packets (and LINQ).

Note that winpcap driver will have to be installed on your system.


text:
Q: Error getting sendmail to properly send emails from AWS EC2 server (domain of server address does not exist) I'm having trouble getting sendmail to send out emails from my AWS EC2 machine.
I'm using the following command to send an email:
sendmail -vt < mail.txt

The mail.txt file has the following content (edited for security):
To: locksleyu@yahoo.com
Subject: Put a subject here
From: to_whoever@example.org

Message body

When I run sendmail it looks like things are working:
>>> MAIL From:<ec2-user@XXX.us-west-2.compute.internal> SIZE=128
250 2.1.0 <ec2-user@XXX.us-west-2.compute.internal>... Sender ok
>>> RCPT To:<locksleyu@yahoo.com>
>>> DATA
250 2.1.5 <locksleyu@yahoo.com>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 s0FLLsxw009758 Message accepted for delivery
locksleyu@yahoo.com... Sent (s0FLLsxw009758 Message accepted for delivery)

However I never get the email on my yahoo account. Next I checked /var/log/messages and it said I have new mail in "/var/spool/mail/ec2-user". Here is what I saw in that file:
 ----- The following addresses had permanent fatal errors -----
 <locksleyu@yahoo.com>
 (reason: 553 #5.1.8 Domain of sender address <ec2-user@XXX.us-west-2.compute.internal> does not exist)

 ----- Transcript of session follows -----
... while talking to smtp02.yahoo.com.:
>>> MAIL From:<ec2-user@XXX.us-west-2.compute.internal> SIZE=669
<<< 553 #5.1.8 Domain of sender address <ec2-user@XXX.us-west-2.compute.internal> does not exist
501 5.6.0 Data format error

Can someone tell me what configuration is needed to make this work? The XXX above is my ip-XXX-YYY-ZZZ-AAA address which corresponds to my EC2 machine.
I did some searching around for solutions but none of those I found have worked for me so far.

A: Large swaths of the EC2 address space are blacklisted by several email providers. If you need to send email from your instance, you'll either need to relay out through a non-EC2 host or else use AWS's SES service to send email.
Personally, I use SES, as it's very easy to integrate with your MTA, and prices are very low (or free) for all but the largest email volumes.

A:  ----- Transcript of session follows -----
... while talking to smtp02.yahoo.com.:
>>> MAIL From:<ec2-user@XXX.us-west-2.compute.internal> SIZE=669
<<< 553 #5.1.8 Domain of sender address <ec2-user@XXX.us-west-2.compute.internal> does not exist

Explicitly set envelope sender address using sendmail -f command line options
OR
Make your sendmail use "this host email name" ($j) with public MX or A DNS records.
https://askubuntu.com/questions/9540/how-do-i-change-the-computer-name
OR
Make your sendmail masquearde as another host for email purposes
https://www.sendmail.com/sm/open_source/docs/m4/masquerading.html


text:
Q: Set word document page margins through java I have created a file by using Java where I want to change page margins but I can't
Here is my code:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();

paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setNumID(BigInteger.ONE);

run.setFontSize(18);

run.setText("Test");

    try{
        FileOutputStream output = new FileOutputStream("C://WordDocument.docx");
        document.write(output);

        output.close();

    } catch (Exception e){
        e.printStackTrace();
    }

What I want to do is something like document.setMarginLeft( Left_Margin ); and document.setMarginRight( Right_Margin );
Thanks in advance

A: I think he/she meant for ooxml-schemas library and rest dependencies.

A: you need to get the body of the document and adding a Section, then adding a CTPageMar, this object proovide methods for setting margins for the section you just created.
this is actually working for me,
values are large i suppose 10000 is the total width of a page but i'm not sure about it, so find your own desidered values :)
    XWPFDocument doc = new XWPFDocument();
    CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
    CTPageMar pageMar = sectPr.addNewPgMar();
    pageMar.setLeft(BigInteger.valueOf(1500L));
    pageMar.setRight(BigInteger.valueOf(1500L));
    pageMar.setTop(BigInteger.valueOf(2000L));
    pageMar.setBottom(BigInteger.valueOf(1000L));

enjoy


text:
Q: Multiple raw_inputs #Print out the menu
print """
###############################################
# 1 - Introduction.                           #
# 2 - Base.                                   #
# 3 - Contact.                                #
###############################################"""

#Get the user's choice
choice = raw_input("")

#Work with choice
print choice
if choice == 1:
    print "# Welcome to xbrEra's first application!      #"
elif choice == 2:
    print "# This application was built in Python 7.2.1.  #"
elif choice == 3:
    print "# Contact me at Blackriver.era@hotmail.com     #"
else:
    print "# Invalid choice!                              #"

That is my code. My problem is that after the first input has been completed, they next inputs will have ">>> " as a prefix. How do I change this, and also I keep getting "Invalid choice!" in the current code. Please help, thank you!

A:
I keep getting "Invalid choice!" in the current code

raw_input() returns string in python 2.7, so you need to compare as
choice == "1"

or you may try with input() instead of raw_input(), which evaluate input as numbers.
or you could parse to integer with int(raw_input()) as J.F. Sebastian pointed out. non-integer input could cause errors, so wrap it with try: except: block like
try:
  choice = int(raw_input(), 10)
except ValueError:
  choice = None

ps: ", 10" is for base 10, input could be zero padded like 010, which could take input as octal numbers

A: #Print out the menu

ch = """###############################################
# 1 - Introduction.                           #
# 2 - Base.                                   #
# 3 - Contact.                                #
###############################################

  Enter your choice : """

choice = raw_input(ch)
warn = "\n  You must enter 1 or 2 or 3.\n"+\
     "  Enter your choice : "
while choice not in ('1','2','3'):
    choice = raw_input(warn)

print ("# Welcome to xbrEra's first application!      #",
       "# This application was built in Python 7.2.1.  #",
       "# Contact me at Blackriver.era@hotmail.com     #")[int(choice)-1]

A: I think you need to code your new lines like this '\n''You must enter 1, 2, or 3.''\n'


text:
Q: Idiomatic `obj.value = f(obj)` in Ramda? R.evolve lets us replace object properties with the result of a function applied to that property's current value:
R.evolve({ count: R.inc }, { count: 1 })
   == { count: 2 }

But I frequently find I want to add a property calculated from multiple properties of input object:
assocFruitTotal({ appleCount: 5, orangeCount: 3 })
  == { appleCount: 5, orangeCount: 3, fruitCount: 8 }

I came up with my own simple utility function:
const assocDerived = R.curry(
   (name, f, obj) => ({
      ...obj,
      [name]: f(obj)
   });

... and I use it a lot:
const sumFruit = R.pipe(
   R.props(['appleCount', 'orangeCount']),
   R.sum);
const assocFruitTotal = assocDerived('fruitCount', sumFruit);

But the sheer frequency with which I use this makes me wonder why it's not
native to Ramda, as so many other convenient functions are. And that makes
me wonder whether I'm missing a better idiom that achieves the outcome -- that is, building up detail in an object by adding properties based upon combinations of other properties.
Is there an idiomatic functional programming construct I should be using instead?

A: Personally I would do it this way:
const fruitCount = applySpec({fruitCount: compose(sum, values)})

fruitCount({apple: 5, orange: 3})
//=> {"fruitCount": 8}

const withFruitCount = converge(mergeRight, [identity, fruitCount]);

withFruitCount({apple: 5, orange: 3});
//=> {"apple": 5, "fruitCount": 8, "orange": 3}

If there are non-count properties to exclude from the sum, you can use pickBy:
const pickCount = pickBy(flip(includes('Count')));

pickCount({appleCount: 5, orangeCount: 3, foo: 'bar'});
//=> {"appleCount": 5, "orangeCount": 3}

A: Let's start by recognizing that obj.value = f(obj) is a mutable assignment and therefore not a functional idiom to begin with. This is imperative-style thinking at work.
Storing a computed value as a property on your object is a misstep, in most cases. If either appleCount or orangeCount changes, there's nothing there to enforce the integrity of fruitCount.
fruitCount should be a function, not a property.
const fruitCount =
  pipe
    ( props ([ 'appleCount', 'orangeCount' ])
    , sum
    )

 fruitCount ({ appleCount: 1, orangeCount: 3 }) // 4
 fruitCount ({ appleCount: 5, orangeCount: 3 }) // 8

If I had to guess, this is fake data and an example problem. In some scenarios, a computed value does make sense (memoisation is the first technique that comes to mind) but those cases make up the exception, not the rule. You say "the sheer frequency with which I use this ...", so I'd wager you do it in more areas than you should.
And as you pointed out, Ramda doesn't have a built-in for this, so this should further indicate that there are more conventional ways of solving this kind of problem.

An object-oriented programmer would assign this as a computed property -

const FruitData = function (apples = 0, oranges = 0)
{ this.apples = apples
  this.oranges = oranges
}

Object.defineProperty
  ( FruitData.prototype
  , 'fruitCount'
  , { get () { return this.apples + this.oranges } }
  )

const f =
  new FruitData (3, 4)

console .log (f.fruitCount) // 7

When writing functional style, we leave OOP concepts at the door. Start thinking in terms of functions and your problems go away -

const FruitData = (apples = 0, oranges = 0) =>
  ({ apples, oranges })

const appleCount = fd =>
  fd.apples

const orangeCount = fd =>
  fd.oranges

const fruitCount = fd =>
  appleCount (fd) + orangeCount (fd)

console .log (fruitCount (FruitData (10, 3))) // 13


text:
Q: Amazon CloudWatch Logs Insights: Aggregating logs using bin(1w) always starts on a Sunday I want to display a bar diagram where each bar represents a week starting on a Monday.
The below meta code does that except that each week starts on a Sunday.
I realize that the Query syntax only mentions time periods with m for minutes and h for hours, but it seems to work fine also using d for day and w for week (except that I cannot set the starting day).
Any idea how to make weeks starting on Mondays instead of Sundays?
fields @timestamp, @message
| fields strcontains(@message, 'the start') as start
| fields strcontains(@message, 'the result') as result
| stats sum(start) as startCalls, sum(result) as resultCalls by bin(1w) as t
| sort t asc


text:
Q: Avoiding appending of previous page parameter when clicking on jquery tabs In my webpage I am using jquery tabs.

            <?php echo lang('purchasedtickets');?>

<a href="#gifted" onclick="giftedtickets('<?php echo $userid;?>','<?php echo base_url();?>')"><?php echo lang('gifted').' '.lang('tickets');?>

<a href="#received" onclick="receivedtickets('<?php echo $userid;?>','<?php echo base_url();?>')"><?php echo lang('received').' '.lang('tickets');?>

When I click on tab2 ie, #gifted tab, the corresponding result will be fetched from an ajax call and will be set to div with id gifted. In this sections I am using Codeigniter pagination. If I click on pagination link 2 of gifted section, the URL will come like http://domain.org/project/video/tickets/2#gifted where 2 in the URL is the page number.
After this, when I click on any other tab say tab1 ie, purchased tab, then the link of page will come like http://domain.org/project/teshot/video/tickets/2#purchased (instead of http://domain.org/project/teshot/video/tickets#purchased) which is appending the url of previous section.
I want to avoid this problem. How can I solve this?
Can ayone help me?
Thanks in advance.


text:
Q: A word that can refer to an address but also for a contact in general I'm creating a database that includes so-called sites. Those sites have an address and a shipment address; the addresses include phone numbers, but the postal part is the most important.
On the other hand there are service people you can call on the cellphone. They don't necessarily have any relation to the site, in particular not with the main address or the shipment address.
To keep my database lean, I want to have three fields of the same general type: "Main Address," "Shipment Address," and "Service Guy Address."
What would be a better word in this context? I thought about "contact," but "Shipment contact" doesn't make much sense for the delivery people as they have their own database with much more extensive contact information.

A: Main Address, Shipment Address, and Service Address.  I won't even get into the whole database design issue.

A: Following up on my comment, you should probably have separate fields for each part of the address and also for the phone number, so you'd have things like, site address, site city, site state, site ZIP, site phone, all as separate rows.  Then you'd have shipping address, shipping city, etc. And finally service contact. or whatever.
If all this information is in one field it makes parsing it much more difficult, so while the database may have fewer fields, getting that information out or manipulating it in any useful way will be much more involved. But that's a question for stackoverflow maybe.

A: I'm a wee bit concerned you're trying to distill concepts too much, but if you were to go down this road, how does "Notification Address"
sound?


text:
Q: Shell function in .bashrc is not recognized I know this must be something silly but somehow I am stuck trying to create a shortcut (alias) for a shell function.
Here is my exact .bash_profile:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
alias l="ls -G"
r () {
   echo "iron_worker upload $1"
   echo "iron_worker queue $1"
}
export -f r

So I've added my function r() at the end of the file. Now when I type r in the shell, I still get error:
-bash: r: command not found

I have restarted terminal, shell window, and still no effect.
I am on Mac OS 10.8.5 if that matters.
EDIT.
After some searching found this question suggesting to use bash_profile instead of bashrc, which is now working! But ... what I get are the commands listed but not executed:

Dmitris-MacBook-Pro:~ dmitrizaitsev$ r
iron_worker upload
iron_worker queue

This the normal command execution that I expected:

Dmitris-MacBook-Pro:~ dmitrizaitsev$ iron_worker upload
Please specify code package name or path to workerfile
usage: iron_worker upload CODE_PACKAGE_NAME_OR_PATH_TO_WORKERFILE [OPTIONS]
    -n, --name NAME                  override code name
    -c CONCURRENCY,                  max number of concurrent workers for this code package
        --max-concurrency
    -r, --retries NUM_RETRIES        max number of automatic retries on task fail
    -d RETRIES_DELAY,                delay between each automatic retry
        --retries-delay
        --worker-config CONFIG_FILE  config file for worker
    -h, --host HOST                  host name, eg: www.mydomain.com
    -a, --async                      don't wait for package build
        --full-remote-build          activate full remote build
        --config CONFIG              config file
    -e, --env ENV                    environment
        --project-id PROJECT_ID      project id
Dmitris-MacBook-Pro:~ dmitrizaitsev$

Instead I am only getting the command and nothing else.
Any idea what is going on?

A: You should use, inside the same file, the line:
   export -f r

To check that this works, you must use a different shell that you have started after you sourced your .bashrc, so that it can have inherited the new function. In staler shells, this will not work.
Also, insert this in your ~/.bash_profile:
   if [ -f ~/.bashrc ]; then
       source ~/.bashrc
   fi

If you wish to run the program iron_worker, then the body of the function r should be:
   r () {
   iron_worker upload $1
   iron_worker queue $1
   }

Also, I suggest you provide the full pathname to the command iron_worker (i.e. substitute iron_worker with /path/to/iron_worker).

A: Terminal and iTerm open new shells as login shells by default, so bash reads ~/.bash_profile but not ~/.bashrc.
You can either:

*

*Use ~/.bash_profile instead of ~/.bashrc.

*Add . ~/.bashrc to ~/.bash_profile.

*Make new shells open with a non-login shell, by for example changing "Shells open with" from "Default login shell" to the command /bin/bash in Terminal.

I have done the last two. For example tmux and the shell mode in Emacs open new login shells as non-login shells by default. ~/.bash_profile is still read when I ssh to my computer.
See https://www.gnu.org/s/bash/manual/html_node/Bash-Startup-Files.html for more information.
The function keyword in your function definition is redundant by the way. function name() { :; } is identical to name() { :; } in bash. The function keyword is not defined by POSIX.


text:
Q: IllegalStateExeption when using JavaFX webEngine.print() function I've tried everything I can think of, I'm hoping someone out there might have some knowledge I don't.
I'm trying to print an HTML document loaded into a JavaFX webview control, and I keep getting an IllegalStateException violation(Even though it still prints). Originally the code was being run inside an event handler so I thought that might be the issue. I tried moving the actual print code to the FX/UI thread, into it's own thread, and even a listener.(it's currently in the listener configuration) all produce the same exceptions.
Random data points:

*

*There are always exactly 7 exceptions thrown regardless the size of
the HTML document.

*The exceptions are coming from inside the WebEngine.print() method.

I'm really hoping someone out there has an idea what might be wrong.
Thanks,
TR
Here's the code.
      public class PostView {
        @FXML protected WebView webviewer;
        protected BooleanProperty printReq = new SimpleBooleanProperty(false);
        protected WebEngine engine;

      @FXML
      public void initialize() {
         engine = webviewer.getEngine();

         printReq.addListener(new ChangeListener<Boolean>() {
              @Override
              public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                  // Only if completed
                  if (newValue) {
                    if (Security.okayToPrint()) {
                      PrinterJob job = PrinterJob.createPrinterJob(Printer.getDefaultPrinter());
                      if (job != null) {
                        if (job.showPrintDialog(Info.windowHandle)) {
                          Squirt.out(5, "PostView - User wants to print a page!!!!");
                          engine.print(job); // <- Exceptions squirt out here.
                          job.endJob();
                        }
                      } else {
                        Log.warning("Could not create a print job");
                        final Shout shout = new Shout(AlertType.ERROR);
                        shout.setContentText(Info.lexicon.shipLogPrintErrorMsg);
                        shout.showAndWait();
                      }
                    }
                  }
                  printReq.set(false);
              }
            });
        }
    }

Here's the Exception trace:
***java.lang.IllegalStateException:** the method should not be called in this context
    at com.sun.javafx.webkit.theme.RenderThemeImpl.ensureNotDefault(RenderThemeImpl.java:250)
    at com.sun.javafx.webkit.theme.RenderThemeImpl.createWidget(RenderThemeImpl.java:263)
    at com.sun.webkit.WebPage.twkPrint(Native Method)
    at com.sun.webkit.WebPage.lambda$print$46(WebPage.java:1851)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:204)
    at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
    at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
    at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:590)
    at com.sun.prism.j2d.print.J2DPrinterJob$J2DPageable.implPrintPage(J2DPrinterJob.java:1146)
    at com.sun.prism.j2d.print.J2DPrinterJob$J2DPageable.access$500(J2DPrinterJob.java:972)
    at com.sun.prism.j2d.print.J2DPrinterJob.print(J2DPrinterJob.java:797)
    at javafx.print.PrinterJob.printPage(PrinterJob.java:398)
    at javafx.print.PrinterJob.printPage(PrinterJob.java:414)
    at javafx.scene.web.WebEngine.print(WebEngine.java:1649)
    at com.trmartin.controls.PostView$1.changed(PostView.java:135)
    at com.trmartin.controls.PostView$1.changed(PostView.java:125)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.BooleanPropertyBase.fireValueChangedEvent(BooleanPropertyBase.java:103)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:110)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at com.trmartin.controls.PostView$PrintRequest.handle(PostView.java:611)
    at com.trmartin.controls.PostView$PrintRequest.handle(PostView.java:606)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at com.trmartin.controls.TheMenu.menuPrint(TheMenu.java:1049)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
    at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Unknown Source)*

A: I have same trouble. My solutions were:

*

*With java8 version 121, it works without exceptions.

*With java8 version 172 and code below, it works anyway after a lot of exceptions.
try {
    engine.print(job);
} finally {
    job.endJob();
}
This page may give you some ideas:
https://bugs.java.com/view_bug.do?bug_id=8097381


text:
Q: How to remove Resharper warning in Debug.WriteLine(string.Format("Test Data Value: {0}", data))? I want to remove the warning in the following code that will be warned by Resharper as "Redundant 'string.Format' call".
Debug.WriteLine(string.Format("Test Data Value: {0}", data));

I think everything with Debug class will not be included in release Mode by compiler and Debug will be used only in Debug mode.
So why Resharper cares about string.Format if it will be removed anyway.
But this code will work even though in Release mode both will be warned.
string message = string.Format("Test Data Value: {0}", data);
Debug.WriteLine(message);

The code above will not be warned by Resharper but message variable will become a trash in release if is not optimized.
I ask this question because there are a lot of such code and if I use "Suppress inspection" then the code will be bigger and not clean.
How to remove the warning?

A: Although you can, of course, suppress the warning - ReSharper is very flexible in terms of telling it to "shut up".
However, I'd say, ReSharper is a little helpful here. The string.Format is very redundant for the simple reason is that Debug.WriteLine has an overload which mimics the same thing:
http://msdn.microsoft.com/en-us/library/cc190153(v=vs.110).aspx
I'd suggest a better solution would be to replace your uses of Debug.WriteLine(string.Format(....)); with Debug.WriteLine("Test Data Value: {0}", data).

A: #pragma warning disable
//Your code with warnings
#pragma warning restore


text:
Q: Perspective camera coordinates to screen coordinates in libgdx perspectiveCamera = new PerspectiveCamera(90, 80, 48);
perspectiveCamera.position.set(0,0, 10f);
perspectiveCamera.lookAt(0,0,0);
perspectiveCamera.near = .01f;
perspectiveCamera.far = 300f;

My ScreenWidth x ScreenHeight are 800 x 480;
pCamera.unproject(mytouchPoint) shall suppose to give results between
x = 0 to 80
y = 0 to 48
but I m getting 0.000xyz for both x and y axis

A: Don't use such a small value for your camera's near member, it will cause floating point errors and/or z-fighting.
The width and height values you provided to PerspectiveCamera constructor, are used to calculate the aspect ratio. There is no single 2D resolution (the size of the screen-plane in world coordinates) in a 3D perspective.
You cannot simply unproject a 2D screen coordinate to a single 3D coordinate. For each 2D screen coordinate, there are an "infinite" amount of 3D coordinates possible. Therefor the unproject method of the camera will use the z-coordinate of the provided screen coordinate to decide which of those 3D coordinates to return. If z is zero, it will give the coordinate on the near-plane. If z is one, it will give the coordinate on the far-plane.
Assuming you used z=0 for myTouchPoint and given you have a very small near-plane (since you near value is very small), the unprojected value will be vary small and therefor (almost) equal to zero.
For more information, you might want to have a look at: http://blog.xoppa.com/interacting-with-3d-objects/

A: I found a way to easily do it. Its fast too.
Just create a plane at required depth z and find intersection of ray on it.
float zDepth=-10;//your decision or and object z position

public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    Ray ray = camera.getPickRay(screenX,screenY);

    Plane plane=new Plane();
    plane.set(0,0,1,0);// the xy plane with direction z facing screen

    plane.d=zDepth;//***** the depth in 3d for the coordinates

    Vector3 yourVector3Position=new Vector3();
    Intersector.intersectRayPlane(ray, plane, yourVector3Position);

}


text:
Q: Mapping a color variable in plotly bar charts I am trying to reproduce this bar chart with my dataset, which is an xts object like this:
distance <- structure(c(-0.88, 2.61, 3.31, 4.7, 7.49, 0.51, 0.51, -5.07,
0.51, -2.28, 8.89, -7.86, -10.65, -7.86, -7.86, -7.86, -7.86,
-5.07, -3.65, -1.29, 2.96, 4.15, 6.92, -2.08, 1.05, -5.51, -0.48,
-2.95, 4.24, -6.34, -8.73, -6.97, -1.62, -9.22, -11.66, -7.73,
4.7, 4.7, 6.1, 8.89, 7.49, 8.89, 6.1, 0.51, 8.89, 6.1, 8.89,
3.31, -2.28, -2.28, -2.28, -2.28, -2.28, -5.07, -29.5, -19.03,
-10.65, -16.24, -14.84, -27.41, -16.24, -32.99, -24.61, -44.16,
-35.78, -58.12, -52.54, -55.33, -49.74, -49.74, -55.33, -72.08,
-16.94, -9.26, -5.07, -10.65, -7.86, -16.24, -9.26, -19.03, -16.24,
-24.61, -30.2, -35.78, -24.61, -30.2, -38.57, -27.41, -38.57,
-58.12, -21, -11.72, -6.77, -12.43, -10.48, -18.3, -11.61, -22.85,
-18.07, -27.5, -26.07, -36.69, -32.35, -33.93, -35.27, -30.9,
-35.64, -42.99), index = structure(c(1513292400, 1516316400,
1518735600, 1521154800, 1524175200, 1529013600, 1537480800, 1545346800,
1561068000, 1576796400, 1592517600, 1608246000, 1639695600, 1671145200,
1702594800, 1734649200, 1766098800, 1797548400), tzone = "", tclass = c("POSIXct",
"POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct",
"POSIXt"), tzone = "", .Dim = c(18L, 6L), .Dimnames = list(NULL,
    c("Call Median", "Call Mean", "Call 3rd Qu.", "Put 1st Qu.",
    "Put Median", "Put Mean")), class = c("xts", "zoo"))

So I would like to group my data like this:

*

*by as.character(index(distance)) like ggplot2::diamonds$cut on x-axis;

*by using different colors according to colnames(distance) like ggplot2::diamonds$clarity;

My trial so far:
# Transpose is just because... who knows? Maybe it works
distance.t = t(distance)

as.data.frame(distance.t) %>%
  plot_ly(
    x = ~rownames(distance.t),
    y = ~as.data.frame(distance.t),
    type = "bar",
    color = ~colnames(distance.t))

Result:
Error: Column `color` must be length 1 or 18, not 6

What am I missing?

A: Plotly expects that the x and y values have the same shape or have a length of 1, i.e. they all have the same coordinates.
In the example in the documentation each value has its own x, y and color value. Your data holds the same information but not in a way which can be understood by Plotly.
You could plot the data by iterating over it and adding the bars sequentially.
p <- plot_ly(x = attr(distance, "index"))
for (i in 1:dim(distance)[2])
{
  p <- add_bars(p,
                y = as.numeric(distance[,i]),
                name = colnames(distance)[i]
                )
}


text:
Q: Theorem of a minimal polynomial vector Theorem: Minimal polynomial for a vector $v\in \text{(Complex numbers without 0 )}^n$ on a matrix A divides the minimal polynomial of a matrix A.
Above should be a theorem from linear algebra. However it does not make sense to me what it actually means.
So my question is: what does "vector" in the context above mean?
I also searched online and I could not find any similar theorem.


text:
Q: Is there a way to increase/bypass the limit for ClickOnce deployed activations attempting to load at once? I am writing a Crystal Report Viewer in Visual Studios using ClickOnce to deploy updates and install on users computers. I am using Visual Studios C# and have the application checking for updates before loading the program to ensure all users have the latest version when needed.
One thing that I did not think about and just ran into is the number of reports attempting to load at once on a machine. Some users have 10+ reports starting simultaneously when they log into our ERP. I made a batch file to start all the reports they needed but I ran into an error:

Too many deployed activations are attempting to load at once

I tried searching for an answer as to how many ClickOnce instances are allowed to load at once and I could not find the answer. It seems to be around is 8 (based on my testing) and apparently it is in place to prevent DOS attacks against the ClickOnce server. I tried waiting a few seconds in the batch file after every 5 reports or so but this is not a long term solution.
Is there a way to increase this limit or should I just open all the reports needed in a single instance from a command? Even if I go with the second option, users can still add reports to automatically open in the ERP causing this issue to arise again. So is there a way to detect how many ClickOnce instances are currently loading and wait for them to finish, allowing me to bypass this issue entirely?

A: The solution I came up with for this was to expand the command to include multiple reports so all the reports will open under the same program. That way, ClickOnce is only involved once per batch file. Each report runs in its own thread so it behaves the same as running each report as a new instance of the program.
Theoretically a user could add enough batch files to our ERPs auto launch feature to overload the system and receive the same error as before but we could just add that to the batch file once we find out.
Until I find out if there's any way around this limit, this is the best I can come up with since it seems to be happening before the program even hits main().


text:
Q: Use AJAX to GET smart_collections.json Within a Shopify store I am making several AJAX calls and only one returns a 401 Unauthorized. The AJAX url is https://{{key}}:{{password}}@stand-around-creations.myshopify.com/admin/smart_collections.json?limit=250&fields=id,title,handle,image and it returns this:
XMLHttpRequest cannot load https://stand-around-creations.myshopify.com/admin/smart_collections.json?limit=250&fields=id,title,handle,image.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://stand-around-creations.myshopify.com' is therefore not allowed access. The response had HTTP status code 401.

I am using a private app with read access only for products, variants and collections. I know this is an authentication issue but how to solve to me isnt really clear. I have never used Basic Auth, OAuth or OAuth 2 and only have a very basic understanding of the concept. I tried searching the Shopify forums for a solution but couldn't find a solution. So how can I solve this issue or what am I doing wrong?


text:
Q: C Data Structure or Core Foundation? I am working on an app that works heavily with the file system.
I have a C background and it is a habit to just use C Data Structures as much as possible.
Can anyone comment on how to decide when to use C Data Structures vs the Core Foundation data structures?
OS X 10.6.

A: It's pretty much common sense: Use Core Foundation when it provides the functionality you need. Use your own data structures when something appropriate has not been provided.

A: I think it depends a bit on the specific requirements of the application. If you end up spending too much time implementing the C data structure instead of working on the actual problem, then your best bet is to work with an already existing data structure.
Also, data structures from a good library are generally well tested and can save you a lot of debugging time.
However if, for example, you are thinking in working on a specific behavior of a red black tree algorithm in order to tackle your problem, then indeed you should better write your own version.


text:
Q: fhir patient level bulk export not working I'm trying to perform a Patient level bulk export:
"Endpoint - All Patients    Export a detailed set of FHIR resources of diverse resource types pertaining to all patients.   [fhir base]/Patient/$export
"
I have a fhir server running on a smile CDR instance loaded with some basic data with the  Synthea tool. I've generated 11 patients and more data related to it.
Resources loaded in the database are:
"AllergyIntolerance", "Bundle", "CarePlan", "CareTeam", "Claim", "Condition", "Coverage", "DiagnosticReport","DocumentReference", "Encounter", "ExplanationOfBenefit", "ImagingStudy", "Immunization", "Location", "Medication","MedicationAdministration", "MedicationRequest", "Observation", "Organization","Patient", "Practitioner","PractitionerRole","Procedure", "Provenance", "ServiceRequest"

When I request a resource export (Patient, Practitioner, Organization) the bulk export works:
http://localhost:8000/$export?_type=Organization
{
"resourceType": "Organization",
"id": "1633",
"meta": {
    "versionId": "1",
    "lastUpdated": "2021-11-12T20:42:45.627+00:00",
    "source": "#HJck1YaOzVjNjBTA",
    "profile": [
        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-organization"
    ]
},....

}
Now, the patient level export is generating a status job with no results at all. First I launch the bulk job with:
http://localhost:8000/Patient/$export
and then, I ask for the job status with the provided url:
http://localhost:8000/$export-poll-status?_jobId=4aaadbc9-fbe8-44e1-b631-9335fc1c2712
And the response is always the same, with no results at all (I can see in the logs that the job is completed).
{
    "transactionTime": "2021-12-01T19:37:46.341+00:00",
    "request": "/Patient/$export?_outputFormat=application%2Ffhir%2Bndjson"
}

By reading the documentation I think the issue is related to the bulk export permissions. In FHIR_OP_INITIATE_BULK_DATA_EXPORT, I've configured "Patient" as permission, but no matter what word I wrote there, the behavior is the same (I mean, the resource export works, but not the patient level export).
I would like to understand what I should configure on the FHIR_OP_INITIATE_BULK_DATA_EXPORT permission and on the other ones (FHIR_OP_INITIATE_BULK_DATA_EXPORT_GROUP, FHIR_OP_INITIATE_BULK_DATA_EXPORT_PATIENT, FHIR_OP_INITIATE_BULK_DATA_EXPORT_SYSTEM) to allow a user to download everything, like a super user.


text:
Q: effect on dlls when moving to 64 bit machine We've had a 32 bit terminal services computer running some Windows services we constructed using .NET.  Recently we moved everything to a 64 bit machine.  Most things work.  However, we are getting grief from a dll for apachefop.net.
In particular we get the following error

Error: Plugin Transcript Service
  Execution Failed: Could not load file
  or assembly 'apachefop.net,
  Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=null' or one of its
  dependencies. An attempt was made to
  load a program with an incorrect
  format.

I'm guessing that this is because it isn't meant to work on a 64 bit machine.  Any suggestions about how to rectify this type of situation?

A: The problems seems to be caused by the fact that your assembly has been compiled with the anycpu setting. In this mode, when run on a 64 bits machine, your process automatically becomes a 64 bits process while your native references don't... And as it is not possible to load 32bits libraries from a 64 bits process you're running into troubles.
To quickly diagnose if it is the case you can use the corflags.exe which is part of the .net framework :
corflags.exe pathtoyourdotnetprogram /32bit+
Then run your program. If your soft is running well, then you should change the anycpu settings in your project to force the compiler to compile to a 32bits assembly.


text:
Q: LUA: Looking for a specific table by its variable I'm currently starting work on a text adventure game in Lua--no addons, just pure Lua for my first project. In essence, here is my problem; I'm trying to find out how I can do a "reverse lookup" of a table using one of its variables. Here's an example of what I've tried to do:
print("What are you trying to take?")
bag = {}
gold = {name="Gold",ap=3}
x = io.read("*l")
if x == "Gold" then
     table.insert(bag,gold)
     print("You took the " .. gold.name .. ".")
end

Obviously, writing a line like this with every single object in the game would be very... exhausting--especially since I think I'll be able to use this solution for not just taking items but movement from room to room using a reverse lookup with each room's (x,y) coordinates. Anyone have any ideas on how to make a more flexible system that can find a table by the player typing in one of its variables? Thanks in advance!
-blockchainporter

A: This doesn't directly answer your question as you asked it, but I think it would serve the purpose of what you are trying to do.  I create a table called 'loot' which can hold many objects, and the player can place any of these in their 'bag' by typing the name.
bag = {}
loot = {
    {name="Gold", qty=3},
    {name="Axe", qty=1},
}

print("What are you trying to take?")
x = io.read("*l")
i = 1
while loot[i] do
    if (x == loot[i].name) then
        table.insert(bag, table.remove(loot,i))
    else
        i = i + 1
    end
end

For bonus points, you could check 'bag' to see if the player has some of that item already and then just update the quantity...
while loot[i] do
    if (x == loot[i].name) then
        j, found = 1, nil
        while bag[j] do
            if (x == bag[j].name) then
                found = true
                bag[j].qty = bag[j].qty + loot[i].qty
                table.remove(loot,i)
            end
            j = j + 1
        end
        if (not found) then
            table.insert(bag, table.remove(loot,i))
        end
    else
        i = i + 1
    end
end

Again, this isn't a 'reverse lookup' solution like you asked for... but I think it is closer to what you are trying to do by letting a user choose to loot something.
My disclaimer is that I don't use IO functions in my own lua usage, so I have to assume that your x = io.read("*l") is correct.

PS. If you only ever want objects to have a name and qty, and never any other properties (like condition, enchantment, or whatever) then you could also simplify my solution by using key/val pairs:
bag = {}
loot = { ["Gold"] = 3, ["Axe"] = 1 }

print("What are you trying to take?")
x = io.read("*l")
for name, qty in pairs(loot) do
    if x == name then
        bag.name = (bag.name or 0) + qty
        loot.name = nil
    end
end

A: I have a few notes to start before I specifically address your question. (I just want to do this before I forget, so please bear with me!)
I recommend printing to the terminal using stderr instead of stdout--the Lua function print uses the latter. When I am writing a Lua script, I often create a C-style function called eprintf to print formatted output to stderr. I implement it like this:
local function eprintf(fmt, ...)
    io.stderr:write(string.format(fmt, ...))
    return
end

Just be aware that, unlike print, this function does not automatically append a newline character to the output string; to do so, remember to put \n at the end of your fmt string.
Next, it may be useful to define a helper function that calls io.read("*l") to get an entire line of input. In writing some example code to help answer your question, I called my function getline--like the C++ function that has similar behavior--and defined it like this:
local function getline()
    local read = tostring(io.read("*l"))
    return read
end

If I correctly understand what it is you are trying to do, the player will have an inventory--which you have called bag--and he can put items into it by entering item names into stdin. So, for instance, if the player found a treasure chest with gold, a sword, and a potion in it and he wanted to take the gold, he would type Gold into stdin and it would be placed in his inventory.
Based on what you have so far, it looks like you are using Lua tables to create these items: each table has a name index and another called ap; and, if a player's text input matches an item's name, the player picks that up item.
I would recommend creating an Item class, which you could abstract nicely by placing it in its own script and then loading it as needed with require. This is a very basic Item class module I wrote:
----------------
-- Item class --
----------------
local Item = {__name = "Item"}
Item.__metatable = "metatable"
Item.__index = Item

-- __newindex metamethod.
function Item.__newindex(self, k, v)
    local err = string.format(
        "type `Item` does not have member `%s`",
        tostring(k)
    )
    return error(err, 2)
end

-- Item constructor
function Item.new(name_in, ap_in)
    assert((name_in ~= nil) and (ap_in ~= nil))
    local self = {
        name = name_in,
        ap = ap_in
    }
    return setmetatable(self, Item)
end

return Item

From there, I wrote a main driver to encapsulate some of the behavior you described in your question. (Yes, I know my Lua code looks more like C.)
#!/usr/bin/lua

-------------
-- Modules --
-------------
local Item = assert(require("Item"))

local function eprintf(fmt, ...)
    io.stderr:write(string.format(fmt, ...))
    return
end

local function printf(fmt, ...)
    io.stdout:write(string.format(fmt, ...))
    return
end

local function getline()
    local read = tostring(io.read("*l"))
    return read
end

local function main(argc, argv)
    local gold = Item.new("Gold", 3)
    printf("gold.name = %s\ngold.ap = %i\n", gold.name, gold.ap)
    return 0
end
main(#arg, arg)

Now, as for the reverse search which you described, at this point all you should have to do is check the user's input against an Item's name. Here it is in the main function:
local function main(argc, argv)
    local gold = Item.new("Gold", 3)
    local bag = {}
    eprintf("What are you trying to take? ")
    local input = getline()
    if (input == gold.name) then
        table.insert(bag, gold)
        eprintf("You took the %s.\n", gold.name)
    else
        eprintf("Unrecognized item `%s`.\n", input)
    end
    return 0
end

I hope this helps!


text:
Q: How to sort a user Created List Collection in C# I wish to sort the collection List<UserClass>
on the basis of one of the property among various of that UserClass which is User Defined.
Is it valid
List<Function> objFunctionsList = new List<Function>();

// populating data in objFunctionsList

objFunctionsList = objFunctionsList.OrderBy(x => x.Name).ToList();

A: Just use the linq extension method orderby
var sorted=list.OrderBy(x=>x.MyProperty);

If you need a list as a result then add  ToList() eg
var sortedList=list.OrderBy(x=>x.MyProperty).ToList();

Alternatively you could use this Extension class
public static class SortExtension {

  public static Comparison<T> GetComparer<T, TP>(Expression<Func<T, IComparable<TP>>> propertyExpression) {

    if (propertyExpression == null) throw new ArgumentNullException();
    var member = ((propertyExpression.Body is UnaryExpression) ? ((UnaryExpression)propertyExpression.Body).Operand : propertyExpression.Body) as MemberExpression;
    if (member == null) throw new ArgumentException();
    var parameterA = Expression.Parameter(typeof(T), "a");
    var parameterB = Expression.Parameter(typeof(T), "b");
    var nullExpr = Expression.Constant(null);
    var valueA = Expression.Property(parameterA, member.Member.Name);
    var valueB = Expression.Property(parameterB, member.Member.Name);
    var compare = Expression.Call(valueA, typeof(TP).GetMethod("CompareTo", new[] { typeof(TP) }), valueB);
    var checkBPropNull = Expression.Condition(Expression.Equal(valueB, nullExpr), Expression.Constant(0), Expression.Constant(-1));
    var checkAPropertyNull = Expression.Condition(Expression.Equal(valueA, nullExpr), checkBPropNull, compare);
    var checkBNullANot = Expression.Condition(Expression.Equal(parameterB, nullExpr), Expression.Constant(1), checkAPropertyNull);
    var checkBNullANull = Expression.Condition(Expression.Equal(parameterB, nullExpr), Expression.Constant(0), Expression.Constant(-1));
    var checkANull = Expression.Condition(Expression.Equal(parameterA, nullExpr), checkBNullANull, checkBNullANot);
    return (a, b) => Expression.Lambda<Func<T, T, int>>(checkANull, parameterA, parameterB).Compile()(a, b);
  }

  public static void SortBy<T, TP>(this List<T> source, Expression<Func<T, IComparable<TP>>> propertyExpression) {
    if (source == null) throw new ArgumentNullException();
    source.Sort(GetComparer(propertyExpression));
  }
}

Then you can just do
list.SortBy(x=>x.MyProperty);
The Expression building produces a comparitor that is functionally equivalent to
list.Sort((a,b) => {
  if (a == null) return (b==null) ? 0 :-1;
  if (b==null) return 1;
  if (a.MyProperty == null) return (b.MyProperty==null) ? 0 : -1;
  return a.T1.CompareTo(b.T1);
});

A: users.Sort((u1, u2) => {
    return u1.Age.CompareTo(u2.Age);
});

This will sort by Age for example.

A: If your list is list, then:
list.Sort((a, b) => {
                       if (a==null) return (b==null) ? 0 : -1;
                       if (b==null) return 1;
                       if (a.Property==null) return (b.Property==null) ? 0 : -1;
                       return a.Property.CompareTo(b.Property);
                     });


text:
Q: Child calling parent's method without calling parent's __init__ in python I have a program that have a gui in PyQt in the main thread. It communicates to a photo-detector and gets power readings in another thread, which sends a signal to the main thread to update the gui's power value.
Now I want to use a motor to automatically align my optical fiber, getting feedback from the photo-detector.
So I created a class that controls the motors, but I have to somehow pass the photo-detector readings to that class. First, I tried to access parent's power variable but it didn't work.
Then I created a method in my gui to return the variable's value and tried to access it from the motor class. I got a problem saying that I couldn't use parent's method without using its __init__ first. Is there a way to bypass it? I can't call the gui __init__ again, I just want to use one of its methods from within the child class.
If there is an alternative way to do this, I'd be happy as well.
PS: I guess I can't give the child class the photo-detector object because it is in another thread, right?
--Edit--
The gui code is:
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    self.PDvalue = 0 #initial PD value
    self.PDState = 0 #control the PD state (on-off)
    self.PDport =  self.dialog.pm100d.itemText(self.dialog.pm100d.currentIndex()) #gets pot info

    def __init__(self):
    ... #a lot of other stuff
    self.nano = AlgoNanoMax.NanoMax('COM12') #creates the motor object
    self.nano_maxX.clicked.connect(self.NanoMaximizeX) #connect its fun to a buttom
    self.actionConnect_PM100D.triggered.connect(self.ActionConnect_PM100D) #PD buttom

    def NanoMaximizeX(self):
        self.nano.maximize_nano_x() #uses motor object function

    def ActionConnect_PM100D(self):
        if self.PDState == 0: #check if PD is on
            self.PD = PDThread(self.PDState, self.PDport) #creates thread
            self.PD.valueupdate.connect(self.PDHandler) #signal connect
            self.PD.dialogSignal.connect(self.PDdialog) #create error dialog
            self.threads = []
            self.threads.append(self.PD)
            self.PD.start() #start thread
        else:
            self.PDState = 0
            self.PD.state = 0 #stop thread
            self.startpd.setText('Start PD') #change buttom name

   def PDHandler(self, value):
       self.PDvalue = value #slot to get pow from thread

   def ReturnPow(self):
       return self.PDvalue #return pow (I tried to use this to pass to the motor class)

   def PDdialog(self):
       self.dialog.set_instrument('PM100D') #I have a dialog that says error and asks you to type the right port
       if self.dialog.exec_() ==  QtGui.QDialog.Accepted: #if Ok buttom try again
           ret = self.dialog.pm100d.itemText(self.dialog.pm100d.currentIndex()) #new port
           self.PD.port = str(ret)
           self.PD.flagWhile = False #change PD stop loop condition to try again
       else: #pressed cancel, so it gives up
           self.PD.photodetector.__del__() #delete objects
           self.PD.terminate() #stop thread
           self.PD.quit()

Now the PD class, which is in another thread but in the same file as gui:
class PDThread(QtCore.QThread):

valueupdate = QtCore.pyqtSignal(float) #creating signals
dialogSignal = QtCore.pyqtSignal() #signal in case of error
state = 1 #used to stop thread

def __init__(self, state, port):
    QtCore.QThread.__init__(self)
    self.photodetector = PM100D() #creates the PD object
    self.port = port

def run(self):
    while True:
        self.flagWhile = True #used to leave while
        try:
            self.photodetector.connect(self.port) #try to connect
        except:
            self.dialogSignal.emit() #emit error signal
            while self.flagWhile == True:
                time.sleep(0.5) #wait here until user press something in the dialog, which is in another thread
        else:
            break #leave loop when connected

    window.PDState = 1 #change state of main gui buttom (change functionality to turn off if pressed again)
    window.startpd.setText('Stop PD')   #change buttom label
    while self.state == 1:
        time.sleep(0.016)
        value = self.photodetector.get_pow() #get PD pow
        self.valueupdate.emit(value) #emit it

The AlgoNanoMax file:
import gui
from NanoMax import Nano

class NanoMax(gui.MyApp): #inheriting parent

def __init__(self, mcontroller_port):
    self.mcontroller = Nano(mcontroller_port) #mcontroller is the communication to the motor

def maximize_nano_x(self, step=0.001, spiral_number=3):
    ''' Alignment procedure with the nano motor X'''
    print 'Optimizing X'
    power = super(NanoMax, self).ReturnPow() #here I try to read from the photodetector
    xpos = self.mcontroller.initial_position_x
    position = []
    position = [[power, xpos]]
    xsign = 1
    self.mcontroller.move_relative(self.mcontroller.xaxis, (-1) * spiral_number * step)
    print 'X nano move: '+ str((-1) * spiral_number * step * 1000) + ' micrometers'
    time.sleep(4)
    power = super(NanoMax, self).ReturnPow()
    xpos += (-1) * spiral_number * step
    position.append([power, xpos])
    for _ in xrange(2*spiral_number):
        self.mcontroller.move_relative(self.mcontroller.xaxis, xsign * step)
        print 'X nano move: '+ str(xsign * step * 1000) + ' micrometers'
        time.sleep(5)
        power = super(NanoMax, self).ReturnPow()
        xpos += xsign * step
        position.append([power, xpos])
    pospower = [position[i][0] for i in xrange(len(position))]
    optimalpoint = pospower.index(max(pospower))
    x_shift = (-1) * (xpos - position[optimalpoint][1])
    print 'Maximum power: ' + str(max(pospower)) + ' dBm'
    print 'Current power: ' + str(super(NanoMax, self).ReturnPow()) + ' dBm'
    self.mcontroller.move_relative(self.mcontroller.xaxis, x_shift)

A: The __init__ for NanoMax and MyApp should call super().__init__() to ensure initialization is done for all levels (if this is Python 2, you can't use no-arg super, so it would be super(NanoMax, self).__init__() and super(MyApp, self).__init__() respectively). This assumes the PyQT was properly written with new-style classes, and correct use of super itself; you're using super in other places, so presumably at least the former is true. Using super appropriately in all classes will ensure all levels are __init__-ed once, while manually listing super classes won't work in certain inheritance patterns, or might call some __init__s multiple times or not at all.
If there is a possibility that many levels might take arguments, you should also accept *args/**kwargs and forward them to the super().__init__ call so the arguments are forwarded where then need to go.
Combining the two, your code should look like:
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MyApp, self).__init__(*args, **kwargs)
        ... rest of __init__ ...

class PDThread(QtCore.QThread):
    def __init__(self, state, port, *args, **kwargs):
        super(PDThread, self).__init__(*args, **kwargs)
        ...

class NanoMax(gui.MyApp): #inheriting parent

    def __init__(self, mcontroller_port, *args, **kwargs):
        super(NanoMax, self).__init__(*args, **kwargs)
        self.mcontroller = Nano(mcontroller_port) #mcontroller is the communication to the motor

Note: If you've overloaded methods that the super class might call in its __init__ and your overloads depend on state set in your own __init__, you'll need to set up that state before, rather than after the super().__init__(...) call. Cooperative multiple inheritance can be a pain that way. Also note that using positional arguments for anything but the lowest level class can be ugly with multiple inheritance, so it may make sense to pass all arguments by keyword, and only accept and forward **kwargs, not *args, so people don't pass positional arguments in ways that break if the inheritance hierarchy changes slightly.

A: class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    self.PDvalue = 0 #initial PD value
    self.PDState = 0 #control the PD state (on-off)

In the above code it is setting a variable outside of a function. To do this in a class don't put the self keyword in front of it. This way you can just have in the class definition
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    PDvalue = 0 #initial PD value
    PDState = 0 #control the PD state (on-off)

and in the super line
power = super(NanoMax, self).PDvalue

For example:
>>> class Hi:
  H = 5
  def __init__(self):
    self.g = 6

>>> class Bye(Hi):
  def H(self):
    print(super(Bye, self).H)

>>> e = Bye()
>>> e.H()
5
>>>


text:
Q: What to report for reliability analysis? After completing data collection on a reliability analysis where multiple examiners sampled each subject three times, which value should I report for descriptive statistics? If intra-rater reliability is much better than inter-rater reliability, should I report the intra-rater data for the descriptive statistics? One of the examiners is much more skilled and has more experience with the instrument than the other examiners.

A: You can of course report both intra-rater and inter-rater reliability. Which one is more important in a given study depends on what point you are trying to make and what threat to measurement validity you are concerned about. If you want to show that ratings did not change over time and that the influence of contextual factors that different between measurement occasions, then intra-rater reliability will be important. If you want to show that ratings did not change across raters and that the influence of rater bias did not influence your measurements, then inter-rater reliability will be important.


text:
Q: How do I get the name of the class 'a' where class 'b' is created? I want to do the same that Django does. If I have a Model Poll and a Model Choices and define an attribute Poll = ForeignKey(Poll) Poll have a field named Poll.choices_set
I have to following code:
class rel(object):
    def __init__(self,cls):
        # here I want to get the name of class c there this class is instanced.
        setattr(cls,[name_of_class_c] +"_set",cls())

class a(object):
    pass

class c(object):
    somevar = 3
    relationField = rel(a);

abc = a();
print abc.c_set.somevar

Here class a is class Poll, class c is the Choices class and class rel is the foreign key class.
Does somebody know how to achieve this?

A: If you only want to set an attribute, you can just pass the class itself as a parameter:
class rel(object):
    def __init__(self,cls, parent):
        setattr(cls,parent.__name__ +"_set",cls())
class c(object):
    somevar = 3
    relationField = rel(a, c);

Or if you just want the name:
class rel(object):
    def __init__(self,cls, name):
        setattr(cls,name+"_set",cls())
class c(object):
    somevar = 3
    relationField = rel(a, 'c');

A: Have found a dirty workaround, not perfect yet:
class Model:
    pass
class rel(object):
    def __init__(self,cls):
    self.relation = cls;

class a(Model):
    pass

class c(Model):
    some_other = 4
    a = rel(a)

class b(Model):
    somevar = 3
    a = rel(a);

### Some sort of hack ###
gl = list(globals())
for v in gl:
    if type(eval(v)).__name__ == 'classobj':
        cls = eval(v);
        if len(cls.__bases__) > 0 and cls.__bases__[0].__name__ == "Model":
            for atr in dir(cls):
                if type(getattr(cls,atr)).__name__ == "rel":
                    relL = getattr(cls,atr).relation;
                    print relL.__name__, "->", cls.__name__
                    setattr(relL,cls.__name__ + "_set",cls)
### End - Some sort of hack ###

d = a();
print a.b_set.somevar
print a.c_set.some_other

Output:
a -> c
a -> b
3
4

EDIT: Some better dirty hack:
class Model:
    ### Some sort of hack ###
    def __init__(self):
        gl = list(globals())
        print self.__class__.__name__, "Relations:"
            for v in gl:
                if type(eval(v)).__name__ == 'classobj':
                    cls = eval(v)
                    if len(cls.__bases__) > 0 and cls.__bases__[0].__name__ == "Model":
                        for atr in dir(cls):
                            if type(getattr(cls,atr)).__name__ == "rel":
                                rell = getattr(cls,atr).relation;
                                if isinstance(self,rell):
                                    print rell.__name__, "<-", cls.__name__
                                    setattr(rell,cls.__name__ + "_set",cls)
    ### End - Some sort of hack ###

class rel(object):
    def __init__(self,cls):
    self.relation = cls;

class a(Model):
    pass

class c(Model):
    some_other = 1
    a = rel(a);

class d(Model):
    string = "Hello"
    c = rel(c)
class b(Model):
    somevar = 3
    a = rel(a);
    d = rel(d);

a = a();
c = c();
print "\nVars:"
print "somevar",":",a.b_set.somevar
print "some_other",":",a.c_set.some_other

Output:
a Relations:
a <- c
a <- b
c Relations:
c <- d
...


text:
Q: Launch urls based on different versions of java I am in a situation where i need to create a simple launcher that allows me too select which web address to launch with different versions of java.  I have researched several sites.  Having the user change windows settings is not an option as it would generate too many support calls or user does not have priviliges. What i want is a programming way to set or change the version of java being used to launch a url.  I have seen proprietary systems make launchers with a gui that allows you to change address and java version and then launch it in a browser.  I am new to development and obviously having trouble understanding which techniques to use.
Will you please point me in the right direction.  I am comfortable writing guis(in c# or java) I just need to know how to write the function for the launch button?
function launchbutton(url, javaversion)

{

If (javaversionselect == 1.3)
{
open url in default browser running java version 1.3
}

If (javaversionselect == 1.4)
{
open url in default browser running java version 1.4
}

If (javaversionselect == 1.5)
{
open url in default browser running java version 1.5
}

If (javaversionselect == 1.6)
{
open url in default browser running java version 1.6}
}

A: Bare Bones Browser Launcher will detect the java version and use the appropriate calls.
http://www.centerkey.com/java/browser/

A: You wan't be able to change the version of java that for example 'IE' or 'Chrome' use from withing your  application, your only solutions would be to use some kind of embedded browser

*

*jBrowser

*XPCOM from Mozilla

*Browse source and look on how Eclipse embedded their browser

A: You can write an applet that does it.  Compile something like this, using javac -target 1.3:
public class Redirector
extends Applet {
    @Override
    public void start() {
        String newURL;

        Package pkg = Object.class.getPackage();
        if (pkg.isCompatibleWith("1.7")) {
            newURL = "java17.html";
        } else if (pkg.isCompatibleWith("1.6")) {
            newURL = "java16.html";
        } else if (pkg.isCompatibleWith("1.5")) {
            newURL = "java15.html";
        } else if (pkg.isCompatibleWith("1.4")) {
            newURL = "java14.html";
        } else {
            newURL = "java13.html";
        }

        try {
            getAppletContext().showDocument(new URL(newURL));
        } catch (MalformedURLException e) {
            showStatus(e.toString());
        }
    }
}

If you really want let the user choose the Java version for himself, you can create UI elements in your applet for that:
public class Redirector
extends Applet
implements ActionListener {
    private Choice list;

    @Override
    public void init() {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    list = new Choice();
                    list.add("1.7");
                    list.add("1.6");
                    list.add("1.5");
                    list.add("1.4");
                    list.add("1.3");

                    Button button = new Button("Launch");
                    button.addAtionListener(Redirector.this);

                    add(new Label("Java version:"));
                    add(list);
                    add(button);
                }
            });
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void actionPeformed(ActionEvent event) {
        String newURL;
        String version = list.getSelectedItem();
        if (version.equals("1.7")) {
            newURL = "java17.html";
        } else if (version.equals("1.6")) {
            newURL = "java16.html";
        } else if (version.equals("1.5")) {
            newURL = "java15.html";
        } else if (version.equals("1.4")) {
            newURL = "java14.html";
        } else {
            newURL = "java13.html";
        }

        try {
            getAppletContext().showDocument(new URL(newURL));
        } catch (MalformedURLException e) {
            showStatus(e.toString());
        }
    }
}


text:
Q: PHPUnit+Selenium: 'displayed()' isn't working on popover element In my PHPUnit_Extensions_Selenium2TestCase test case, I try to open a bootstrap popover element (http://getbootstrap.com/javascript/#popovers) and then click a link inside.
I manage to open it, but then I can't click the link because PHPUnit considers that it's still hidden. I use the waitUntil function but it timeouts, although the element is in fact visible (I can see the popover opened when I run the test case).
My code:
// open popover
$this->byXPath("//something")->click();

// wait
$this->waitUntil(function() {
    return $this->byId("myId")->displayed() ? true : null;
}, 2000);

// click on link (never reached, the previous function timeouts)
$this->byId("myId")->click();

Thanks for your help.

A: I'm not sure why you are getting the error, I believe the problem is with your markup / js. Just checked the below with the latest libraries, works fine (url navigation doesn't work from the popover for some reason):
class Test extends PHPUnit_Extensions_Selenium2TestCase
{

    protected function setUp()
    {
        $this->setBrowser('chrome');
        $this->setBrowserUrl('');
    }

    public function test()
    {
        $this->url('http://jsfiddle.net/ianbytchek/0adyuhkg/embedded/result/');
        $this->frame($this->byXPath('//*[@id="result"]/iframe'));

        // open popover
        $this->byXPath("//button")->click();

        // wait
        $this->waitUntil(function () {
            return $this->byId("myId")->displayed();
        }, 2000);

        // click on link (never reached, the previous function timeouts)
        $this->byId("myId")->click();

        sleep(10);
    }
}

When the link gets clicked, the button changes the style, check the fiddle.