EzDevInfo.com

amp

A non-blocking concurrency framework for PHP applications amphp – amphp/amp amp is a non-blocking concurrency framework for php applications.

Xcode Singleton Undeclared Identifier amp

I'm following a tutorial on creating a weather app for iOS. After a while, I've encountered an error which is dispatch_once(&onceToken, ^{ use of undeclared identifier 'amp'.

Can anyone tell me why this is happening? This is the tutorial: Building a Weather Application


Source: (StackOverflow)

Ampersand (& amp;) not escaping in DOM generated a href

Here's my question. I need to create an a href = (..) using DOM and the href should contains some ampersand.

What I did:

 var anchor = document.createElement('a');   
     var link = "../php/page.php?id=100&mode=edit";  
     anchor.setAttribute("href", link);  
     parent.appendChild(anchor);

The problem I have is that when I try to click on the link the & amp; remains and it's not escaped to and as it should.


Source: (StackOverflow)

Advertisements

Number of AMPs consumed by a session in Teradata

I am new to teradata. I have a Stored Procedure which is taking lot of time on server. I just want to know How many AMPs it is using. I have the session id of the Process and only the procedure will be running in that session.So, with the session id available, can I query something on DBC tables and know how many AMPs are being used for that session.

Thanks in advance


Source: (StackOverflow)

Remove amp; from url with htaccess

Hello how can I remove amp; from this url with htaccess

http://www.mywebsite.com/forum/viewtopic.php?f=144&t=14177

to make it output like this

http://www.mywebsite.com/forum/viewtopic.php?f=144&t=14177

All help appericated


Source: (StackOverflow)

Java String Replace '&' with & but not & to &

I have a large String in which I have & characters used available in following patterns -

A&B
A & B
A& B
A &B
A&B
A & B
A& B
A &B

I want to replace all the occurrences of & character to & While replacing this, I also need to make sure that I do not mistakenly convert an & to &. How do I do that in a performance savvy way? Do I use regular expression? If yes, please can you help me to pickup the right regular expression to do the above?

I've tried following so far with no joy:

data = data.replace(" & ", "&"); // doesn't replace all &
data = data.replace("&", "&");   // replaces all &, so & becomes &

Source: (StackOverflow)

ASP Request.QueryString doesn't html decode "&" from URL query string

In ASP having this URL:

http://www.example.com?foo=1&bar=2

Request.QueryString["bar"] returns NULL

The URL is a map area "href" link which I have assigned like so:

PolygonHotSpot p = new PolygonHotSpot();
p.NavigateUrl = http://www.example.com?foo=1&bar=2

ASP automatically HTML encodes the URL for the href, but it is not HTML decoding it again in the request therefore query string "bar" is not found.

Now I am using IIS URL Rewrite 2 module. Maybe this module is causing the problem? What can I do to solve it? I have tried using URL rewrite rules but couldn't figure our how or if it is the proper way.

Thank you.


Source: (StackOverflow)

C++ amp atomics

I am rewriting an algorithm in C++ AMP and just ran into an issue with atomic writes, more specifically atomic_fetch_add, which apparently is only for integers?

I need to add a double_4 (or if I have to, a float_4) in an atomic fashion. How do I accomplish that with C++ AMP's atomics?

Is the best/only solution really to have a lock variable which my code can use to control the writes? I actually need to do atomic writes for a long list of output doubles, so I would essentially need a lock for every output.

I have already considered tiling this for better performance, but right now I am just in the first iteration.

EDIT: Thanks for the quick answers already given. I have a quick update to my question though.

I made the following lock attempt, but it seems that when one thread in a warp gets past the lock, all the other threads in the same warp just tags along. I was expecting the first warp thread to get the lock, but I must be missing something (note that it has been quite a few years since my cuda days, so I have just gotten dumb)

parallel_for_each(attracting.extent, [=](index<1> idx) restrict(amp)
{
   .....
   for (int j = 0; j < attracted.extent.size(); j++)
   {
      ...
      int lock = 0; //the expected lock value
      while (!atomic_compare_exchange(&locks[j], &lock, 1));
      //when one warp thread gets the lock, ALL threads continue on
      ...
      acceleration[j] += ...; //locked write
      locks[j] = 0; //leaving the lock again
   }
});

It is as such not a big problem, since I should write into a shared variable at first and only write it to global memory after all threads in a tile have completed, but I just don't understand this behavior.


Source: (StackOverflow)

LoopingCall AMP commands

Why do I get an error while trying to implement LoopingCall function calling AMP commands?

from twisted.protocols.amp import AMP
from twisted.python.log import startLogging, err
from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from sys import stdout

import commands

startLogging(stdout)


class MyAMP:

    def __init__(self, host, port):
        destination = TCP4ClientEndpoint(reactor, host, port)
        self.protocol = AMP()
        self.d = connectProtocol(destination, self.protocol)

    def say(self):
        return self.protocol.callRemote(commands.Say,
                                   phrase='Hello world')


def loop(myamp):
    myamp.say()


def main(host, port):
    myamp = MyAMP(host, port)
    lc = LoopingCall(loop, myamp=myamp)
    lc.start(4.0)
    reactor.run()

main('127.0.0.1', 12345)

Error while calling myamp.say() within loop:

2013-08-16 12:28:58-0400 [-] Starting factory <twisted.internet.endpoints.OneShotFactory instance at 0x92273ec>
2013-08-16 12:28:58-0400 [-] Unhandled error in Deferred:
2013-08-16 12:28:58-0400 [-] Unhandled Error
    Traceback (most recent call last):
      File "lib/client.py", line 35, in <module>
        main('127.0.0.1', 12345)
      File "lib/client.py", line 32, in main
        lc.start(4.0)
      File "/usr/local/lib/python2.7/site-packages/twisted/internet/task.py", line 173, in start
        self()
      File "/usr/local/lib/python2.7/site-packages/twisted/internet/task.py", line 218, in __call__
        d = defer.maybeDeferred(self.f, *self.a, **self.kw)
    --- <exception caught here> ---
      File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 137, in maybeDeferred
        result = f(*args, **kw)
      File "lib/client.py", line 26, in loop
        myamp.say()
      File "lib/client.py", line 22, in say
        phrase='Hello world')
      File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 821, in callRemote
        return co._doCommand(self)
      File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1778, in _doCommand
        self.requiresAnswer)
      File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 752, in _sendBoxCommand
        box._sendTo(self.boxSender)
      File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 577, in _sendTo
        proto.sendBox(self)
    exceptions.AttributeError: 'NoneType' object has no attribute 'sendBox'

