text:
Q: how to transfomr list() into str_split? I want to upgrade my server's PHP from 5.5 to 7, as I heard it will perform faster.
I read in the documentation that:

list() can no longer unpack string variables. str_split() should be
  used instead.

Currently I have a string quantity variable which contains a string of comma seperated numbers, like 2,5,3.
I'm using list in order to create 3 new variables, one per each of these 3 comma separated values:
list($item[$key + 1]["red"], $item[$key + 1]["green"], $item[$key + 1]["blue"]) = explode(",", $item[$key + 1]["quantity"]);

Will this command no longer work on PHP 7? If so, how should I write it with str_split?

A: You may use explode to accomplish what you are trying to do.
$quantity = '2,5,3';
$item = explode(',',$quantity);
print_r($item);


text:
Q: Packet Declaration Language I'm writing a program which will communicate with another program and, obviously, should use same protocol for it.
What I need is something like protobuf, but not protobuf, because it won't let me describe packets format exactly as I want. For example, it inserts field numbers in its packets. Pickle won't do either because of the same reasons.
I wrote my own thing using struct but it is ugly and I not fully understand how is it working. I need something where I can describe different fields like short, integer, their endianness, complex fields, which consists of primitive fields or another complex fields, arrays of primitive fields, array of complex fields.
Could you recommend something like this? Or I doomed to stick to my own solution?

A: I've had to write Python code for dealing with binary formats before, and struct is no fun to work with.  The construct module is much nicer.  It allows you to both consume and generate complex binary formats using a simple declarative syntax.

redpajama_set_name: RedPajamaStackExchange


text:
Q: akka.net Stashing messages during a specific state of an actor I have an actor (Person) that I want to be able to stash the messages during a state.  The issue is that I am not sure how to best to accomplish this.
Lets say I have a few commands.
ChangeAddress
ChangePhoneNumber
BeginMove
FinishMove

While I am in the middle of a move (After BeginMove has started and before FinishMove) I want to prevent updates to Address and PhoneNumber and just replay any events after the move is finished.  I am using a ReceivePersistentActor and each command is a different class.
Right now I was thinking about a status flag on the actor but though the become/unbecome functionality would be a more natural fit but can't see how to apply it to the different commands.
Also as a side question is there a good pattern for breaking up the amount of commands and recovers that have to be written as an actor needs to handle more commands/events?

A: Akka already has this built in:
http://getakka.net/docs/working-with-actors/Stashing%20Messages
You would stash messages in one state as they are received, then unstash when you are ready to transition to the relevant state. The stashed messages then go to the front of the mailbox for processing.
In your example you would receive a BeginMove command and transition to a Moving state by calling Become(Moving). The next time a message is processed you will be in this new state. Inside your Moving method, you would configure the Receive<ChangeAddress>message handlers to stash the message and all the other handlers to have whatever behaviour you want whilst Moving. At some point in the future you need a FinishMove command that changes your behaviour back to what it was before you started the move and unstashes all messages. At this point all stashed messages will begin to be processed in your original behaviour state. This is all non-blocking.
void OriginalState()
    {
        Receive<ChangeAddress>(s =>
        {
             // change address logic
        });

        Receive<BeginMove>(msg =>
        {
            Become(Moving);
        }
    }

void Moving()
    {
        Receive<ChangeAddress>(s =>
        {
            Stash.Stash();
        });

        Receive<FinishMove>(msg =>
        {
            Become(OriginalState);
            Stash.UnstashAll();
        }
    }

See switchable behaviours for more example code on how to configure your states to handle your message types.
One way to break things up is to delegate behaviour to child actors if appropriate, but it becomes more of a design issues at that stage.

A: first things first: as long as there is no PipeTo() calls - there is nothing to change.
Every actor processes one messages at a time, so when it get a list of requests they will be processed in received order, one by one, in a sequence.
To avoid interruption when processing a long running call  (like using db) - I'm stacking my actor - please see an example with receiving actor. This allows to:

*

*stop processing inbox

*prevents stopping method by dispatcher (timeout)

*avoids using a stash as it is not needed
public class ProcessActor : ReceiveActor{

 public ProcessActor() {

    Receive < ChangeAddress > (
        message =  > {
            BecomeStacked(ProcessingOrDoNothing);
            //{do the job here}
            UnbecomeStacked();
        });
 }

  public void ProcessingOrDoNothing(){}

}


text:
Q: Running two projects at once in Visual Studio 2010 - do not want You may think this question is the exact duplicate of Running two projects at once in Visual Studio. Not really, it is the exact opposite.
I have a VS 2010 solution with two MVC3 projects. I've already configured the solution with a single startup project. However, each time I run it, VS spawns two servers with the two MVC applications (and one does not have direct dependency on the other).
So, how do I get rid of such behavior?

A: Click on the project you don't want to start up, go to the Properties tab, and change 'Always start when debugging' to False.


text:
Q: Converting a String to a Date in Swift I have date in string with format below code want to change in Date
but i'm getting nil
let addedDate = "Tue, 25 May 2010 12:53:58 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "dd MM YYYY"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")

A: The date format needs to be for the string you are trying to convert, not the format you want back
so
formatter.dateFormat = "dd MM YYYY"

should be
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"

A: You have to transform your String (addedDateString) to a Date? (addedDate) then you can convert it to a String (dateString) using the format you want. Please note: addedDate is nil when conversion from String to Date failed.
import UIKit

let addedDateString = "Tue, 25 May 2010 12:53:58 +0000"

// Transform addedDateString to Date
let addedDateFormatter = DateFormatter()
addedDateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"

if let addedDate = addedDateFormatter.date(from: addedDateString) {

    // Converstion String to Date return a valid Date
    print ("addedDate", addedDate)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MM YYYY"
    let dateString = dateFormatter.string(from: addedDate)
    print("Date: ", dateString)

} else {

    // addedDate == nil value when conversion String to Date failed
    print ("addedDateString not valid")

}

You can also make a function. Something like this:
func transformStringDate(_ dateString: String,
                         fromDateFormat: String,
                         toDateFormat: String) -> String? {

    let initalFormatter = DateFormatter()
    initalFormatter.dateFormat = fromDateFormat

    guard let initialDate = initalFormatter.date(from: dateString) else {
        print ("Error in dateString or in fromDateFormat")
        return nil
    }

    let resultFormatter = DateFormatter()
    resultFormatter.dateFormat = toDateFormat

    return resultFormatter.string(from: initialDate)
}

print (transformStringDate("Tue, 25 May 2010 12:53:58 +0000",
                           fromDateFormat: "E, d MMM yyyy HH:mm:ss Z",
                           toDateFormat: "dd MM YYYY") ?? "Error")


text:
Q: Running python scripts causes BSOD seemingly at random I am working with Python 3.2 on an HP desktop running Windows 7. For awhile I have had issues with Python crashing my system, causing a blue screen of death, and I can't find any pattern in when it happens.
It has happened before when I closed out of the Python Shell, but mainly it happens when I initiate a run of the program out of IDLE.
It has also happened upon running several different programs, including larger applications using about a dozen modules, as well as on simple 6-liner test code with no imports.
There have even been times when I have been running a tkinter GUI several times in a row changing nothing but label formatting inbetween runs, and it will work fine for five or six times in a row, then suddenly bam: BSOD.
I've looked through the python docs a little but don't see anything about a bug that may be causing this. I know I haven't given much to go off of, but any ideas for what might be happening would be greatly appreciated!
Update:
The following is from the bugcheck analysis of dump file created when this happens.
CRITICAL_OBJECT_TERMINATION (f4)
A process or thread crucial to system operation has unexpectedly exited or been
terminated.
Several processes and threads are necessary for the operation of the
system; when they are terminated (for any reason), the system can no
longer function.
Arguments:
Arg1: 00000003, Process
Arg2: 8725ed40, Terminating object
Arg3: 8725eeac, Process image file name
Arg4: 82e11ca0, Explanatory message (ascii)

Debugging Details:
------------------

----- ETW minidump data unavailable-----

PROCESS_OBJECT: 8725ed40
IMAGE_NAME:  mfehidk.sys
DEBUG_FLR_IMAGE_TIMESTAMP:  50296571
MODULE_NAME: mfehidk
FAULTING_MODULE: 00000000
PROCESS_NAME:  pythonw.exe
BUGCHECK_STR:  0xF4_pythonw.exe
CUSTOMER_CRASH_COUNT:  1
DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT
CURRENT_IRQL:  0
ANALYSIS_VERSION: 6.3.9600.17029 (debuggers(dbg).140219-1702) x86fre
LAST_CONTROL_TRANSFER:  from 82ef3edb to 82cf118c

I don't know enough about the system for this to mean much to me, but hopefully it helps.


text:
Q: Alias not working I have an alias that does an ssh into a machine and executes 1 line of code as following:
alias posts-update= 'ssh user@host.com "cd /var/www/blog/posts && git pull"'

This works perfectly if executed manually but if I try to use the posts-update alias, it does nothing and prints nothing

A: There is a space after the = in your command, splitting the parameter into two:

*

*'posts-update='

*'ssh user@host.com "cd /var/www/blog/posts && git pull"'
This causes alias to alias posts-update to nothing (as there is nothing following the =). It should also print an error message about the second parameter, which doesn't have a = in it so alias thinks it's an existing alias name to be described.


text:
Q: boost::graph function with edge iterator passed by value and graph passed by reference The following code appears in boost graph library manual available here.

I have no problem understanding what the code does. My questions are:
(1)Why is the graph object passed as a constant reference. const Graph& g ?
(2)Why is the edge descriptor not passed similarly, but simply by value?
As I understand, the answer to (1) is that it imposes a constraint to ensure that the function is_self_loop() does not modify the object g and also that no copy is made of g within the function.
On the other hand, a copy is indeed made within the function of the edge_descriptor.
Is there any reason to accord these two different reasonings for the two passed objects? The function does not seem to alter e either, so why not pass it as a const and also to prevent a local copy, why not also pass it as a reference? Does this have to do with the sizes of g and e? That is, copying e is not a costly operation? If yes, how can the user figure out which object is "easy" to copy and which object is expensive to copy?


text:
Q: Makefile negative wildcard I use to make use of wildcards in a Makefile in order to select all the files that end with an .c suffix in its name. That looks like that SRCS := $(wildcard *.c). In other parts of the Makefile SRCS is used.
What I need to do now is to prevent a given file to be included in the SRCS variable. The way I found to do is combine the shell directive with some console commands: SRC :=$(shell find . -name "*.c" | grep -v "file_to_exclude.c" | xargs)
That works fine, but I would like to know whether there is some other  more elegant way than that one using only wildcards.

A: You can use the $(filter-out P,T) command...
SRCS := $(filter-out icky-file.c,$(wildcard *.c))

Of course, using shell script is pretty much taking things to another level, as then you're not constrained by Make's commands.
Got a bunch of non-wants?
NOWANTS := one.c two.c three.c
SRCS := $(filter-out $(NOWANTS),$(wildcard *.c))


text:
Q: Facing issue while consuming services from a class library in a API project I have created a Class library project and add the service reference of "E-Verify" web service to this project. In this project, I have created a wrapper class and consumed all the services of "E-Verify".
I have added the reference to this project in the API project. But, while assessing this wrapper method inside an API project I am getting an error
Error:

Could not find default endpoint element that references contract 'EmployerWebServiceV29.IEmployerWebServiceV29' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

Anyone having any idea how to fix this issue?
Wrapper Code:
try {
    EmployerWebServiceV29Client client = new EmployerWebServiceV29Client();
    client.ClientCredentials.UserName.UserName = "";
    client.ClientCredentials.UserName.Password = "";
    client.VerifyConnection();
} catch (Exception ex) {
    throw new ServiceAccessException(ErrorConstants.SERVICE_ACCESS_ERROR);
}

app.config:
<bindings>
    <basicHttpBinding>
        <binding name="BasicHttpBinding_IEmployerWebServiceV29">
            <security mode="TransportWithMessageCredential"/>
        </binding>
    </basicHttpBinding>
    <wsHttpBinding>
        <binding name="CustomBinding_IEmployerWebServiceV29">
            <security mode="TransportWithMessageCredential">
                <transport clientCredentialType="None"/>
                <message clientCredentialType="UserName"/>
            </security>
        </binding>
    </wsHttpBinding>
</bindings>

<client>
    <endpoint address="stage.e-verify.uscis.gov/WcfWebService/…;"
              binding="basicHttpBinding"
              bindingConfiguration="BasicHttpBinding_IEmployerWebServiceV29"
              contract="EmployerWebServiceV29.IEmployerWebServiceV29"
              name="BasicHttpBinding_IEmployerWebServiceV29"/>
    <endpoint address="stage.e-verify.uscis.gov/WcfWebService/…;"
              binding="wsHttpBinding"
              bindingConfiguration="CustomBinding_IEmployerWebServiceV29"
              contract="EmployerWebServiceV29.IEmployerWebServiceV29"
              name="CustomBinding_IEmployerWebServiceV29"/>
</client>


text:
Q: How Do I Resume Music That Is From Outside The App? I am making a small app and I want for the app to resume playing applications like spotify or pandora once it stops. So, I have this:
        AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    Boolean myChecker = audioManager.isWiredHeadsetOn();

    if(audioManager.isMusicActive() == true)
    {
        Log.i("Hey", "Music Is Playing");
    }
    if(audioManager.isMusicActive() == false){
        Log.i("Hey", "Music Isn't Playing");

        //TODO: Resume The Music My Dudes!

    }

I assumed there would be some sort of audioManager function that would resume the background music or play it again, but I haven't found anything that works.

A: Try this:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

A: You can call this method
am.abandonAudioFocus(afChangeListener); ,
where afChangeListener is OnAudioFocusChangeListener

This notifies the system that you no longer require focus and unregisters the
      associated OnAudioFocusChangeListener. If you requested transient focus, this
      will notify an app that paused or ducked that it may continue playing or
      restore its volume.

A: You need to call onAudioFocusChangeListener to handle all music services.
Like this..
  onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    @Override
    public void onAudioFocusChange(int focusChange) {

        switch (focusChange) {
            case (AudioManager.AUDIOFOCUS_LOSS):
                break;
            case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
                pause();
                break;
            case (AudioManager.AUDIOFOCUS_GAIN):
                resume();
                break;
            case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                // Lower the volume while ducking.
                player.setVolume(0.1f, 0.1f);
                break;
        }
    }
};