2013-08-16 12:28:58-0400 [Uninitialized] AMP connection established (HOST:IPv4Address(TCP, '127.0.0.1', 50457) PEER:IPv4Address(TCP, '127.0.0.1', 12345))

Source: (StackOverflow)

Example how to test twisted AMP

I am trying to figure out how to write unit tests for Twisted AMP, but I seem to be failing. I checked the source code, but it's quite overwhelming.

Can anyone write or point me to an example of testing simple AMP protocol sending data and receiving data via responder?


Source: (StackOverflow)

Serializing twisted.protocols.amp.AmpList for testing

I have a command as follows:

class AddChatMessages(Command):

    arguments = [ 
        ('messages', AmpList([('message', Unicode()), ('type', Integer())]))]

And I have a responder for it in a controller:

def add_chat_messages(self, messages):
    for i, m in enumerate(messages):
        messages[i] = (m['message'], m['type'])
        self.main.add_chat_messages(messages)
    return {}
commands.AddChatMessages.responder(add_chat_messages)

I am writing a unit test for it. This is my code:

class AddChatMessagesTest(ProtocolTestMixin, unittest.TestCase):
    command = commands.AddChatMessages
    data = {'messages': [{'message': 'hi', 'type': 'None'}]}

    def assert_callback(self, unused):
        pass

Where ProtocolMixin is as follows:

class ProtocolTestMixin(object):

    def setUp(self):
        self.protocol = client.CommandProtocol()

    def assert_callback(self, unused):
        raise NotImplementedError("Has to be implemented!")

    def test_responder(self):
        responder = self.protocol.lookupFunction(
            self.command.commandName)
        d = responder(self.data)
        d.addCallback(self.assert_callback)
        return d

It works if AmpList is not involved, but when it is - I get following error:

======================================================================
ERROR: test_responder
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/internet/defer.py", line 139, in maybeDeferred
    result = f(*args, **kw)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/internet/utils.py", line 203, in runWithWarningsSuppressed
    reraise(exc_info[1], exc_info[2])
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/internet/utils.py", line 199, in runWithWarningsSuppressed
    result = f(*a, **kw)
  File "/Users/<username>/Projects/space/tests/client_test.py", line 32, in test_responder                                                                             
    d = responder(self.data)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1016, in doit
    kw = command.parseArguments(box, self)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1717, in parseArguments
    return _stringsToObjects(box, cls.arguments, protocol)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 2510, in _stringsToObjects
    argparser.fromBox(argname, myStrings, objects, proto)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1209, in fromBox
    objects[nk] = self.fromStringProto(st, proto)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1465, in fromStringProto
    boxes = parseString(inString)
  File "/Users/<username>/Projects/space/env/lib/python2.7/site-packages/twisted/protocols/amp.py", line 2485, in parseString
    return cls.parse(StringIO(data))
TypeError: must be string or buffer, not list

Which makes sense, but how do I serialize a list in AddChatMessagesTest.data?


Source: (StackOverflow)

How should a Twisted AMP Deferred be cancelled?

I have a Twisted client/server application where a client asks multiple servers for additional work to be done using AMP. The first server to respond to the client wins -- the other outstanding client requests should be cancelled.

Deferred objects support cancel() and a cancellor function may be passed to the Deferred's constructor. However, AMP's sendRemote() api doesn't support passing a cancellor function. Additionally, I'd want the cancellor function to not only stop the local request from processing upon completion but also remove the request from the remote server.

AMP's BoxDispatcher does have a stopReceivingBoxes method, but that causes all deferreds to error out (not quite what I want).

Is there a way to cancel AMP requests?


Source: (StackOverflow)

Reading Buffer Data using C++ AMP

I can't seem to find a way to let myself read the data from my AMP array.

What I want to be able to do, is take my buffer, copy it into a vector and then use the vector. I'm aware that I should set the CPU access flags, but I'm having trouble doing so.

Firstly, this is how I'm trying to access the buffer. I'm putting this here first just in case I have done something how it shouldn't be done. Perhaps there is a function built in that I've missed that does this for me?

std::vector<Pticle> vecParticles;
    ID3D11Buffer* pBuffer = reinterpret_cast<ID3D11Buffer *>(concurrency::direct3d::get_buffer(m_arrParticles));
    D3D11_MAPPED_SUBRESOURCE MappedResource;
    m_pDeviceContext->Map(pBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
    {
        auto pData = (Pticle*)MappedResource.pData;
        for (unsigned i = 0; i < m_uiNumParticles; ++i)
        {
            vecParticles.push_back(pData[i]);
        }
    }
    m_pDeviceContext->Unmap(pBuffer, 0);

Basically it should write all the data from the buffer into the vector

Now I know I should set my access flags, however I can't seem to do it. I write in the following function in my initialise:

m_Accelerator.set_default_cpu_access_type(concurrency::access_type::access_type_read_write);

however it breaks, with the following error

"Invalid access_type specified. accelerator does not support zero copy."

I'm not sure what this means, if I'm attempting to set it up to read and write, didn't it pass the test? It also does it on any access type I try.

How can I set it up so that I can read the data from the buffer?

Any help would be great. Cheers :)


Source: (StackOverflow)

How to remove reference to ttf file after using imagettftext?

I'm currently developing a captcha system for the site I'm currently developing for a school project.. here: http://rjtestsystem.atwebpages.com/