int mediaresult = audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

if (mediaresult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    //other app stop music you can play now
     //put you play code here..
 }

Enjoy!!!


text:
Q: execute relational query with django orm I have this model in my django application:
class Buyer(model.Model):
    username = ...
    ...

class Seller(model.Model):
    username = ...
    ...

class Stuff(model.Model):
    seller = models.ForeignKey(Seller)
    ....

class BuyerStuff(models.Model):
    buyer = models.ForeignKey(Buyer)
    stuff = models.ForeignKey(Stuff)
    ...

I want to get all stuffs that related to specific seller that buyer for example order that stuff. I can do this with raw sql but I want to know is there any way to do this with django ORM?

A: Are you looking for reverse relation ships?
https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
also have a look at the 'related_name' model property... nice to use in reverse lookups.

A: By default FK reverses are named {model}_set
So in your case:
john = Buyer.objects.get(pk=5)
john_stuff = john.buyerstuff_set.all()

But using related_names is a bit easier to remember.
If your model was like:
class BuyerStuff(models.Model):
    buyer = models.ForeignKey(Buyer)
    stuff = models.ForeignKey(Stuff, related_name='stuff')
    ...

john_stuff = john.stuff.all()
But if you want to query against FK:
buyer = BuyerStuff.objects.filter(buyer__pk=5)

And at last select_related and fetch_related, are performance optimization (JOINs). select_related is used in One-to-X scenarios, prefetch_related in Many-to-X scenarios.


text:
Q: How to inject OSGi service to EJB with Blueprint I know it is possible to use ServiceTracker to inject OSGi services to EJBs.
However, how should I use OSGi Blueprint XML configuration to inject services to standard EJBs, so that services would be available when EJBs are used elsewhere?
Or is it really impossible, as EJBs work in a layer of their own?
I've been trying to do this with Aries Blueprint as well as Gemini Blueprint, with JBoss AS7, without luck.
As an example bean:
import javax.annotation.PostConstruct;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import org.osgi.framework.BundleContext;

@Stateless
@LocalBean
public class SimpleStatelessSessionBean {

  InformationService service; // how'd I go about to get this populated?

  @PostConstruct
  public void init() {

  }

  public String getMessage() {

    if (service == null)
      throw new IllegalStateException("Service not available");

    return "EJB:" + service.getMessage();
  }
}

A: It seems what I asked is not really possible.
What is possible is

*

*for spring apps, use Gemini Blueprint which combines spring injection with OSGi

*for ejbs/servlets, use CDI/OSGi integration component. There exists PAX CDI for Pax Web and JBoss Weld OSGi integration (somewhat usable now, in process for JBoss AS), at least

*for any app, when else fails, programmatic usage of ServiceTracker works


text:
Q: I accidentally updated, but my replays are still there - why? I have a ton of replays saved, which I wanted to convert to video before the update hits, as the new update comes with balance changes, which I would expect would make the replays from older versions unplayable.
From what I understand, the replays you take after each match are simply a recording of all the events and inputs that happened in a match. So when you watch a replay, the game simply recreates the whole match based on that info. That's why you can interact with the replay and change the camera around for example.
So if an update comes with balance changes, the game shouldn't be able to replay the data. Say you had a smash attack that takes longer to execute in the new patch. If you attempt to watch the replay from before the patch, the changed smash attack would throw the whole thing out of sync, wouldn't it? That's why they always warn you of updates and how replays would be lost... or so I thought.
I was horrified today when I realized the game had updated when I wasn't looking. I expected all the unsaved replays to be gone, but they were still there. And yes, the game was updated, as I was able to play online. From the few replays that I tried to watch, they seemed to work perfectly fine... but why?
I don't get it. Why can I still look at the old replays? Do I have to fear some of the replays might be gone and it simply kept all salvageable replays? Or do the replays somehow play back using an older version of the game? If so, why do they warn us in upcoming updates if that's the case?

A: It's been awhile since I've been home to play Smash on my own Switch, but I finally got the chance last night.
Upon opening Smash, I was prompted with the screen below with some Version 3.1.0 details. I've highlighted one bullet in particular (the system wouldn't let me screenshot this, so enjoy a picture of my TV):

*

*There may be some compatibility issues with replays from Ver. 3.0.0 and Ver. 3.0.1. Replays from Ver. 2.0.2 and earlier are not compatible. If you want to keep your replays, convert them into videos before installing the update. You can do this via Vault -> Replays -> Replay Data -> Convert to Video.

It sounds like Nintendo only "invalidated" replays from 2.0.2 and earlier (the last update before 3). 3.0.0 updates on the other hand, they've left with a warning that "there may be some compatibility issues."
It looks like these "compatibility issues" are exactly what you're seeing--but at least you didn't lose all of your replays this time!

A: We're not really sure yet how or why 3.0.0/3.0.1 replays are still usable in 3.1.0. The leading theory is that the game knows what characters/stages are unchanged and so doesn't need to invalidate replays that only use them. The other major guess is that the game actually has both datasets saved and will pick the one that matches the replay, though I haven't seen any proof of this yet.


text:
Q: I Keep Getting "IndentationError: expected an indented block" My program is simple, i'm planing on making a console application where you can draw some art using turtle by some commands such as "left_star","left_circle" ext. When I tried to implement updates, it gives me the indentation error for some reason.Can you help me with this problem?
import turtle
import random
turtle.color('green', 'red')
turtle.begin_fill()
print(" ")
print("right_star: makes a right star.             ")
print(" ")
print("left_star: makes a star on the left.        ")
print(" ")
print("right_circle: makes a circle on the right.  ")
print(" ")
print("left_circle: makes a circle on the left side")
print(" ")
_input = input("What shape do you want to make? type 'help' if you want help: ")

turtle.Turtle()
print(turtle.pos())
if _input == "left_star":
    i = 0
    while  i != 10:
        turtle.forward(200)
        turtle.left(200)
        i += 1
        if  i > 9:
        #_input2 = input("What shape do you want to make? type 'help' if you want help: ")
    elif _input=="right_circle":
        while True:
            turtle.forward(70)
            turtle.right(70)
            _input2 = input("What shape do you want to make? type 'help' if you want help: ")
    else _input == "right_star":
        while True:
            turtle.right(200)
            turtle.forward(200)
        while True:
            _input2 = input("What shape do you want to make? type 'help' if you want help: ")
    elif _input == "left_circle":
        while True:
            turtle.left(70)
            turtle.forward(70)
    elif _input == "help":
        print("right_star: makes a right star.             ")
        print("left_star: makes a star on the left.        ")
        print("right_circle: makes a circle on the right.  ")
        print("left_circle: makes a circle on the left side")
        print("PLEASE RESTART THE APPLICATION!'python opt.py'")

A: Your elif _input=="right_circle": and all consecutive elifs are not aligned with if _input == "left_star":. Remove the unnecessary spaces in front of the elifs.


text:
Q: Why selector "input:read-only, input:-moz-read-only" won't work on Google Chrome? Why selector input:read-only, input:-moz-read-only won't work on Google Chrome? Works only, if I write it as two separate selectors input:read-only, input:-moz-read-only with same instruction.