Here's the code, err, prototype I came up with so far:

 <?php
    if (isset($_GET['METHOD']) && $_GET['METHOD']=='captcha')
    {   session_start();
        $code=rand(1000,9999);
        $_SESSION["code"] = $code;
        session_write_close();
        $font = rand(1,4).".ttf";
        if ($font == "1.ttf")
            $font_size = 20;
        else if ($font == "2.ttf")
            $font_size = 25;
        else if ($font == "3.ttf")
            $font_size = 30;
        else if ($font == "4.ttf")
            $font_size = 35;
        $angle = 0;
        $width = 120;
        $height = 60;
        $bounding_box = imagettfbbox($font_size, $angle, $font, $code);
        $textwidth = abs($bounding_box[4] - $bounding_box[0]);
        $textheight = abs($bounding_box[5] - $bounding_box[1]);
        $x = ($width - $textwidth) / 2;
        $y = (($height*3/4) + $textheight) / 2;
        $image = imagecreatetruecolor($width, $height);
        $text_background = imagecolorallocate($image, 0, 0, 0);
        $color = imagecolorallocate($image, 230, 230, 230);
        imagefill($image, 0, 0, $text_background);
        imageline($image, 0, $y-rand(0,10), $width, $y-rand(0,10), $color);
        imageline($image, 0, $y, $width, $y, $color);
        imageline($image, 0, $y+rand(0,10), $width, $y-rand(0,20), $color);
        imageline($image, $x+rand(0,$width/2), 0, $x+rand($width/2,$width), $height, $color);
        imageline($image, $x+rand(0,$width/2), $height, $x+rand($width/2,$width), 0, $color);
        for($i=0;$i<400;$i++)
        {   imagesetpixel($image,rand()%$width,rand()%$height,$color);
        }
        imagettftext($image, $font_size, $angle, $x, $y, $color, $font, $code);
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
        exit();
    }
    ?>
    <img src = "<?php echo $_SERVER['PHP_SELF']; ?>?METHOD=captcha">

The code seems to be working fine, but when I try to move the files elsewhere, the system would give me a message that the file is being used by another program. It seems that the references to the TTF files are still there even after executing the code. I've tried to look for a way to stop this behavior but I can't seem to get my searches right. Well, the problem goes away once I restart the server, but it's a hassle when debugging. Is there a way or proper method to remove the references / file handle / etc to the TTF files or close this process as soon as it's finished? If possible, I'd like to keep using this code.

I have only a year of experience in Php so please bear with my rudimentary way of coding and asking questions. If anyone can lead me to the right discussions, please do. Thank you.

I'm using WAMP server version 2.4.


Source: (StackOverflow)

Time out exception when accessing Connectship web service through progistic AMP

I am implementing a shipping application for a client. In order to ship via UPS carrier client wants us to use Connectship web services. Progistics AMP API is used to communicate with Connectship web services. while installing connectship tool kit it creates a AMP IIS host in our dev environment (win server 2012).

below is app.config settings.

 <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="AMPSoapService">
          <textMessageEncoding messageVersion="Soap12" />
          <httpTransport />
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="http://kcmfsupsd01.na.imtn.com:8080/amp.svc/soap"
          binding="customBinding" bindingConfiguration="AMPSoapService"
          contract="AMPServiceReference.CoreXmlPort" name="AMPSoapService" />
    </client>
  </system.serviceModel>

This is how i access in code:

CoreXmlPortClient client = new CoreXmlPortClient();
// Create ship request and append all required parameters
            ShipRequest shipRequest = new ShipRequest();
// Send ship request
            ShipResponse shipResponse = client.Ship(shipRequest);

My Question is: Timeout exception is thrown in dev, qa and prod environments. This is not consistent.

system.timeoutexception: the http request to 'http://kcmfsupsd01.na.imtn.com/amp.svc/soap http://kcmfsupsd01.na.imtn.com/amp.svc/soap ' has exceeded the allotted timeout of 00:01:00. the time allotted to this operation may have been a portion of a longer timeout.

Not specific to a request. It can happen any request, any time.


Source: (StackOverflow)

Twistd amp protocol : Producer/Consumer pattern?

I would like to use protocal to send data between server/client : list of unicode (string) that exceed the limit size of 65,535 bytes. A nice and clean solution to deal with the limit size problem is to Implement Producer/Consumer pattern.

Unfortunately, I read the documentation and example but I can't find how to start. For small size of transferred data, my amp implementation works very well . I show here relevant parts of my code.

command

class DataCommand(Command):
    response = [("data", ListOf(Unicode()))]
    errors = {
        KeyError: "KEY_ERROR",
        ValueError: "VALUE_ERROR",
    }    

server

class ProducerLocator(CommandLocator):
    def __init__(self,size,N):
        self.data = [id_generator(size=size) for x in range(N)]
    @DataCommand.responder
    def getData(self):
        return {'data':self.data}  ## don't work if is self.data > 64kB

client

class Consumer:     
    d = connect()
    def getData(protocol):
        return protocol.callRemote(DataCommand)
    d.addCallback(getData) 

Some code to generate data (used above in the factory constructor)

import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

Source: (StackOverflow)