input:read-only,
input:-moz-read-only {
  border: 1px solid red;
}

/* Works if i will repeat it separate, like below */

/* input:read-only {
    border: 1px solid red;
} */
<input type="text" name="" value="Read-only" id="" readonly>

A: As @Paulie_D said, "... you can't combine vendor prefixed selectors. Separate them.".
Similar question was already answered on stackoverflow.
I close the question.


text:
Q: Is there a way to decode numerical COM error-codes in pywin32 Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)

Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic.
How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful?
[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!

A: Yes try the win32api module:
import win32api
e_msg = win32api.FormatMessage(-2147352567)

You can grab any codes returned from the exception and pass them to FormatMessage. Your example had 2 error codes.

A: Specifically for pythoncom, the errors codes that result are more than cryptic. This is because pythoncom represents them internally as a 32bit signed integer, when the correct representation is a 32bit unsigned integer. As a result, the conversion that you end up seeing in the stack trace is incorrect.
In particular, your exception, according to pythoncom, is -2147352567, and your (for lack of a better word) Err.Number is -2146788248.
This however causes some issues when watching for specific errors, like below:
DISP_E_EXCEPTION = 0x80020009
#...
#except pywintypes.com_error as e:
#    print repr(e)
#    #pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
#    hr = e.hresult

hr = -2147352567
if hr == DISP_E_EXCEPTION:
    pass #This never occurs
else:
    raise

To see why this has issues, lets look into these error codes:
>>> DISP_E_EXCEPTION = 0x80020009
>>> DISP_E_EXCEPTION
2147614729L
>>> my_hr = -2147352567
>>> my_hr == DISP_E_EXCEPTION
False

Again, this is because python sees the constant declared as positive, and pythoncom's incorrect declaration interpreted it as negative. Of course, the most obvious solution fails:
>>> hex(my_hr)
'-0x7ffdfff7'

The solution is to properly interpret the number. Luckily, pythoncom's representation is reversible. We need to interpret the negative number as a 32 bit signed integer, then interpret that as an unsigned integer:
def fix_com_hresult(hr):
    import struct
    return struct.unpack("L", struct.pack("l", hr))[0]

>>> DISP_E_EXCEPTION = 0x80020009
>>> my_hr = -2147352567
>>> my_hr == DISP_E_EXCEPTION
False
>>> fixed_hr = fix_com_hresult(my_hr)
>>> fixed_hr
2147614729L
>>> fixed_hr == DISP_E_EXCEPTION
True

So, putting it all together, you need to run fix_com_hresult() on that result from pythoncom, essentially all the time.
Since normally you need to do this when checking for exceptions, I created these functions:
def fix_com_exception(e):
    e.hresult = fix_com_hresult(e.hresult)
    e.args = [e.hresult] + list(e.args[1:])
    return e

def fix_com_hresult(hr):
    import struct
    return struct.unpack("L", struct.pack("l", hr))[0]

which can then be used how you expect:
DISP_E_EXCEPTION = 0x80020009
try:
    #failing call
except pywintypes.com_error as e:
    print repr(e)
    #pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
    fix_com_exception(e)
    print repr(e)
    #pywintypes.com_error: (2147614729L, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
    if e.hresult == DISP_E_EXCEPTION:
        print "Got expected failure"
    else:
        raise

I was unable to find a MSDN document listing all HRESULTs, but I found this: http://www.megos.ch/support/doserrors_e.txt
Also, since you have it, fix_com_hresult() should also be run on your extended error code (-2146788248), but as Euro Micelli said, it doesn't help you in this particular instance :)

A: You are not doing anything wrong. The first item in your stack trace (the number) is the error code returned by the COM object. The second item is the description associated with the error code which in this case is "Exception Occurred". pywintypes.com_error already called the equivalent of win32api.FormatMessage(errCode) for you. We'll look at the second number in a minute.
By the way, you can use the "Error Lookup" utility that comes in Visual Studio (C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\ErrLook.exe) as a quick launching pad to check COM error codes. That utility also calls FormatMessage for you and displays the result. Not all error codes will work with this mechanism, but many will. That's usually my first stop.
Error handling and reporting in COM is a bit messy. I'll try to give you some background.
All COM method calls will return a numeric code called an HRESULT that can indicate success or failure. All forms of error reporting in COM build on top of that.
The codes are commonly expressed in hex, although sometimes you will see them as large 32-bit numbers, like in your stack trace. There are all kinds of predefined return codes for common results and problems, or the object can return custom numeric codes for special situations. For example, the value 0 (called S_OK) universally means "No error" and 0x80000002 is E_OUTOFMEMORY. Sometimes the HRESULT codes are returned by the object, sometimes by the COM infrastructure.
A COM object can also choose to provide much richer error information by implementing an interface called IErrorInfo. When an object implements IErrorInfo, it can provide all kinds of detail about what happened, such as a detailed custom error message and even the name of a help file that describes the problem. In VB6 and VBA. the Err object allows you to access all that information (Err.Description, etc).
To complicate matters, late bound COM objects (which use a mechanism called COM Automation or IDispatch) add some layers that need to be peeled off to get information out. Excel is usually manipulated via late binding.
Now let's look at your situation again. What you are getting as the first number is a fairly generic error code: DISP_E_EXCEPTION. Note: you can usually figure out the official name of an HRESULT by googling the number, although sometimes you will have to use the hex version to find anything useful.
Errors that begin with DISP_ are IDISPATCH error codes. The error loosely means "There was a COM exception thrown by the object", with more information packed elsewhere (although I don't quite know where; I'll have to look it up).
From what I understand of pywintypes.com_error, the last number in your message is the actual error code that was returned by the object during the exception. It's the actual numeric code that you would get out of VBA's Err.Number.
Unfortunately, that second code -2146788248 (0x800A9C68) is in the range reserved for custom application-defined error messages (in VBA: VbObjectError + someCustomErrorNumber), so there is no centralized meaning. The same number can mean entirely different things for different programs.
In this case, we have reached a dead end:

The error code is "custom", and the application needs to document what it is, except that Excel doesn't. Also, Excel (or the actual source of the error) doesn't seem to be providing any more information via IErrorInfo.

Excel is notorious (to me at least) for cryptic error codes from automation and obscure situations that cause them. This is especially so for errors that one could consider "design-time errors" ("you should have known better than calling a method that doesn't exist in the object"). Instead of a nice "Could not read the Name property", you get "Run-time error '1004': Application defined or object-defined error" (which I just got by trying to access a Name property on a Range, from VBA in Excel). That is NOT very helpful.
The problem is not routed on Python or it's interface to Excel. Excel itself doesn't explain what happened, even to VBA.
However, the general procedure above remains valid. If you get an error from Excel in the future, you might get a better error message that you can track the same way.
Good luck!

A: Do it like this:
try:
    [whatever code]
except pythoncom.com_error as error:
    print(win32api.FormatMessage(error.excepinfo[5]))

More information on digesting the pythoncom.com_error object here: https://web.archive.org/web/20170831073447/http://docs.activestate.com/activepython/3.2/pywin32/com_error.html

A: No-one has yet mentioned the strerror attribute of the pywintypes.com_error Exception. This returns the result of FormatMessage for the error code. So instead of doing it yourself like this
try:
    [whatever code]
except pythoncom.com_error as error:
    print(win32api.FormatMessage(error.excepinfo[5]))

You can just do this:
try:
    [whatever code]
except pythoncom.com_error as error:
    print(error.strerror)

Note it will return None if you have a non-standard HRESULT :(


text:
Q: "Conversion failed when converting the nvarchar value '113332,113347' to data type int." I am getting error for the below code. I am passing local ids as "113332,113347"
cn.Open();
SqlCommand cmd = new SqlCommand("SelectUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@in_UserId", SqlDbType.Int).Value = Convert.ToInt32(userId);
cmd.Parameters.Add("@in_StartDate", SqlDbType.DateTime).Value = fromDate;
cmd.Parameters.Add("@in_EndDate", SqlDbType.DateTime).Value = toDate;
cmd.Parameters.Add("@in_LocalIds", SqlDbType.NVarChar, 100).Value = localids.ToString();
cmd.ExecuteNonQuery();

"Conversion failed when converting the nvarchar value '113332,113347' to data type int."
In database, the local id is of datatype int.
The stored procedure code is given below
CREATE PROCEDURE [dbo].[User_Update] @in_UserId INT
,@in_StartDate DATETIME
,@in_EndDate DATETIME
,@in_LocalIds NVARCHAR(100)
AS
BEGIN
SELECT * FROM TABLE1 WHERE LocalId in (@in_LocalIds) AND UserId = @in_UserId
END
go

A: In the @in_LocalIds parameter you have the int joined by ',', so split the values (in SQL it should be some kind of while loop), convert the values to int and insert them to the temporary table.
Then use the table in your where clause.
EDIT:
CREATE PROCEDURE [dbo].[User_Update] @in_UserId INT
,@in_StartDate DATETIME
,@in_EndDate DATETIME
,@in_LocalIds NVARCHAR(100)
AS
BEGIN

declare @tempLocalIds nvarchar(100)
declare @tempStrId nvarchar(100)
declare @tempId int
declare @idx int
declare @Ids TABLE ( ID int )

set @tempLocalIds = @in_LocalIds

while( len(@tempLocalIds) > 0)
begin
    -- find index of first ',' char
    set @idx = charindex(',', @tempLocalIds)
    -- get substring 0 to previously found index
    set @tempStrId = substring(@tempLocalIds, 0, @idx-1)
    -- convert the value
    set @tempId = convert(@tempStrId as int)
    -- remove the first number from string
    set @tempLocalIds = substring(@tempLocalIds, @idx, len(@tempLocalIds) - @idx -1)

    -- insert into the temp table
    insert into @Ids(ID)
    values (@tempId)

end

SELECT * FROM TABLE1 WHERE LocalId in (select ID from @Ids) AND UserId = @in_UserId
END
go


text:
Q: C++ Vector of templated class objects I don't know if it's possible to achieve what I'm trying but maybe someone can guide me in the right direction. Sidenote: this is on an embedded system.
I have an SPI communication that returns a std::vector<int> representing a set of registers. This is done in a separate thread so asynch.
To handle this, I create an object on every read call containing a std::promise<std::vector<int>> (and some other information) and directly return the future of it, so the caller can wait for the result.
Once the SPI transfer is complete, I set the value of the promise accordingly. So far so good.
Now what I'd like to do is to not always return a future of type std::vector<int> but do some preprocessing on the vector and return either int or double or even a struct.
I thought I can achieve that by handing an anonymous function to the read function and store a reference in the object. This function would then be called before the promise is assigned.
The problem I now have is that the return type of this function directly affects the return type of my promise and the object storing them is not always the same anymore. So I thought I just template it
template <class ret_type>
class obj{
    public:
    std::promise<ret_type> prms;
    ret_type (*map_function)(std::vector<int>);
    ...
};

But now I have to problem that my vector containing these objects (the SPI queue) that was of type std::vector<obj> cannot hold objects of different types.
Is there a proper way to solve that?
edit:
I'd use the vector in a way like
for(auto &element : vector){
    std::vector<int> answer_from_spi = spi_read();
    element.prms.set_value(element.map_function(answer_from_spi));
}

A: Note: As I don't have enough reputation to comment, I am writing an answer.
If you can use C++17, then maybe you can use std::any.
https://en.cppreference.com/w/cpp/utility/any
Before C++17, you can create a polymorphic classes (Define a base class, derived classes for different types you want to return and store) and store the pointers to them in the vector. Something like this:
vector<Base*> vec;
vec.push_back(derived1);
vec.push_back(derived2);
Please see the below answer:
Vector that can have 3 different data types C++

A: The bog-standard solution consists of moving your entire type-varying part into a virtual function. Store (smart) pointers to the base class in your vector, and have the virtual function implemented in derived classes.
class obj {
  public:
    virtual void set_promise () = 0;
};

template <class ret_type>
class obj_impl : public obj {
    std::promise<ret_type> prms;
    ret_type (*map_function)(const std::vector&<int>);
    void set_promise () override {
        std::vector<int> answer_from_spi = spi_read();
        prms.set_value(map_function(answer_from_spi));
    }
};

std::vector<std::unique_ptr<obj>> objects;
for(auto &element : objects)
    element->set_promise();


text:
Q: How to start the autofill option from a cell in excell I have a field(cell): P2 and when I type 25 I need that value to be copied to cell B53 and from this cell B53 to start autofilling and increasing the value when cell C46 is not empty anymore. Let me explain that again : So when I put a value to P2 that should be copied to B53. After that when I fill cell C46 the cell B54 would be the increased value from cell B53
Example: I put 25 in cell P2...Then cell B53 become 25...Then I put something in cell C46 so the cell B54 is autofilled with value 26.
Thanks for your help. And do not hesitate to ask any questions that you have.

A: Put 25 in P2 or any value you need, and in B53 write =P2
In B54 write the following
=IF(C46<>0,B53+1,"")
or
=IF(NOT(ISBLANK(C46)),B53+1,"")
Depending on the value you write in C46 the result in B54 will be the value in P2 + 1 if C46 is not empty and nothing if C46 is empty.


text:
Q: deleting dynamic table rows in android in my app, i have created  table rows dynamically
in each table row, i provide an icon that will help the user help in deleting that specific row
how can i achieve this? any suggestions please
is there a better option than using setVisibility()?
i tried setTag() and setId(), but it doesn't seem to work after one row is deleted, since the id values remain same after deletion
hope my question is well understood

A: lets assume your layout is like this.
<TableRow>
<Icon>
</Icon>
</TableRow>

your icon view can be anything ImageView or ImageButton. since you din't post any xml. i am just referring as icon.
Now, how to access the table row to delete?
on the onClick event. you get access to the icon view.
  TableRow tr = (TableRow)iconview.getParent();

will give access to the parent view after which you can perform deletions on this view.


text:
Q: Is it possible to sync a Photos library hosted on external HD with iCloud? I have a ~90 GB Photos library on an external hard drive. Every time I want to access those photos, I need to have access to and to connect this hard drive. I was thinking about syncing with iCloud so:

*

*I can access a copy of the photos wherever I have an Internet connection.

*I would also have an offsite backup.
My question: Is it merely a matter of going into System Preferences → iCloud → and ticking the Photos box? If it is, I'm guessing I must have the external hard drive (where the Photos library it) connected when I do it, and must be ready to leave it connected for a while (maybe overnight) while it syncs with iCloud?

A:
Is it merely a matter of going into System Preferences → iCloud → and ticking the Photos box?

Yes.

If it is, I'm guessing I must have the external hard drive (where the Photos library it) connected when I do it, and must be ready to leave it connected for a while (maybe overnight) while it syncs with iCloud?

Yes,


text:
Q: Dynamically add TableRow to above of TableLayout I want to dynamically add TableRow to above of TableLayout. I use blow code:
In my activity:
TableLayout table = (TableLayout)ChatActivity.this.findViewById(R.id.tblChats);
        for(int i = 1; i < 10; ++i)
        {
            TableRow row = (TableRow)LayoutInflater.from(ChatActivity.this).inflate(R.layout.chat_row, null);
            ((TextView)row.findViewById(R.id.attrib_name)).setText("A");
            ((TextView)row.findViewById(R.id.attrib_value)).setText(i + "");
            table.addView(row);
        }
        table.requestLayout();

chat_row.xml:
<?xml version="1.0" encoding="utf-8"?>

<TableRow xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView android:id="@+id/attrib_name"
        android:textStyle="bold"/>

    <TextView android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>

</TableRow>

As you know these codes adds TableRow in the bottom of the TableLayout.
Is there any way to add it to the above of TableLayout?

A: yes you can add row as runtime in table layout.
use below code like chart.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout

xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tblChats"
android:layout_width="match_parent"
android:layout_height="match_parent">  </TableLayout>

and make activity like below ..
public class ChartActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_layout);
        TableLayout table = findViewById(R.id.tblChats);
        for (int i = 0; i < 5; i++) {

            TableRow row = new TableRow(this);
            TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(lp);
            TextView textView = new TextView(this);
            textView.setText("Name" + " " + i);
            EditText editText = new EditText(this);
            row.addView(textView);
            table.addView(row, i);
        }

    }
}

A: According to Android Team's answer I realized I must change this line:
table.addView(row);

to this:
table.addView(row, 0);


text:
Q: How to increase the number of /dev/mtd* in linux In my linux /dev/ folder, I have mtd0 - mtd7 and mtdblock0 - mtdblock7. I want to have more mtd devices here. What should I change when building the kernel?
Thanks

A: You need more mtd partitions. Upon boot, the kernel creates one mtd and one mtdblock under /dev for each. The MTD partitions are usually written in the board's BSP file. You can override that by passing the kernel a mtdparts option.
More info here. Also mtdinfo and /proc/mtd describe the start-end of each partition and its name.
EDIT:
An example of the mtd partition table is in arch/arm/mach-omap2/board-omap3beagle.c for the beagleboard here.
static struct mtd_partition omap3beagle_nand_partitions[] = {
/* All the partition sizes are listed in terms of NAND block size */
{
    .name       = "X-Loader",
    .offset     = 0,
    .size       = 4 * NAND_BLOCK_SIZE,
    .mask_flags = MTD_WRITEABLE,    /* force read-only */
},
{
    .name       = "U-Boot",
    .offset     = MTDPART_OFS_APPEND,   /* Offset = 0x80000 */
    .size       = 15 * NAND_BLOCK_SIZE,
    .mask_flags = MTD_WRITEABLE,    /* force read-only */
},
{
    .name       = "U-Boot Env",
    .offset     = MTDPART_OFS_APPEND,   /* Offset = 0x260000 */
    .size       = 1 * NAND_BLOCK_SIZE,
},
{
    .name       = "Kernel",
    .offset     = MTDPART_OFS_APPEND,   /* Offset = 0x280000 */
    .size       = 32 * NAND_BLOCK_SIZE,
},
{
    .name       = "File System",
    .offset     = MTDPART_OFS_APPEND,   /* Offset = 0x680000 */
    .size       = MTDPART_SIZ_FULL,
},

};
There are 5 partitions mtd0 to mtd4 with sizes hard-coded in the Kernel image.


text:
Q: Return rows that match certain Japanese characters in a Series I have a pandas dataframe with several columns in Japanese.
I would like to run a search that returns rows that contain certain Japanese characters.
ex.
find_str = 'バッグ'

I know I can't just use things like:
df[df.col1.str.contains(find_str)] or df[df.col1 == find_str]

How would I go about this? Like what encoding would I need to use, etc.?
                                           name
0                                                    ヴァラ
1             ALEXANDER WANG(アレキサンダーワン) クラッチバッグ パイソン【中古】
2                                                 ミューズトゥ
3                                                 ミューズトゥ
4                                               ローディーロック
5                                          バブーシュカクリスタルGG

I'd run something simple like:
df[df.name.str.contains('ゥ')]

which should return rows 2 and 3 but instead I get an empty result

A: For me working:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import pandas as pd

df = pd.read_csv('file.csv', encoding='utf-8')
find_str = u'バッグ'

m = df['name'].str.contains(find_str)
print (m)
0    False
1     True
2    False
3    False
4    False
5    False
Name: name, dtype: bool


text:
Q: Setting BooleanToVisibilityConverter to true depending on selected combo box value I need to add some logic to my code that will set the BooleanToVisibilityConverter to true or false depending on a selected value from a XAML combo box in my MVVM model. To complicate matters I actually have 2 combo boxes. The list displayed in combo box 2 depends on what value is selected in combo box 1
Combo box 1 XAML
<ComboBox Margin="103,6,0,24"
     x:Name="FirstOne"
     Grid.Column="1"
     DisplayMemberPath="SetCriteria"
     ItemsSource="{Binding CriteriaList}"
     SelectedItem="{Binding SelectedCriteriaLists, Mode=TwoWay}"/>

Combo box 1, code behind
public void SearchViewModel()
    {
        this.CriteriaList = new ObservableCollection<SearchCriteriaList>
        {
            new SearchCriteriaList {SetCriteria = "Date Range"},
            new SearchCriteriaList {SetCriteria = "Gateway"},
            new SearchCriteriaList {SetCriteria = "Direction"}
        };

              this.OperatorList = new ObservableCollection<SearchOperatorLists>();
        }

Combo box 2 XAML
 <ComboBox Margin="103,41,1,40"
                          x:Name="SecondOne"
                          Grid.Column="1"
                          Grid.RowSpan="2"
                          DisplayMemberPath="OperatorName"
                          ItemsSource="{Binding OperatorList}"/>

Combo box 2, code behind
private readonly List<SearchOperatorLists> dateOperatorList = new List<SearchOperatorLists>
    {
        new SearchOperatorLists {OperatorName = "Today"},
        new SearchOperatorLists {OperatorName = "Between"},
        new SearchOperatorLists {OperatorName = "Last Month"}
    };

    private readonly List<SearchOperatorLists> gatewayOperatorList = new List<SearchOperatorLists>
    {
        new SearchOperatorLists {OperatorName = "CCSUK"},
        new SearchOperatorLists {OperatorName = "MCP"},
        new SearchOperatorLists {OperatorName = "CNS"},
        new SearchOperatorLists {OperatorName = "Email"}
    };

    private readonly List<SearchOperatorLists> directionOperatorList = new List<SearchOperatorLists>
    {
        new SearchOperatorLists {OperatorName = "In"},
        new SearchOperatorLists {OperatorName = "Out"}
    };

    private SearchCriteriaList selectedCriteriaList;

OK so using an onPropertyChanged event whenever a value is selected in the FirstOne combo box (Date Range, Gateway or Direction) combo box 2 display the corresponding list (dateOperatorList, gatewayOperatorList, directionOperatorList)
My requirement is to capture a value in combo box 2, say "Between" and then set my BooleanToVisibilityConverter to true. Which in this case will display 2 date pickers.
Any pointers are much appreciated.

A: Rather use an object model where your primary item (first combo) has a Children property which contains the items for the second Combobox.
This would then make your second Combobox's Binding as:
<ComboBox Margin="103,41,1,40"
                      x:Name="SecondOne"
                      Grid.Column="1"
                      Grid.RowSpan="2"
                      DisplayMemberPath="OperatorName"
                      ItemsSource="{Binding SelectedCriteriaLists.Children}"/>

Much simpler and less of a maintenance issue in the long run if the lists of dependent objects change.


text:
Q: DumpCount in WER doesn't work precisely I work on a Windows 64-bit PC. My application launches 10+ instances of a 32-bit process with the same name, Proc.exe. These instances are launched very close in time; in a certain scenario they crash, also very close in time.
I try to collect crash dumps for these crashes, using WER. I use the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\Proc.exe, as explained in "Collecting User-Mode Dumps" MSDN article. I use the full dump (DumpType=2). In the target dump folder I obtain a number of dump files whose names differ by the PID number: Proc.exe.1836.dmp, Proc.exe.5428.dmp, etc.
The problem: the total number of the generated dump files is not always exactly according to the value of DumpCount, often there are more files, and their actual number varies from run to run. I saw up to 5 files for DumpCount=1, and up to 8 files for DumpCount=3.
I tried to work with the global LocalDumps settings (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps) instead of the per-process settings, and the results are similar.
It's important for me to control the number of the generated dump files, since the free disk space is very limited.
Do I miss something, or what I reported now is a bug in Windows?


text:
Q: pycharm with wrong PYTHONPATH? When I start a python console in PyCharm I do/see:

/usr/local/bin/python3.7 "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevconsole.py" --mode=client --port=59807
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['...snip_current_project_folder...'])
...
import os
os.environ.get("PYTHONPATH")
'/Applications/PyCharm CE.app/Contents/helpers/third_party/thriftpy:/Applications/PyCharm CE.app/Contents/helpers/pydev'

Which is not the contents of my PYTHONPATH.
The PYTHONPATH in my .bash_profile is fine. For example in the terminal, "echo $PYTHONPATH" is non-empty and I have verified is working for python3 in the command line to import a module.  Also I have seen Pycharm not do this to PYTHONPATH in the past.
MAC OS.
Thoughts?
I have tried deleting the .idea file and starting over for this project.
In regards to Hassan's interpreter suggestion.
It does seem like something is wrong with the environment, but that was a system installed python.  I tried switching it to an virtualenv and I tried making a new virtualenv via pycharm.  None of those seemed to show the PYTHONPATH in bash_profile making it to the interpreter.
Other variables in the bash_profile show up.  For example, I added to .bash_profile:

export HASSAN_JAN_2019_CHECK="test"

And after restarting pycharm I get:

import os
print(os.environ.get("PYTHONPATH"))

/Applications/PyCharm CE.app/Contents/helpers/third_party/thriftpy:/Applications/PyCharm CE.app/Contents/helpers/pydev

print(os.environ.get("HASSAN_JAN_2019_CHECK"))

test
Accumulated Evidences:

*

*PYTHONPATH works by hand in the terminal when starting the same interpreter that pycharm is using to load itself in Python Console.

*Switching the interpreter in pycharm does not seem to help.

*Adding a test export variable to the bash_profile that has the PYTHONPATH gets all the way to the os.environ.get correctly, but the PYTHONPATH itself does not make it unmodified.

A: I think because Pycharm uses virtualenv you are seeing this difference. See link below how you can set your paths in Pycharms
Installing, Uninstalling and Reloading Interpreter Paths


text:
Q: Saving values from a function call in a for loop I want to save the values from the function call in a txt file but I am getting the typeerror: expected a character buffer object
def printme( x ):
    "Function f(x) = x(x+2)"
    print x*(x+2)
    return

myfile = open('xyz.txt', 'w')
    for w in b:
        myfile.write('%d' (printme(w)))

myfile.close()

A: There are at least four problems with your code as posted, and none of them will demonstrate the error you're actually seeing.

First, there's an IndentationError:
myfile = open('xyz.txt', 'w')
    for w in b:
    myfile.write('%d' (printme(w)))

You can't randomly indent code wherever you want; the for statement follows the assignment statement, and the myfile.write call is supposed to be inside the for loop. So:
myfile = open('xyz.txt', 'w')
for w in b:
    myfile.write('%d' (printme(w)))

If you fix that, your next error will be a TypeError, but it will be for 'str' object is not callable, not anything about a character buffer object.
In Python, anything of the form foo (bar) is a function call—an attempt to call foo like a function, with bar as its only argument. So, this expression:
'%d' (printme(w))

… attempts to call the string '%d' as a function, passing the result of printme(w) as its only argument. That's obviously not going to work, because strings aren't callable like functions. Hence the exception.

You probably wanted to use the % operator there, like this:
'%d' % (printme(w))

That's close, but still not quite right, because (printme(w)) is not a tuple of one value. Tuples are created by commas, not by parentheses, so a tuple of one value has to have a comma in it. So:
'%d' % (printme(w),)

(You don't actually need a tuple here, because % has special handling for single values. But if you're trying to create a tuple, you should get it right, not get it wrong and have your code possibly work anyway…)

And now we're getting close, but we've got another problem: printme doesn't return a number, it prints a number, and then returns None. (That's the default value you get from any function that doesn't return something different.) So, the % operator will give you yet another TypeError, this time saying '%d" format: a number is required, not NoneType.
To fix that, you want to return the value instead of (or in addition to) printing it:
def printme( x ):
    "Function f(x) = x(x+2)"
    return x*(x+2)

Of course a function named printme that instead returns a value is a bit misleading, so you might want to rename it at this point…

If you fix that, then everything works. There is no TypeError saying expected a character buffer object anywhere.
Most likely, in your actual code, you're trying to write the value you got back from printme, without formatting it into a string first (with that % operator or otherwise). For example, if you do this:
myfile.write(printme(w))

… that's either trying to write None (if you didn't fix the last problem) or some number (if you did), neither of which is a string (or other "character buffer object"), hence the error.
To fix that, just use the code you showed us instead of different code.

Putting it all together, here's working code that does what you're apparently trying to do:
def printme( x ):
    "Function f(x) = x(x+2)"
    return x*(x+2)

myfile = open('xyz.txt', 'w')
for w in b:
    myfile.write('%d' % (printme(w),))

myfile.close()

A: I think this is what you want
def printme( x ):
    "Function f(x) = x(x+2)"
    return x*(x+2)

b = [1,2,3,4,5]

myfile = open('xyz.txt', 'w')

for w in b:
    myfile.write(str(printme(w)))
    myfile.write("\n")

# !!! EDIT !!!
myfile.close()


text:
Q: How can i get the sum of a line from a .txt file in powershell? So, I have a textfile "numbers.txt" like this:
2 3 4 5
5 6
6 7 7
6 88 9 67 4
65 76 979 8
6 88 5 4 23

My question is, how can i get the sum of each line?
What i tried to do:
$data=Get-Content -Delimiter " " numbers.txt
$data | % {
 $sum=0
 foreach($num in $_) {
 $sum+=$num
 }
 Write-Host $sum
 }

But it gives back weird numbers.
I dont know how to separate the different numbers in each line and get the sum of them.

A: Here's a fast and concise PSv4+ solution that utilizes LINQ:
(Get-Content numbers.txt).ForEach({
  [Linq.Enumerable]::Sum([int[]] ($_ -split ' '))
})

*

*(Get-Content numbers.txt) returns the input file's lines as an array of strings.

*.ForEach({ ... }) executes a script block ({ ...}) for each input line.

*

*[Linq.Enumerable]::Sum(...) sums the elements of an array (enumerable) of numbers.

*$_ -split ' ' splits the input line at hand ($_) into (string) tokens by spaces, and converts the result to an array of integers ([int[]]).
Here's a - slower - solution closer to what you attempted (works in PSv3- too):
Get-Content numbers.txt | ForEach-Object {  # Process each line.
  $sum = 0 # initialize the sum (implicitly of type [int])
  foreach ($num in $_ -split ' ') { # Process all tokens on the line.
    # Note: Because $sum is [int]-typed, adding the *string* token at
    #       hand implicitly converts it to [int].
    $sum += $num
  }
  $sum # Output the sum - do NOT use Write-Host to output DATA
}

Both solutions yield the following:
14     # 2 + 3 + 4 + 5
11     # 5 + 6
20     # ...
174
1128
126

As for what you tried:

Get-Content -Delimiter " " numbers.txt

This splits your entire file into a single array of number strings, ignoring line boundaries.
Instead, you must use Get-Content as-is in order to process the file line by line, and then split each line into space-separated tokens to sum up.

A: Turn it into a single array of numbers:
-split (get-content numbers.txt) | measure -sum | % sum

1473

Oops, sum each line:
get-content numbers.txt | foreach { -split $_ | measure -sum } | foreach sum

14
11
20
174
1128
126


text:
Q: .Length behavior vs .LongLength when array size is larger than Int32.MaxValue I'm looking for some documentation on the differences between an array's .Length and .LongLength properties.
Specifically, if the array's length is larger than Int32.MaxValue, will .Length throw an exception, return Int32.MaxValue, go negative, return 0?
(to clear up "possible duplicate" concerns: I'm not asking about the maximum length of an array, or the maximum size of a .NET CLR object. Assume a 64 bit system and a CLR version which supports large objects)

A: It is not possible to create a one dimensional array having more than 2,147,483,591 elements (for comparison, int.MaxValue is 2,147,483,647). OutOfMemoryException is thrown if an attempt is made to create an array with more elements. It means that the LongLength property is still useless and you can use the Length property instead.
I've tested it on the x64 platform using .NET 4.5. In order to create the array with 2,147,483,591 elements I've modified the configuration file and added:
<configuration>
    <runtime>
        <gcAllowVeryLargeObjects enabled="true" />
    </runtime>
</configuration>

Basically, I used this MSDN page to enable arrays that are greater than 2 (GB) in total size. The real limit for arrays:

The maximum index in any single dimension is 2,147,483,591
  (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and
  2,146,435,071 (0X7FEFFFFF) for other types.


text:
Q: How to hide DOM elements I have an html document which has the following structure (which I cannot change):

...

..

<div..<//div>
.../...

...

..

<div..<//div>
.../...
repeating

I have create the following code which successfully hides the h2 element based on the text taken from a field called searchTarget:

This successfully hides the header elements, but I want also the code to hide the next two  elements just underneath the header if the header is hidden.

A: JavasScript Siblings
nextsibling
function toggle_targets() {

        var searchValue = document.getElementById("searchTarget").value;
        var headers = document.getElementsByTagName('h2');
        for (i=0; i<headers.length; i++) {
                if (headers[i].textContent.includes(searchValue)) {
                        headers[i].style.display = "none";
                        headers[i].nextSibling.nextSibling.style.display = "none";
                        headers[i].nextSibling.style.display = "none";
                } else {
                        headers[i].style.display = "block";
                        headers[i].nextSibling.nextSibling.style.display = "block";
                        headers[i].nextSibling.style.display = "block";
                }
        }
}

A: You can try it with nextElementSibling to get the element's sibling as DOM element. This code hides the next two siblings of the selected h2 element. It does not matter which element a sibling is (input, div, ....).
function toggle_targets() {
        var searchValue = document.getElementById("searchTarget").value;
        var headers = document.getElementsByTagName('h2');
        for (i=0; i<headers.length; i++) {
                if (headers[i].textContent.includes(searchValue)) {
                        headers[i].style.display = "none";
                        headers[i].nextElementSibling.nextElementSibling.style.display = "none";
                        headers[i].nextElementSibling.style.display = "none";
                } else {
                        headers[i].style.display = "block";
                        headers[i].nextElementSibling.nextElementSibling.style.display = "block";
                        headers[i].nextElementSibling.style.display = "block";
                }
        }
}

Edit:  Added code example.

function toggle_targets() {
        var searchValue = "Hide me!";
        var headers = document.getElementsByTagName('h2');
        for (i=0; i<headers.length; i++) {
                if (headers[i].textContent.includes(searchValue)) {
                        headers[i].style.display = "none";
                        headers[i].nextElementSibling.nextElementSibling.style.display = "none";
                        headers[i].nextElementSibling.style.display = "none";
                } else {
                        headers[i].style.display = "block";
                        headers[i].nextElementSibling.nextElementSibling.style.display = "block";
                        headers[i].nextElementSibling.style.display = "block";
                }
        }
}

Hide me! (on click)

D1

D2

Headline 2

D3

D4

Headline 3

D5

D6

A: Try this one
function toggle_targets() {
  const search = document.getElementById("searchTarget");

  for (const header of document.getElementsByTagName("h2")) {
    const content = header.textContent || '';
    const includeSearchText = content.includes(search.value)

    const next1 = header.nextElementSibling;
    const next2 = next1.nextElementSibling;

    for (const el of [header, next1, next2]) {
      if (!el) return

      el.style.display = includeSearchText ? 'none' : 'display'
    }
  }
}

A: If the pattern is regular, i.e. it's always a H2 and two divs, you could use an adjacent sibling combinator to select all the elements, and then iterate through the found elements and hide the ones you need:

const searchValue = 'header',
  hiddens = document.querySelectorAll('h2, h2 + div, h2 + div + div');
for (let n = 0, eN = hiddens.length; n < eN; n++) {
  if (n % 3 === 0 && hiddens[n].textContent.includes(searchValue) === false) {
    n += 2; // No keyword in this header, jump to the next header
    continue;
  }
  hiddens[n].style.display = 'none';
}

Hidden header 1

Hidden div 1

Hidden div 2

Visible div 3

Visible div 4

Head element 2

Visible Head div 5

Visible header div 6

Visible div 7

Visible div 8

Yet another header 3

Hidden div 9

Hidden div 10

Visible div 11


text:
Q: wordpress child theme styles.css does not want to override parent style.css My child theme styles.css does not want to override parent style.css.
I am working with the wordpress theme twenty fourteen .
I have created a child theme, and through research have found the following piece of code...
require_once( get_stylesheet_directory() . '/my_included_file.php' );

My question is where exactly does this code go? I read in the functions.php. So do I put it in the first line of the page.
I want my child theme stylesheet to take priority over my parent stylesheet.
Thank you any help would be great..

A: You should not need that code. Once you activate the child theme, that stylesheet will be included after the parent theme's and will therefore override those in the parent theme's stylesheet.
Read more about Child Themes at the WordPress Codex.

A: You can directly import your parent-theme style.css by @import url('../parent-theme-name/style.css'); in your child-theme style.css and below it write your own css code or override the parent-theme css code.
you can also use this plugin to create child theme http://wordpress.org/plugins/orbisius-child-theme-creator/


text:
Q: How to re-use a bunch of code when 2 objects are involved in Swift I have faced this issue many times, but finally asking how to solve this in Swift and iOS. I have the same code block that runs against 2 different kind of objects, but I can't figure out, how to apply the code to either of the 2 object types with it being strongly typed. In other languages (like PHP) I would just put a generic var myVar = nil at the top of block and then set that to one or the other of those objects, then hang the code off of it, but swift won't let me do that.
How do you handle this programming situation in Swift/iOS?
static func entitySetup(jsonObject: JSON, object: MyCoreDataEntityObject?) {
    if let existingObj = object { // existingObj = a MyCoreDataEntityObject
        existingObj.setValue(jsonObject["firstName"].stringValue, forKey: "firstName")
        existingObj.setValue(jsonObject["lastName"].stringValue, forKey: "lastName")
        existingObj.setValue(jsonObject["address"].stringValue, forKey: "address")
        existingObj.setValue(jsonObject["phone"].stringValue, forKey: "phone")
    } else { // newObj = NSManagedObject
        let entity = NSEntityDescription.entity(forEntityName: "MyCoreDataEntityObject", in: self.context)
        let newObj = NSManagedObject(entity: entity!, insertInto: self.context)
        newObj.setValue(jsonObject["firstName"].stringValue, forKey: "firstName")
        newObj.setValue(jsonObject["lastName"].stringValue, forKey: "lastName")
        newObj.setValue(jsonObject["address"].stringValue, forKey: "address")
        newObj.setValue(jsonObject["phone"].stringValue, forKey: "phone")
    }
    do {
        try self.context.save()
    } catch let error as NSError  {
        print("ERROR: Could not save \(error), \(error.userInfo)")
        completionHandler(false)
    }
}

A: Since both objects are NSManagedObject, you can do this:
let mangedObject: NSManagedObject
if let existingObj = object {
    managedObject = existingObj
} else {
    let entity = NSEntityDescription.entity(forEntityName: "MyCoreDataEntityObject", in: self.context)
    managedObject = NSManagedObject(entity: entity!, insertInto: self.context)
}

managedObject.setValue(jsonObject["firstName"].stringValue, forKey: "firstName")
managedObject.setValue(jsonObject["lastName"].stringValue, forKey: "lastName")
managedObject.setValue(jsonObject["address"].stringValue, forKey: "address")
managedObject.setValue(jsonObject["phone"].stringValue, forKey: "phone")

do {
    try self.context.save()
} catch let error as NSError  {
    print("ERROR: Could not save \(error), \(error.userInfo)")
    completionHandler(false)
}

And as suggested, the four lines calling setValue can be simplified as:
for key in ["firstName", "lastName", "address", "phone"] {
    managedObject.setValue(jsonObject[key].stringValue, forKey: key)
}

A: Try this
static func entitySetup(jsonObject: JSON, object: MyCoreDataEntityObject?) {

    let newObject = object ?? NSManagedObject(entity: NSEntityDescription.entity(forEntityName: "MyCoreDataEntityObject", in: self.context)!, insertInto: self.context)

    for key in ["firstName", "lastName", "address", "phone"] {
        newObject.setValue(jsonObject[key].stringValue, forKey: key)
    }

    do {
        try self.context.save()
    } catch let error as NSError  {
        print("ERROR: Could not save \(error), \(error.userInfo)")
        completionHandler(false)
    }
}


text:
Q: Почему не работает считывание координаты при нажатии мышкой по scene? Почему не работает считывание координаты при нажатии мышкой по scene?
 def mousePressEvent(self, event):

        x = event.scenePos().x()
        y = event.scenePos().y()
        print(x, y)

Ниже представлен весь код:
import sys
    from PyQt5 import QtWidgets
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *

    class Editor(QMainWindow):
        def __init__(self):
            super().__init__()
            self.state = ""
            self.resize(500, 500)
            self.setWindowTitle('GraphicsEditor')

            self.grview = QGraphicsView()
            self.scene = QGraphicsScene(self.grview)
            self.scene.setSceneRect(0, 0, 520, 520)
            self.grview.setScene(self.scene)

            self.pen = QPen(Qt.red)
            self.brush = QBrush(Qt.green)

            self.set_figure()

            self.trash_action.triggered.connect(self.clear)
            self.line_action.triggered.connect(self.click_line)
            self.rect_action.triggered.connect(self.click_rect)
            self.circle_action.triggered.connect(self.click_circle)

            self.centralWidget = QWidget()
            self.setCentralWidget(self.centralWidget)
            layout = QVBoxLayout(self.centralWidget)
            layout.addWidget(self.grview)

            self.show()

        def mousePressEvent(self, event):

            x = event.scenePos().x()
            y = event.scenePos().y()
            print(x, y)

            if self.state == "rect":
                rect = self.scene.addRect(100, 100,  100, 100, self.pen, self.brush)
                rect.setFlag(QGraphicsItem.ItemIsMovable)
            elif self.state == "circle":
                circle = self.scene.addEllipse(100, 100, 100, 100, self.pen, self.brush)
                circle.setFlag(QGraphicsItem.ItemIsMovable)
            elif self.state == "line":
                line = self.scene.addLine(10, 10, 100, 100, self.pen)
                line.setFlag(QGraphicsItem.ItemIsMovable)
            super(Editor, self).mousePressEvent(event)

        def mouseMoveEvent(self, event):
            print("mouse movement")
            super(Editor, self).mouseMoveEvent(event)

        def set_figure(self):
            self.figure_toolbar = QToolBar("figure")
            self.figure_toolbar.setIconSize(QSize(14, 14))
            self.basicToolBar = self.addToolBar(self.figure_toolbar)
            #кнопка line
            self.line_action = QAction(QIcon("images/line.png"), 'line', self)
            self.line_action.setStatusTip("line")
            self.figure_toolbar.addAction(self.line_action)
            #кнопка rectangle
            self.rect_action = QAction(QIcon("images/rect.png"), 'rectangle', self)
            self.rect_action.setStatusTip("rect")
            self.figure_toolbar.addAction(self.rect_action)
            #кнопка круг
            self.circle_action = QAction(QIcon("images/circle.ico"), 'circle', self)
            self.circle_action.setStatusTip("circle")
            self.figure_toolbar.addAction(self.circle_action)
            #кнопка select
            self.select_action = QAction(QIcon("images/select.ico"), 'select', self)
            self.select_action.setStatusTip("select")
            self.figure_toolbar.addAction(self.select_action)
            #кнопка очистки
            self.trash_action = QAction(QIcon("images/trash.png"), 'trash', self)
            self.trash_action.setStatusTip("trash")
            self.figure_toolbar.addAction(self.trash_action)

        def click_line(self):
            self.state = "line"

        def click_rect(self):
            self.state = "rect"

        def click_circle(self):
            self.state = "circle"

        def clear(self):
            self.scene.clear()

    def main():
        app = QtWidgets.QApplication(sys.argv)
        g = Editor()
        sys.exit(app.exec_())

    if __name__ == "__main__":
        main()

A: С некоторыми разъяснениями по вашему вопросу можете ознакомиться
здесь Cцена и предствление в pyqt5
Особое внимание обратите на то, что
Графическое представление основано на декартовой системе координат,
у представлений, сцен и примитивов есть свои собственные координаты.
import sys
import math                                                     ###
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
class GraphicsScene(QGraphicsScene):
    clicked = pyqtSignal(QPointF)

    def drawBackground(self, painter, rect):
        l = min(rect.width(), rect.height()) / 30

        x_left = QPointF(rect.left(), 0)
        x_right = QPointF(rect.right(), 0)
        painter.drawLine(x_left, x_right)

        right_triangle = QPainterPath()
        right_triangle.lineTo(-0.5 * math.sqrt(3) * l, 0.5 * l)
        right_triangle.lineTo(-0.5 * math.sqrt(3) * l, -0.5 * l)
        right_triangle.closeSubpath()
        right_triangle.translate(x_right)

        painter.setBrush(QColor("black"))
        painter.drawPath(right_triangle)

        y_top = QPointF(0, rect.top())
        y_bottom = QPointF(0, rect.bottom())
        painter.drawLine(y_top, y_bottom)

        top_triangle = QPainterPath()
        top_triangle.lineTo(.5*l, -0.5 * math.sqrt(3) * l)
        top_triangle.lineTo(-.5*l, -0.5 * math.sqrt(3) * l)
        top_triangle.closeSubpath()
        top_triangle.translate(y_bottom)

        painter.setBrush(QColor("black"))
        painter.drawPath(top_triangle)

    def mousePressEvent(self, event):
        sp = event.scenePos()
        self.clicked.emit(sp)
        super().mousePressEvent(event)
#  +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

class Editor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.state = ""
        self.resize(520, 550)

        self.setWindowTitle('GraphicsEditor')

        self.grview = QGraphicsView()
        self.grview.scale(1, -1)                                       # +++

#        self.scene = QGraphicsScene(self.grview)                      # ---
        self.scene = GraphicsScene()                                   # +++
        self.scene.clicked.connect(self.handle_clicked)                # +++

#        self.scene.setSceneRect(0, 0, 500, 500)
        self.scene.setSceneRect(-250, -250, 500, 500)                  # +++

        self.grview.setScene(self.scene)

        self.pen = QPen(Qt.red)
        self.brush = QBrush(Qt.green)

        self.set_figure()

        self.trash_action.triggered.connect(self.clear)
        self.line_action.triggered.connect(self.click_line)
        self.rect_action.triggered.connect(self.click_rect)
        self.circle_action.triggered.connect(self.click_circle)

        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        layout = QVBoxLayout(self.centralWidget)
        layout.setContentsMargins(0, 0, 0, 0)                           # +
        layout.addWidget(self.grview)

        self.show()

    def mousePressEvent(self, event):
###
#        x = event.scenePos().x()
#        y = event.scenePos().y()
#        print(x, y)
        print(f'event -> {event}, event.pos={event.pos()}')

        if self.state == "rect":
            rect = self.scene.addRect(100, 100,  100, 100, self.pen, self.brush)
            rect.setFlag(QGraphicsItem.ItemIsMovable)
        elif self.state == "circle":
            circle = self.scene.addEllipse(100, 100, 100, 100, self.pen, self.brush)
            circle.setFlag(QGraphicsItem.ItemIsMovable)
        elif self.state == "line":
            line = self.scene.addLine(10, 10, 100, 100, self.pen)
            line.setFlag(QGraphicsItem.ItemIsMovable)
        super(Editor, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        print("mouse movement")
        super(Editor, self).mouseMoveEvent(event)

    def set_figure(self):
        self.figure_toolbar = QToolBar("figure")
        self.figure_toolbar.setIconSize(QSize(14, 14))
        self.basicToolBar = self.addToolBar(self.figure_toolbar)
        #кнопка line
        self.line_action = QAction(QIcon("images/line.png"), 'line', self)
        self.line_action.setStatusTip("line")
        self.figure_toolbar.addAction(self.line_action)
        #кнопка rectangle
        self.rect_action = QAction(QIcon("images/rect.png"), 'rectangle', self)
        self.rect_action.setStatusTip("rect")
        self.figure_toolbar.addAction(self.rect_action)
        #кнопка круг
        self.circle_action = QAction(QIcon("images/circle.ico"), 'circle', self)
        self.circle_action.setStatusTip("circle")
        self.figure_toolbar.addAction(self.circle_action)
        #кнопка select
        self.select_action = QAction(QIcon("images/select.ico"), 'select', self)
        self.select_action.setStatusTip("select")
        self.figure_toolbar.addAction(self.select_action)
        #кнопка очистки
        self.trash_action = QAction(QIcon("images/trash.png"), 'trash', self)
        self.trash_action.setStatusTip("trash")
        self.figure_toolbar.addAction(self.trash_action)

    def click_line(self):
        self.state = "line"

    def click_rect(self):
        self.state = "rect"

    def click_circle(self):
        self.state = "circle"

    def clear(self):
        self.scene.clear()
# +++
    def handle_clicked(self, p):                                       # +++
        print(f"clicked scene: x={p.x()}, y={p.y()}")                  # +++

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    g = Editor()
    sys.exit(app.exec_())


text:
Q: Named pipes in C reading weird result I'm implementing my first program using named pipes in C on windows.
I'm trying to implement Monte Carlo method for number pi.
When creating random numbers everything is generated fine. Then I send numbers and receive it on main thread.
There, somehow, data looks very weird..
It seems the problem is in ConnectNamedPipe as it returns false
Also if I change all the path's with handles, program hangs at ConnectNamedPipe..
It looks something like this:
z:-1.#QNAN0, x:-1.#QNAN0, y:0.000000
z:1.#INF00, x:310579431956368060000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:-0.000000, y:0.000000
z:1.#INF00, x:833189623448552210000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:1.#INF00, x:315573513832673330000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000.000000, y:0.000000
z:-1.#QNAN0, x:-1.#QNAN0, y:0.000000
z:1.#INF00, x:835455692328165330000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000
z:4.000000, x:2.000000, y:0.000000
z:0.000000, x:0.000000, y:0.000000

when it should be something like:
z:4.00000 x:0.475953, y:0.983213
Here is the code for the thread where the numbers are being generated:
 HANDLE readpipe, writepipe;

    int a;
    BOOL   fConnected = FALSE;
    LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe1");

  unsigned int __stdcall stage1(void * param) {
    srand(time(NULL));
    printf("creating...\n");
    writepipe = CreateNamedPipe(
        lpszPipename, // name of the pipe
        PIPE_ACCESS_OUTBOUND, // 1-way pipe -- send only
        PIPE_TYPE_MESSAGE,
        PIPE_UNLIMITED_INSTANCES,
        1024,
        1024,
        0, // use default wait time
        NULL // use default security attributes
    );
    printf("created...\n");
     fConnected = ConnectNamedPipe("\\\\.\\pipe\\mynamedpipe1", NULL) ?
         TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);

         if(!fConnected)
         {
            printf("Not working...");
         }
    printf("connected...\n");
    double y[a];
    DWORD length;
    double x[a];
    int i;
    for (i = 0; i < a; i++)
    {
        x[i] = ((double)rand()) / (double)RAND_MAX;
        y[i] = ((double)rand()) / (double)RAND_MAX;
        printf("%f  %f\n",x[i],y[i]);

    }
    printf("writing...\n");

    /*PIPE*/
    WriteFile( writepipe, x, sizeof(x), &length, 0);
    WriteFile( writepipe, y, sizeof(y), &length, 0);
    CloseHandle( writepipe );
    /*PIPE*/

    return 0;
}

and here is the main thread:
int main( int argc, char* argv[] ){
    a = atoi(argv[1]);
    srand (time(NULL));

    /*PIPE*/
    HANDLE thread1,thread2;

    /*CreatePipe( &readpipe, &writepipe, 0, 0 );*/
    /*PIPE*/

    thread1 = (HANDLE)_beginthreadex( 0, 0, &stage1, 0, 0, 0 );
    WaitForSingleObject( thread1, INFINITE );
    printf("reading.1111..\n");
    CloseHandle(thread1);
    readpipe = CreateFile( lpszPipename, GENERIC_READ,0,               NULL,           OPEN_EXISTING,  0,NULL);
    DWORD length;
    double x[a];
    double y[a];
    printf("reading...\n");

    ReadFile( readpipe, x, sizeof(x), &length, 0);
    ReadFile( readpipe, y, sizeof(y), &length, 0 );

    double z = 0.0;
    int n=0;
    int N=0;
    int i;
    for(i=0;i<a;i++)
    {
        z = x[i] * x[i] + y[i] * y[i];
        printf("z:%f, x:%f, y:%f\n",z,x[i],y[i]);
        if (z < 1) {
            n++;
        }
        N++;
    }

    CloseHandle( readpipe );

    printf("%d %d\n",n,N);
    double result = ((double)n / (double)N) * 4;
    printf("%f\n", result);
    getchar();

    return 0;
}

A: Call CreateNamedPipe in main function before you begin your thread. That should work.


text:
Q: How to integrate OpenAPI into Azure API Management using Azure DevOps CI & CD pipeline I have created an Azure API Management instance. I want to integrate OpenAPI into Azure API Management using Azure DevOps CI & CD pipelines.
For each release, I want to generate the OpenAPI spec from the code automatically. How can I build on this OpenApi spec to set up Azure API Management with all required version sets, apis, products, tags, users, subscriptions, certificates, and policies?

A: Here is the Sample Document where you can Automate Open API to APIM using CI/CD pipelines

https://www.domstamand.com/automating-your-openapi-updates-to-api-management-through-your-cicd-pipeline/

we need to use the Swashbuckle CLI which can be use to retrieve the Swagger/OpenAPI JSON directly from the application's startup assembly, and write it to a file. Follow the configuration to add the CLI to your source control repository so you can restore the tool and use it in your CI build definition.

A: Indeed you can use the Swashbuckle CLI to generate the OpenApi spec file.
You can use this devops extension to easily configure your API Management API's through your CICD pipeline: https://marketplace.visualstudio.com/items?itemName=stephane-eyskens.apim


text:
Q: "ImportError: No module named exceptions" when running Celery I'm attempting to run a Django app that uses Celery and I'm receiving the following error:
    import djcelery
  File "/Library/Python/2.7/site-packages/djcelery/__init__.py", line 25, in <module>
    from celery import current_app as celery  # noqa
  File "/Library/Python/2.7/site-packages/celery/__compat__.py", line 135, in __getattr__
    module = __import__(self._object_origins[name], None, None, [name])
  File "/Library/Python/2.7/site-packages/celery/_state.py", line 18, in <module>
    from celery.utils.threads import LocalStack
  File "/Library/Python/2.7/site-packages/celery/utils/__init__.py", line 24, in <module>
    from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning
  File "/Library/Python/2.7/site-packages/celery/exceptions.py", line 15, in <module>
    from billiard.exceptions import ( # noqa
ImportError: No module named exceptions

billiard is installed and the exceptions module does exist, and I'm able to import billiard.exceptions via Python's interactive prompt without issues. It seems that celery is failing to import billiard. Any ideas?


text:
Q: Regular Expression to select first five CSVs from a string I have a CSV string like apple404, orange pie, wind\,cool, sun\\mooon, earth, in Java. To be precise each value of the csv string could be any thing provided commas and backslash are escaped using a back slash.
I need a regular expression to find the first five values. After  some goggling I came up with the following. But it wont allow escaped commas within the values.
Pattern pattern = Pattern.compile("([^,]+,){0,5}");
Matcher matcher = pattern.matcher("apple404, orange pie, wind\\,cool, sun\\\\mooon, earth,");
    if (matcher.find()) {
        System.out.println(matcher.group());
    } else {
        System.out.println("No match found.");
    }

Does anybody know how to make it work for escaped commas within values?

A: Following negative look-behind based regex will work:
 Pattern pattern = Pattern.compile("(?:.*?(?<!(?:(?<!\\\\)\\\\)),){0,5}");

However for full fledged CSV parsing better use a dedicated CSV parser like JavaCSV.

A: This regular expression works well. It also properly recognizes not only backslash-escaped commas, but also backslash-escaped backslashes. Also, the matches it produces do not contain the commas.
/(?:\\\\|\\,|[^,])*/g

(I am using standard regular expression notation with the understanding that you would replace the delimiters with quote marks and double all backslashes when representing this regular expression within a Java string literal.)
example input

"apple404, orange pie, wind\,cool, sun\\,mooon, earth"

produces this output

*

*"apple404"

*" orange pie"

*" wind\,cool"

*" sun\\"

*"mooon"
Note that the double backslash after "sun" is escaped and therefore does not escape the following comma.
The way this regular expression works is by atomizing the input into longest sequences first, beginning with double backslashes (treating them as one possible multi-byte character value alternative), followed by escaped commas (a second possible multi-byte character alternative), followed by any non-comma value. Any number of these atoms are matched, followed by a literal comma.
In order to obtain the first N fields, one may simply splice the array of matches from the previous answer or surround the main expression in additional parentheses, include an optional comma in order to match the contents between fields, anchor it to the beginning of the string to prevent the engine from returning further groups of N fields, and quantify it (with N = 5 here):
/^((?:\\\\|\\,|[^,])*,?){0,5}/g

Once again, I am using standard regular expression notation, but here I will also do the trivial exercise of quoting this as a Java string:
"^((?:\\\\\\\\|\\\\,|[^,])*,?){0,5}"

This is the only solution on this page so far which actually answers both parts of the precise requirements specified by the OP, "...commas and backslash are escaped using a back slash." For the input fi\,eld1\\,field2\\,field3\\,field4\\,field5\\,field6\\,, it properly matches only the first five fields fi\,eld1\\,field2\\,field3\\,field4\\,field5\\,.
Note: my first answer made the same assumption that is implicitly part of the OP's original code and example data, which required a comma to be following every field. The problem was that if input is exactly 5 fields or less, and the last field not followed by a comma (equivalently, by an empty field), then final field would not be matched. I did not like this, and so I updated both of my answers so that they do not require following commas.
The shortcoming with this answer is that it follows the OP's assumption that values between commas contain "anything" plus escaped commas or escaped backslashes (i.e., no distinction between strings in double quotes, etc., but only recognition of escaped commas and backslashes). My answer fulfills the criteria of that imaginary scenario. But in the real world, someone would expect to be able to use double quotes around a CSV field in order to include commas within a field without using backslashes.
So I echo the words of @anubhava and suggest that a "real" CSV parser should always be used when handling CSV data. Doing otherwise is just being a script kiddie and not in any way truly "handling" CSV data.

A: You can use String.split() here. By specifying the limit as 6 the first five elements (index 0 to 4) would always be the first five column values from your CSV string. If in case any extra column values are present they would all overflow to index 5.
The regex (?<!\\\\), makes sure the CSV string is only split at a , comma not preceded with a \.
String[] cols = "apple404, orange pie, wind\\,cool, sun\\\\mooon, earth, " +
                "mars, venus, pluto".split("(?<!\\\\),", 6);

System.out.println(cols.length); // 6
System.out.println(Arrays.toString(cols));
// [apple404,  orange pie,  wind\,cool,  sun\\mooon,  earth,  mars, venus, pluto]

System.out.println(cols[4]); // 5th = earth
System.out.println(cols[5]); // 6th discarded = mars, venus, pluto


text:
Q: "XMLHttpRequest cannot load" error despite apparently identical file Ok this is just crazy.
A friend of mine is testing out a JavaScript/jQuery stock widget for me.  The content of the HTML file he used to test it couldn't be much more simple.  It's these two lines:

For him this throws the error "[Error] XMLHttpRequest cannot load http://quandl.io/widgets/data/us-fundamentals.php?ticker=MSFT&indicator=REVENUE. Origin null is not allowed by Access-Control-Allow-Origin."
He sent me his file, and I get the same error.  However, oddly in TextWrangler (a plain text editing app), the code in his file appears like this:

However, if I take that code and paste it in a new TextWrangler doc the code looks like this:

And get this:  If I save that new file with the exact same code as the other file, the script executes with no problem.  Both of these files are being executed from the same place (my local machine).  Both, according to the properties I can inspect, are plain HTML files (no weird styling information I can see).  It's odd, to say the least.
EDIT 1:  Both files are on my local computer which is running Safari, OSX.  Though I know this is not 100% kosher for StackOverflow, this problem is likely file-specific, so I'm posting here a link to the files.  (But from what I can tell they are both vanilla text files with .html extensions and the same content... which is why this is so confusing)

A: I suspect that although you're loading the file from your "local machine" in both cases, in the one case you're doing it by double-clicking the file in your file explorer and getting a file:// URL, and in the other case you're doing it by opening the file from a locally-running web server process via a http:// or https:// URL.
It matters, because many browsers (such as Chrome) disallow all XMLHttpRequest calls from pages loaded over file:// URLs, on the basis that all origins are "cross-origin" and so denied by the Same Origin Policy. So if you load the file from a file:// URL, XHR will fail, but if you load it via http:// or https://, it may work.


text:
Q: Masonry JS show items first on resize correctly Problem: (All .items had absolute and top 0 => overlaps)
Its first show correcty when I resize the window.

JavaScript (http://masonry.desandro.com/):
$(document).ready(function() {
    var container = document.querySelector(\'#container\');
    var msnry = new Masonry( container, {
         itemSelector: \'.item\',
         columnWidth: container.querySelector(\'.grid-sizer\')
    });
 });

HTML:

CSS:
#container {
  background: none;
  width: 100%;
}

#container:after {
  content: '';
  display: block;
  clear: both;
}

#container .item img {
    max-width: 100%;
    height: auto;
    display: block;
}

@media screen and (max-width: 480px) {
    #container .item,
    #container .grid-sizer {
        width: 49%;
        margin: 0.5% 0.5% 0 0.5%;
    }
}

@media (min-width: 480px) {
    #container .item,
    #container .grid-sizer {
        width: 32.3%;
        margin: 0.5% 0.5% 0 0.5%;
    }
}

@media screen and (min-width: 768px) and (min-width: 992px) {
    #container .item,
    #container .grid-sizer {
        width: 24%;
        margin: 0.5% 0.5% 0 0.5%;
    }
}

@media screen and (min-width: 992px) and (min-width: 1200px) {
    #container .item,
    #container .grid-sizer {
        width: 11.5%;
        height: auto;
        margin: 0.5% 0.5% 0 0.5%;
    }
}

Thank you very much!

A: Try to look for articles about ResponsiveUI - that will give you much usefull info. "autoscaling" could be done with next code:
.wrapper img {
 width: 100%;
 max-width: 100%
 height: 100%;
}


text:
Q: Pylons error "No object (name: request) has been registered for this thread" with debug = false I'm unable to access the request object in my Pylons 0.9.7 controller when I set debug = false in the .ini file. I have the following code:
def run_something(self):
    print('!!! request = %r' % request)
    print('!!! request.params = %r' % request.params)
    yield 'Stuff'

With debugging enabled this works fine and prints out:
!!! request = <Request at 0x9571190 POST http://my_url>
!!! request.params = UnicodeMultiDict([... lots of stuff ...])

If I set debug = false I get the following:
!!! request = <paste.registry.StackedObjectProxy object at 0x4093790>
Error - <type 'exceptions.TypeError'>: No object (name: request) has been registered for this thread

The stack trace confirms that the error is on the print('!!! request.params = %r' % request.params) line.
I'm running it using the Paste server and these two lines are the very first lines in my controller method.
This only occurs if I have yield statements in the method (even though the statements aren't reached). I'm guessing Pylons sees that it's a generator method and runs it on some other thread. My questions are:

*

*How do I make it work with debug = false ?

*Why does it work with debug = true ? Obviously this is quite a dangerous bug, since I normally develop with debug = true, so it can go unnoticed during development.

A: You should not yield from action directly. Try making inner function and returning func():
def run_something(self):
    request = pylons.request._current_obj()
    def func():
        print('!!! request = %r' % request)
        print('!!! request.params = %r' % request.params)
        yield 'Stuff'
    return func()

A: When you set up your middleware, enable streaming support in RegistryManager:
app = RegistryManager(app, streaming=True)

This keeps the registry (aoo_globals etc.) alive until your response has finished iterating.