text:
Q: NSData on custom class? I am about to look into bluetooth interaction on the iPhone. Now, i read that the only object that can be transferred is an NSData object. Now, i wanna transfer my "character" objects. The class looks something like this:
@interface Character : NSObject <NSCoding>
{
   UIImage *characterImage;
   int health;
   NSString *name;
}

-(void) initWithStats;
-(void) addToViewController: (UIViewController *)theView;

-(void) encodeWithCoder:(NSCoder *)encoder;
-(void) initWithCoder:(NSCoder *)decoder;

@end

Now, i know that i have to conform to the NSCoding protocol and implement those 2 methods, however, i am not quite sure what to do here. I know i somehow need to be able to make instances of this class and then "unpack / unarchieve" them when the NSData object is received by the other device.
So, any advice here is greatly appreciated :=) i am very new to bluetooth programming and have never worked with that or the NSData before. So thanks on advance :)
/JBJ

A: It sounds like you're really just asking how to implement -encodeWithCoder: and -initWithCoder:. It's pretty straightforward:
-(void) encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:characterImage forKey:@"character image"];
    [encoder encodeInt:health forKey:@"health"];
    [encoder encodeObject:name forKey:@"name"];
}

That's all. -initWithCoder: works exactly the same way, except you call the complementary methods, such as: characterImage = [decoder decodeObjectForKey:@"character image"];.
If you need to provide the data in a particular format to work with the target device that doesn't support the archive format, you can do that instead and use the -encodeBytes:length:forKey: method to store whatever you like, or write data in your own format into a NSMutableData object and then use -encodeObject:forKey: on that. Your target device may still need to find your data in whatever envelope the encoder stores it; you can make that easier by starting with a known series of bytes. I'm not sure whether that's necessary in your case, but it's something to keep in mind.


text: Q: Monthly subscription to plugin My question is very simple, how do set up monthly subscription for plugin I make, I have seen some of these in your shop, should be very easy as it is in Shopify. I tried to find information, but didn't succeed. Maybe you could guide me through it, please. ???

redpajama_set_name: RedPajamaStackExchange


text:
Q: AppFabric DataCache GetValues by keys? How can I use AppFabric DataCache and get values by keys?
eg. I want to do:
string[] keys = new []{"key1","key2", ...,"keyLast" }
object[] values = factory.GetCache("MyCache").Get(keys);

This seems like a very fundamental operation, I am hoping there is a way to do this without roundtripping to the backing store.
P.s. I know redis ServiceStack implementation supports this out of the box, for my use case this is a mandatory feature in deciding which technology to adopt for my company.

A: The BulkGet method (MSDN) can do this. It accepts an IEnumerable<string> of the keys and the name of a region to query (which could be the System region, which you can get with the GetSystemRegionName method), and returns an IEnumerable<KeyValue<string, object>> of the keys and values (so you know which value goes with which key). Alternatively, if you're using regions, you can use the GetObjectsInRegion method, which will return the same structure (IEnumerable<KeyValuePair<string, object>>) containing all the objects cached in that region.


text:
Q: What type of tree traversal does the ast module use? What type of tree traversal does ast use (specifically ast.NodeVisitor())? When I created a stack and pushed each node that was traversed into the stack the results seemed to be a 'breadth first' tree traversal. Meaning that the order was dependent on the level in the tree.
Ex. Tree looks like
Module
  Assign
    Name
      Store
    Call
      Attribute
        Str
        Load

and the stack looks like
[Module,Assign,Name,Call,Store,Attribute,Str,Load]

Ex. Code
stack = []
class a(ast.NodeTransformer):
    def visit_Num(self,node):
        stack.append(node)
        ...
        return node

    ...                      #this is all the other visit_*() functions

    def visit_Str(self,node):
        stack.append(node)
        ...
        return node

if __name__ == "__main__":
    with open('some_file.py','r') as pt:
        tree = ast.parse(pt)
    new_tree = a()
    new_tree_edit = ast.fix_missing_locations(new_tree.visit(tree)) # I have tried with and without calling fix_missing_locations and got the same results.
    print stack

A: The ast.walk() function walks the tree breath-first; see the ast.py source:
def walk(node):
    """
    Recursively yield all descendant nodes in the tree starting at *node*
    (including *node* itself), in no specified order.  This is useful if you
    only want to modify nodes in place and don't care about the context.
    """
    from collections import deque
    todo = deque([node])
    while todo:
        node = todo.popleft()
        todo.extend(iter_child_nodes(node))
        yield node

New nodes are pushed into a queue, the next node being traversed is the front of the queue.
If you wanted a depth-first traversal, use a subclass of ast.NodeVisitor() instead; it will walk the tree using recursion; NodeVisitor.visit() calls NodeVisitor.generic_visit() unless a more node-specific visitor method is defined, and NodeVisitor.generic_visit() calls NodeVisitor.visit() again for child nodes:
class NodeVisitor(object):
    """
    A node visitor base class that walks the abstract syntax tree and calls a
    visitor function for every node found.  This function may return a value
    which is forwarded by the `visit` method.

    This class is meant to be subclassed, with the subclass adding visitor
    methods.

    Per default the visitor functions for the nodes are ``'visit_'`` +
    class name of the node.  So a `TryFinally` node visit function would
    be `visit_TryFinally`.  This behavior can be changed by overriding
    the `visit` method.  If no visitor function exists for a node
    (return value `None`) the `generic_visit` visitor is used instead.

    Don't use the `NodeVisitor` if you want to apply changes to nodes during
    traversing.  For this a special visitor exists (`NodeTransformer`) that
    allows modifications.
    """

    def visit(self, node):
        """Visit a node."""
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        return visitor(node)

    def generic_visit(self, node):
        """Called if no explicit visitor function exists for a node."""
        for field, value in iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        self.visit(item)
            elif isinstance(value, AST):
                self.visit(value)

If you do subclass NodeVisitor (or it's derived version, NodeTransformer), do remember to also call super(YourClass, self).generic_visit(node) in your specific visit_* methods to continue to traverse the tree.


text:
Q: Drupal OpenLayers Module JS error I've created a form (using FormEntity) that contains a Map to record user input location (see example). Everything works (almost) fine except that I've got a weird JS error when I want to draw a polygon or a point on the map. The error is : TypeError: c.N(...) is undefined.
I've tried to use the ol-debug.js library to have more details about the error, but when I do that I don't have the possibility to draw anymore.
Another strange thing is, this map works perfectly fine during the configuration step of the CCK field. I can draw on the map and I don't have any error. This one happens only on the main page.
Do you have any idea what is wrong ?
Thanks for your help
Arnaud


text:
Q: How to make the grid pager's width fill 100%,means flowing to right more closely? I has a grid with many column,and I set the grid overflow-x:scroll,but it seems that that the pager not to automatic lengthening when I  drag to scroller? How to make the pager  flow to right more closely?
The picture is here:
           Init Pager location:
The location that I want the pager like


text:
Q: .Net core 2.0 with oracle db connection with current .Ora file we are able to connect in .net 2.0 and 3.5 and unable to connect with .net core 2.0 , whether we need to modify the .ora file compared to old one. please tell the steps
OracleInternal.Network.NetworkException (0x00002F7A): ORA-12154: TNS:could not resolve the connect identifier specified
   at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, String instanceName)
   at OracleInternal.Network.OracleCommunication.DoConnect(String tnsDescriptor)
   at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
   at OracleInternal.ConnectionPool.PoolManager3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
   at OracleInternal.ConnectionPool.OracleConnectionDispenser3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, OracleConnection connRefForCriteria)
   at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
   at TodoApi.Startup.b__5_0(HttpContext context) in D:\Samples\TodoApi\TodoApi\Startup.cs:line 68}

A: Put correct configuration in tns .ora file inside app client folder or check your connection string in json file.


text:
Q: JoinClause - Invalid statement. Please check aliases, field identifiers, projections and query conditions I'm using Dynamicloud and something is wrong in my code:
This is my code:
RecordModel contactFormModel = new RecordModel(contactModelId);
RecordModel userFormModel = new RecordModel(userContactModelId);

DynamicProvider<ContactForm> provider = new DynamicProviderImpl<ContactForm>(new RecordCredential(csk, aci));

contactFormModel.setBoundClass(ContactForm.class);
Query<ContactForm> query = provider.createQuery(contactFormModel);
query.setAlias("contact");

query.setProjection("contact.namef, contact.comments");
JoinClause join = Conditions.innerJoin(userFormModel, "user", "contact.id = user.contactid");
query.join(join);

try {
    RecordResults<ContactForm> list = query.add(Conditions.like("contact.namef", "ProBusiness%")).list();
    System.out.println("list = " + list.getFastReturnedSize());

    if (list.getFastReturnedSize() > 0) {
        System.out.println("Contact Name = " + list.getRecords().get(0).getName());
        System.out.println("Contact Comments = " + list.getRecords().get(0).getComments());
    }

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

This code throws the following Exception:
org.dynamicloud.exception.DynamicloudProviderException: Invalid statement.  Please check aliases, field identifiers, projections and query conditions.

What's wrong?
Thanks!

A: Hi
The problems is the missing "id" in your projection section.  You need to set the id of one model involved in your JoinClause.
Dynamicloud always order the results by Id, in this case the query has ambiguous columns user.id and contact.id"
Try to put the following id in your projection (of course depends of your needs):
    query.setProjection("contact.id, contact.namef, contact.comments");

Hope this helps!


text:
Q: Why does Fortify SCA flag some Java ternary conditions as Always false or Always true I have been reviewing a lot of Fortify findings lately, and I am trying to understand why Fortify SCA is flagging some, not all, Java ternary conditions as either 'Always false' or 'Always true'.  Examples below.
Can anyone provide insight into this?  Thanks in advance.
These examples are all in Entity classes.
This is flagged as "Always false".
public void setGmtInd(String gmtInd) {
    this.gmtInd = gmtInd != null ? gmtInd.toUpperCase() : gmtInd;
}

This is flagged as "Always true".
public void setDefaultValueInd(String defaultValueInd) {
    this.defaultValueInd = defaultValueInd != null ? defaultValueInd.toUpperCase() : defaultValueInd;
}

This is NOT flagged as a finding.
public void setUserid(String userid) {
    this.userid = userid != null ? userid.toUpperCase() : userid;
}

A: I dug deeper into the application code and found the following.
The ones flagged as Always false, are always being called with a null value.
this.setGmtInd(null);

The ones flagged as Always true, are always being called with a hardcoded value.
this.setDefaultValueInd("Y");
this.setDefaultValueInd("N");

The ones not being flagged are, of course, being used properly.
this.setUserid("");
this.setUserid(cmosUser.getUserid());

I apologize for wasting your time on this one...  Next time, I will dig much deeper first.


text:
Q: Using authlogic, login using email and password was working fine. I just added a username field to my User model, and now login doesn't work I use authlogic in my RoR app. For login, I use email and password like this:
<% form_for @user_session, :url => user_session_path do |f| %>
  <%= f.error_messages %>
  <%= f.label :email %>

  <%= f.text_field :email %>

  <%= f.label :password %>

  <%= f.password_field :password %>

  <%= f.check_box :remember_me %><%= f.label :remember_me %>

  <%= f.submit "Login" %>
<% end %>

This was working fine, but I've just added a 'username' field to my user model, and now I'm getting this error (on the <%= f.text_field :email %> line):
 NoMethodError in User_sessions#new
undefined method `email' for #<UserSession: no credentials provided>

I'm assuming that this error is occurring because I now have a username field? How can I have a username field, but not use it for the login?

A: I believe that Authlogic automatically uses the username field if it exists.  If you are not using the username field for authentication then the simplest solution to your answer would be to rename the username column.


text:
Q: ElasticSearch yields wrong results when using terms I have a list of documents indexed on ElasticSearch with the following structure
{
  "product_id": "xx",
  "product_desc":"some product desc"
}

When I perform a search with term, as follows, I get the correct results:
GET my_index/my_doctype/_search
{"query":
 {
  "match":{"product_id": "138156"}
  }
}

However, when I perform the same search with terms, I get a wrong results
GET my_index/my_doctype/_search
{
          "query": {
            "terms": {
              "product_id": ["138156"]
        }
  }
}

This happens for some products and not all them. Any ideas how to resolve this issue?

A: For terms query to work correctly on a string field the field must be non-analyzed.  See for example: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html


text:
Q: How to resolve 'init(proximityUUID:identifier:)' was deprecated in iOS 13.0 for iBeacon I want to receive RSSI of iBeacon on my iOS application this code can run on iOS12. Now I have updated to iOS 13 this code can't run.
and alert

'init(proximityUUID:identifier:)' was deprecated in iOS 13.0
  'startRangingBeacons(in:)' was deprecated in iOS 13.0
  'stopRangingBeacons(in:)' was deprecated in iOS 13.0

How to fix this problem?

A: If you look at the documentation for the method your are using it tells you that it was deprecated in iOS 13 and also tells you what to use instead.
In case the link breaks, this is the alternative option:
init(uuid:major:minor:identifier:)

Check the documentation for the other methods and it will tell you which alternatives to use.
Now.. to configure your app to switch between methods based on the iOS version you can use an @available check..
if #available(iOS 13, *) {
    // use the shiny new one
} else {
    // use the old one
}


text:
Q: Caching bitmaps when working with pointers I have two function: one of them for getting image from .mul file like a byte array into bitmap, the second going to paint it in colors (change pixels of it image). So, here is the function of painting bitmap in colors, and this function caching bitmap:
    public static void RecolorPartial(HueEntry hue, Bitmap bitmap)
    {
        if (hue == null)
            throw new ArgumentNullException("hue");

        if (bitmap == null)
            return;

        if (bitmap.PixelFormat != PixelFormat.Format16bppArgb1555)
            throw new ArgumentException("Invalid bitmap pixel format.", "source");

        BitmapData data = bitmap.LockBits(Ultima.GetBitmapBounds(bitmap), ImageLockMode.ReadWrite, PixelFormat.Format16bppArgb1555);
        Debug.Assert(data.Stride % 2 == 0);

        RecolorPartialInternal(hue, data.Scan0, data.Stride * data.Height / 2);

        bitmap.UnlockBits(data);
    }

    private static unsafe void RecolorPartialInternal(HueEntry hue, IntPtr dataPtr, int lenght)
    {
        ushort* pData = (ushort*)dataPtr.ToPointer();

        for (int i = 0; i < lenght; i++)
        {
            ushort c = (ushort)((*pData) & 0x1F);
            if (c == (((*pData) >> 5) & 0x1F) && c == (((*pData) >> 10) & 0x1F))
            {
                *pData = (ushort)(((*pData) & 0x8000) | hue.Colors[c]);
            }
            pData++;
        }
    }

I can't understand, why when i use it in cycle (for 5-10 bitmaps (but 2 already enought)), it's going to cache it or didn't redraw- after first bitmap, every next looks like first.
        for (int i = 0; i < colors.Count(); i++)
        {
            Bitmap bit = Art.GetStatic(type);

            Hues hues = Hues.Load(huePath);

            if (colors[i] != 0)
                RedrawHue.RecolorPartial(hues[colors[i]], bit);

            Bitmap newbit = new Bitmap(bit.Width, bit.Height);

            Graphics newgraph = Graphics.FromImage(newbit);

...
If my colors array looks like {0, 1590, 0, 1330, 0, 1777} - that's fine, images changing from gray (for 0 color value) to blue (1590 value) , but 1590 = 1330 = 1777. If i make {1590, 1330, 1777, 2000} - all of bitmaps the same and looks like for 1590 (ofcource if i shuffle- every next after first should be like first). Without cycle everything fine.
Mb the question is stupid, isn't full or isn't described well, but i really don't know why is that and what i can to do for using this function in cycle.


text:
Q: IsControl in Javascript Is there a function like .Net's Char.IsControl() in Javascript?
Also, I find it very inconvenient that Javascript doesn't have an official web site like Python, Java and C#. What do you use as reference?

A: No, there isn't one. However, JavaScript uses UTF-16 and so you can use the Unicode definition of a control character to write your own. That definition is:

Control Codes The 65 characters in the ranges U+0000..U+001F and U+007F..U+009F. Also known as control characters.

Thus:
function isControl(ch) {
    var code = ch.charCodeAt(0);
    return ((code >= 0x0000 && code <= 0x001f) || (code >= 0x007f && code <= 0x009f));
}

Or as a regexp:
var isControlRex = /[\u0000-\u001F\u007F-\u009F]/;
function isControl(ch) {
    return isControlRex.test(ch);
}

I use the specification as a reference. Also the Mozilla Developer Network's (what we used to call the MDC) JavaScript pages.


text:
Q: How to change the time value Using VB6
In my Form am using DateTime Picker for Time.
DateTimePickerValue = 13:00:00

From the DateTimePicker i need to get 130000 instead of 13:00:00, How to avoid the ':'
Tried Code
Dim dpv As String

   dpv = Left(dpin, 2) & Mid(dpin, 4, 2) & Right(dpin, 2)
   MsgBox dpv

dtpin is datetimepickerforat
dtpin format = custom Format (HH:mm:ss)
dtpin = "08:00:00" (Selected Values form the datetime picker)
Output displaying: 1222Am(MMDD displaying)
I need Timeonly 080000
How to get this.

A: This will set "s" to "123456" if the time is currently 12:34:56 PM:
Dim s as String
s = Format( Time(), "HHmmss" )

A: Not sure if I understand.
Try
Sub a()
   dpv = "13:00:00"
   dp = Left(dpv, 2) & Mid(dpv, 4, 2) & Right(dpv, 2)
   MsgBox dp
End Sub

A: DateTime.Now.ToString("HHmmss") will do

A: I'm not that familiar with VB6 but I know it can use Regex. Regex will let you use a regular expression to find and replace the colon which sounds like what your going for. Here a link if your new to regular expressions.
http://www.funduc.com/regexp.htm


text:
Q: Including some static html files? Where can we place static html files in our war file? For example, a default project has this:
war/projectname.html

I'd like to just make a few static folders with static pages that are like:
war/projectname.html
war/signup/index.html
war/about/index.html

so that my users can just hit those static pages like:
www.myproject.com/signup
www.myproject.com/about

where would I put folders like that in our project tree? I tried putting them under war/, just beside projectname.html (like above), but they don't seem to be available there, I just get a 404 error,
Thanks

A: This works fine as pointed out by Igor Klimer, I had a Filter enabled which was messing up the routing.


text:
Q: How do i make static values as dynamic values In addSeries method there are values which are declared static i want to give it dynamically Please can anyone make it for me /...................This is dojo code
require(["dojox/charting/Chart", "dojox/charting/axis2d/Default", "dojox/charting/plot2d/StackedAreas", "dojox/charting/themes/Wetland" , "dojo/ready"],
              function(Chart, Default, StackedAreas, Wetland, ready){
                ready(function(){
                  var c = new Chart("chartOne");
                  c.addPlot("default", {type: StackedAreas, tension:3})
                    .addAxis("x", {fixLower: "major", fixUpper: "major"})
                    .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", min: 0})
                    .setTheme(Wetland)
                    .addSeries("Series B", [1, 2, 0.5, 1.5, 1, 2.8, 0.4])
                    .addSeries("Series C", [2.6, 1.8, 2, 1, 1.4, 0.7, 2])
                    .addSeries("Series D", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2])

                .render();
            });
        });

A: You can change it like this:
var arraySer1 = [1, 2, 0.5, 1.5, 1, 2.8, 0.4];
var arraySer2 = [2.6, 1.8, 2, 1, 1.4, 0.7, 2];
var arraySer3 = [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2];

 require(["dojox/charting/Chart", "dojox/charting/axis2d/Default", "dojox/charting/plot2d/StackedAreas", "dojox/charting/themes/Wetland" , "dojo/ready"],
          function(Chart, Default, StackedAreas, Wetland, ready){
            ready(function(){
              var c = new Chart("chartOne");
              c.addPlot("default", {type: StackedAreas, tension:3})
                .addAxis("x", {fixLower: "major", fixUpper: "major"})
                .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", min: 0})
                .setTheme(Wetland)
                .addSeries("Series B", arraySer1)
                .addSeries("Series C", arraySer2)
                .addSeries("Series D", arraySer3)

            .render();
        });
    });

Here's the fiddle for that : http://jsfiddle.net/WdDxM/
First you define the Arrays you need, then fill in the Data.
The array can be filled with the Data from a Store or whereever you get your Data from.
Regards


text:
Q: How to I send results/subset of a panda dataframe to my csv file and sql db I have a python script using pandas.  I surprisingly have everything pulling from my json file, I have looped through the file, got everything into a dataframe and can spit out that df to my csv file and to a mysqldb.
I just learned about flattening my json data, then about using using subsets of my df results so I can get specific columns.  I thought I could just create another var to hold my subset and then use to_csv and to_sql, but when I look at the file, the entire df is in the csv
hold_subset = df[['firstname', 'lastname', 'fruit']]

hold_subset.to_csv(dt_string+'_team-info.csv', index=False)

How do i move my subset results to my csv and mysql?
Thank you in advance.


text:
Q: how to embed an image in a JSON response I'm using Jimp to read in a JSON string that looks like this:

As you can see the image node is a base64-encoded JPEG.
I'm able to succesfully convert it to a TIFF and save it:
  Jimp.read(Buffer.from(inputImage, "base64"), function(err, image) {
    image.getBuffer(Jimp.MIME_TIFF, function(error, tiff) {
    context.bindings.outputBlob = tiff
    ...}

However, when I attempted to embed the tiff inside of a JSON object, the TIFF gets all garbled up:
  const response = {
    image: tiff.toString('base64'),
    correlation: correlation
  };

  context.bindings.outputBlob = response;

Here's the full code:
const Jimp = require("jimp");

module.exports = function(context, myBlob) {
  const correlation = context.bindings.inputBlob.correlation;
  const inputImage = context.bindings.inputBlob.image;
  const imageName = context.bindings.inputBlob.imageName;

  context.log(
    correlation + "Attempting to convert this image to a tiff: " + imageName
  );
  Jimp.read(Buffer.from(inputImage, "base64"), function(err, image) {
    image.getBuffer(Jimp.MIME_TIFF, function(error, tiff) {
      const response = {
        image: tiff.toString('base64'),
        correlation: correlation
      };

      context.bindings.outputBlob = response;
      context.log(
        correlation + "Succesfully converted " + imageName + " to tiff."
      );
      context.done();
    });
  });
};

How do we embed the tiff inside of a JSON payload?
If this output is non-negotiable, how would I render the tiff from the saved payload?

A: Well since you confirmed you are looking for output with context.res here is my working sample.. note that there is a maximum response size, so you can't return every image/file the way I am returning the image here
const Jimp = require('jimp')

module.exports = async function (context, req)
{
    let response = {}

    try
    {
        let url = 'https://noahwriting.com/wp-content/uploads/2018/06/APPLE-300x286.jpg'

        //call function to download and resize image
        response = await resizeImage(url)

    }
    catch (err)
    {
        response.type = 'application/json'
        if (err.response == undefined)
        {
            context.log(err)
            response.status = 500
            response.data = err
        }
        else
        {
            response.data = err.response.data
            response.status = err.response.status
            context.log(response)
        }
    }

    //response
    context.res =
    {
        headers: { 'Content-Type': `${response.type}` },
        body: response.buf
    }
}

async function resizeImage(url)
{
    //read image to buffer
    let image = await Jimp.read(url)

    //resize image
    image.resize(300, Jimp.AUTO)

    //save to buffer
    let image_buf = await image.getBufferAsync(image.getMIME())

    //image.getMIME() returns something like `image/jpeg` which is a valid Content-Type for responses.
    return { 'buf': image_buf, 'type': image.getMIME() }
}

(Offtopic but I saw that you are using blob storage so..) if you plan on storing photos/files/anything in Azure Blob Storage and you want to retrieve them in some systematic way you will find out very fast that you can't query the storage and you have to deal with ugly XML. My work around to avoid this way to create a function that stores photos/files in Blob Storage but then saves the url path to the file along with the file name and any other attributes to a mongo storage. So then I can make super fast queries to retrieve an array of links, which point to the respective files.


text:
Q: How to skip over child element with Scrapy I'm looking to scrape just the job description from this page: https://www.aha.io/company/careers/current-openings/customer_success_specialist_project_management_us
I'd like to get all of the text and HTML inside the div with the class of "container py2 content job", EXCEPT the button. It's in an <a> tag with the class of "btn btn-large btn-secondary".
I've got two different xpath selectors that I thought should work, but don't. The first doesn't exclude the button and the second gets rid of all of the other HTML, which I'd like to keep.
response.xpath('//div[@class ="container py2 content job"]
[not(parent::a/@class="btn btn-large btn-secondary")]').extract()

response.xpath('//div[@class ="container py2 content
job"]/descendant::text()[not(parent::a/@class="btn btn-large btn-
secondary")]').extract()

Neither is scraping all of the HTML in the div minus what's inside the a tag. I'm hoping there's something simple that I'm missing, but I can't find what I'm looking for in the documentation.

A: job_html = response.css('div.content *').extract()
job_html = [x for x in job_html if "Apply now" not in x]
print(job_html)


text:
Q: How to copy parameters from global model to thread-specific model Context:
I am new to TensorFlow and I'm trying to implement some of the algorithms in this paper which require occasionally copying from a global shared model to local thread-specific model.
Question:
What is the best/correct way to accomplish the above task? I've provided a dummy example of the way I am currently doing this below and the error I'm getting. Can someone please explain why the error occurs?
import tensorflow as tf
import threading

class ExampleModel(object):
  def __init__(self, graph):
    with graph.as_default():
      self.w = tf.Variable(tf.constant(1, shape=[1,2]))

sess = tf.InteractiveSession()
graph = tf.get_default_graph()
global_network = ExampleModel(graph)
sess.run(tf.initialize_all_variables())

def example(i):
  global global_network, graph
  local_network = ExampleModel(graph)
  sess.run(local_network.w.assign(global_network.w))

threads = []
for i in range(5):
  t = threading.Thread(target=example, args=(i,))
  threads.append(t)

for t in threads:
  t.start()

Error:
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/Users/kennyhsu5/anaconda/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/Users/kennyhsu5/anaconda/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "tmp.py", line 16, in example
    local_network = ExampleModel(graph)
  File "tmp.py", line 7, in __init__
    self.w = tf.Variable(tf.constant(1, shape=[1,2]))
  File "/Users/kennyhsu5/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 211, in __init__
dtype=dtype)
  File "/Users/kennyhsu5/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 319, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/Users/kennyhsu5/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2976, in __exit__
    self._graph._pop_control_dependencies_controller(self)
  File "/Users/kennyhsu5/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2996, in _pop_control_dependencies_controller
    assert self._control_dependencies_stack[-1] is controller
AssertionError

A: About tf.Graph class in Tensorflow:

Important note: This class is not thread-safe for graph construction.
  All operations should be created from a single thread, or external
  synchronization must be provided. Unless otherwise specified, all
  methods are not thread-safe.

The self.w = ... declaration and the local_network.w.assign(...) operation are causing the error.
I know it basically kills your multithreading implementation, but you can fix the above code by moving these declarations to the main thread. You can then use the threads to actually run what the operations you prescribed. For example:
import tensorflow as tf
import threading

class ExampleModel(object):
  def __init__(self, graph):
    with graph.as_default():
      self.w = tf.Variable(tf.constant(1, shape=[1,2]))

sess = tf.InteractiveSession()
graph = tf.get_default_graph()
global_network = ExampleModel(graph)
sess.run(tf.global_variables_initializer())

def example(sess, assign_w):
  sess.run(assign_w)

threads = []
for i in range(5):
  local_network = ExampleModel(graph)
  assign_w = local_network.w.assign(global_network.w)
  t = threading.Thread(target=example, args=(sess, assign_w))
  threads.append(t)

for t in threads:
  t.start()

I would also advice you to pass your variables to the thread via the args parameter rather than using global.
Finally, consider using global_variables_initializer instead of deprecated initialize_all_variables.


text:
Q: Remove and Add Attribute id using jQuery I have menu in my website and I want to Remove and Add Attribute id using jQuery based on Different Pages.
My Code :

Users

Category

SubCategory

Area

Feedbacks

Here, on Home Page, id 'current' is set to first li. Now, when user visits Category, I want to remove id current from Users and set id to Category.
How to do this ?

A: Try
$(document).ready(function () {
    $('li#current').removeAttr("id"); //remove previously added id
    var loc = $(location).attr('href'); //get current location
    $('#nav a').filter(function () { //filter a tag
        return this.href == loc;//whose link is pointing to current location
    }).parent().attr('id', 'current'); //add id to parent li
});

A: $('li').click(function(e) {
        e.preventDefault();
        $('li').removeAttr('id');
        $(this).attr('id','current');
    });

Demo

A: Try this:
//$('#nav li').each(function(){
    $('#current').removeAttr('id');
    $('li:active').attr('id','current');
//}

A: $('#nav li').click(function() {
        $('li#current').removeAttr("id");
        $(this).attr('id' , 'current');
});

A: Use this,
$('#nav li').click(function(){
  $('#current').removeAttr('id');
  $(this).attr('id','current');
}

A: switch(window.location.pathname) {
    case 'Category.aspx':
        $("#nav").find('#current').attr('id','');
        $('#nav').find('a[href="Category.aspx"]').attr('id', 'current');
    break;
    case 'SubCategory.aspx':
        $("#nav").find('#current').attr('id','');
        $('#nav').find('a[href="SubCategory.aspx"]').attr('id', 'current');
    break;
    case 'Area.aspx':
        $("#nav").find('#current').attr('id','');
        $('#nav').find('a[href="Area.aspx"]').attr('id', 'current');
    break;
    case 'Feedbacks.aspx':
        $("#nav").find('#current').attr('id','');
        $('#nav').find('a[href="Feedbacks.aspx"]').attr('id', 'current');
    break;

}


text:
Q: How to get sum of array element values in Perl? I have a file with a list of strings:
 002.5005.200
 030000050550
 4040004002.2

I would like to find the sum of the numbers that make us these strings. I could split each line into an array then loop through each element and add it together. However, is there a more easier way to do this?
Desired Output:
 7.7
 18
 14.2

A: test.pl
#!/usr/bin/perl
use warnings;
use strict;

while (<>) {
    my @nums = $_ =~ /([1-9](?:\.[0-9])?)/g;
    my $sum = 0;
    map { $sum += $_ } @nums;
    print "$sum\n";
}

Test
$ cat file
002.5005.200
030000050550
4040004002.2
$ ./test.pl file
7.7
18
14.2

Or perl one liner
perl -lne '$sum=0; map { $sum += $_ } $_ =~ /([1-9](?:\.[0-9])?)/g; print $sum;' file

A: my $x = '002.5005.200';
my $sum = 0;
foreach( split '0', $x ) { $sum += $_ }
print "$sum\n";

Outputs 7.7


text:
Q: Dynamically creating buttons that remove a row from a table I'm trying to create a button for each row in my database that, when pressed, will delete this particular row. I should also mention that the data from the database is displayed correctly and the table I'm using is also completely fine.The buttons appear at the side of each row, when the button is clicked, the row dissapears but the data is not deleted from the database, when the page is reloaded the rows that were previously "deleted", reappear. After pressing the button i also get this "Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\INDUSTRIALPROJECT\records.php:56 Stack trace: #0 {main} thrown in C:\xampp\htdocs\INDUSTRIALPROJECT\records.php on line 56".
line 56 is : $del = mysql_query("DELETE FROM records WHERE id=" . $row['id']);. The same query works fine when placed directly into phpMyAdmin.
    <?php
// Check connection
include_once 'config.php';
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$sql = "SELECT * FROM records";
$result = $link->query($sql);
function post($key){ return(isset($_POST[$key]) ? htmlspecialchars($_POST[$key]) : ""); }
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    if(post('rowButton'.$row['id']) =="Delete"){
        $del = mysql_query("DELETE FROM records WHERE id=" . $row['id']);
        $deleted = '
Entry ' . $row['id'] . ' was succesfully deleted
';
    }
    else {
        echo '<form action ="' . $_SERVER['PHP_SELF'] . '" method="post">';
        echo "
";
        echo "" . $row['id'] . "	";
        echo "" . $row["visitingdate"]. "	";
        echo "" . $row["department"] . "	";
        echo "" . $row["visitingreason"]. "	";
        echo "" . $row["importance"]. "	";
        echo "" . $row["visitorname"]. "	";
        echo "" . $row["company"]. "	";
        echo "". $row["internalrecipientname"]. "	";
        echo "". $row["visitinglocation"]. "	";
        echo "". $row["ETA"]. "	";
        echo "". $row["ETD"]. "	";
        echo "". $row["HRverification"]. "	";
        echo "". $row["visitcompleted"]. "	";
        echo '<input type="submit" name="rowButton'. $row['id'] .'" value="Delete"/> 	';
        echo "
";
        echo "</form>";
    }
}
echo "
";
echo $deleted;
}
else { echo "0 results"; }
$link->close();
?>

A: First, this appears to be rather vulnerable to SQL injection attacks. StackOverflow is quite font of pointing this out up front, because it's really a solved problem that you should account for in the early stages of development. You're taking untrusted data (that was submitted by the user, without sanitizing it) and putting it directly in an SQL query. Bad things can happen when that occurs. Now with that aside, on to your actual question.
"Nothing happens" means the page doesn't change at all, right? So the browser doesn't know what to do when the button is clicked.
I think you haven't put any <form...> declaration here, which would be required for <input type="submit"> to do anything useful. You could use JavaScript with the stand alone submit button, but I don't see that in your code, either. You'll need something to tell the browser what to do when the submit button is pressed.
I haven't really tested the rest of your code, but based on what you've got already you might add the following:
    else {
+         echo '<form action ="' . $_SERVER['PHP_SELF'] . '" method="post">';
        echo "
";

and
        echo "
";
+        echo "</form>";
    }

(don't add the plus sign, that's just to show which line is added). I should add that I don't usually use submit buttons like this, so there's a chance I missed some additional details about how you're calling this, but putting the form in a <form> tag is at least a good start.
Edit
The mysql_query() function was removed in PHP 7; if you're using an older PHP you need to add support for the MySQL functions or if you're on PHP 7, you should use the MySQLi or PDO_MySQL functions instead. The warning box on the PHP manual page for mysql_query has some links for alternatives, how to select an alternative, and other supporting documentation that may help you. This StackOverflow answer may help, as well.


text:
Q: Accessing GIT_COMMIT environment variable from Jenkins pipeline script When I do a Git SCM checkout, I don't have the environment variable GIT_COMMIT which contains the latest git commit hash.
I can still access the commit hash by command line with git rev-parse HEAD but the environment variable normally already has it.
pipeline{
    agent {label 'master'}
    stages{
        stage('checkout from SCM'){
            steps{
            checkout([$class: 'GitSCM', branches: [[name: '*/${GIT_BRANCH}']],
                doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [],
                userRemoteConfigs: [[credentialsId: '9595efef-aa11-3366-5e5e-12a11b21da6a',
                url: 'https://host:port/xxx/yyy']]])
                bat """
                    echo %GIT_COMMIT%
                    echo ${env.COMMIT}
                    git rev-parse HEAD
                """
            }
        }
    }
}

Results are:

*

*%GIT_COMMIT% => empty

*${env.COMMIT} => null

*git rev-parse HEAD => prints hash code to Jenkins job output

EDIT:
Also tried to implement solution from this answer : https://stackoverflow.com/a/45845221/8315843
def scmVars = checkout([$class: 'GitSCM', branches: [[name: '*/master']],
    userRemoteConfigs: [[credentialsId: '2b74a351-67d5-4d00-abd3-
    49842a984201', url: 'ssh://git@corporate.com:repo.git']]])
env.GIT_COMMIT = scmVars.GIT_COMMIT

but as soon as I have def someVariable in my script, Groovy throws the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 6: Expected a step @ line 6, column 13.
               def scmVars = checkout([$class: 'GitSCM', branches: [[name: '*/${GIT_BRANCH}']],
               ^

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1107)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:624)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:602)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:579)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:323)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:293)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:677)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:689)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:553)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:505)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:335)
    at hudson.model.ResourceController.execute(ResourceController.java:101)
    at hudson.model.Executor.run(Executor.java:442)
Finished: FAILURE

I'm using Jenkins 2.332.2


text:
Q: Cascading Dropdownlist using ASP.net MVC How to get change Url if I select State from State dropdownlist, city from city Dropdownlist and Locality from Locality dropdownlist, browser Url should be changed as like Zipcode/statename/cityname/Localareaname. How to get this type of url from asp.net mvc using RouteConfig.
Controller Code:
    public ActionResult Index(string Search_name, int? page)
    {

        ViewBag.Title = "INDIAN Postal Codes";
        var StateList = objcity.GetAllStateName();

        model.StateList = StateList.Select(x =>
        {
            return new SelectListItem()
            {
                Text = x.statename,
               //Value = x.statename.Distinct().ToString()

            };

        }).ToList();

        model.StateList.Insert(0, new SelectListItem { Text = "--select--", Value = "0" });

        var CityList = objcity.GetAllCityName();

        model.CityList = CityList.Select(x =>
        {
            return new SelectListItem()
            {

            };
        }).ToList();

        model.CityList.Insert(0, new SelectListItem { Text = "--select--", Value = "0" });

        var LocalareaList = objcity.GetAllLocalareaname();

        model.LocalareaList = LocalareaList.Select(x =>
        {
            return new SelectListItem()
            {

            };
        }).ToList();
        model.LocalareaList.Insert(0, new SelectListItem { Text = "--select--", Value = "0" });

        //ViewData["Search_name"] = Search_name;
        List<usp_PostalcodeList_Fetch_Result> itmlist;
        //int currentPageIndex = page.HasValue ? page.Value : 1;

        Circuit9Entities db = new Circuit9Entities();
        //int pageSize = 10;

        int pageSize = 10;
        int pageIndex = 1;
        pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

        int id = 0;
        itmlist = objcity.GetPostalCodeList(id);
        model.discountList = itmlist.Select(x =>
        {
            return new PostalCodeModel()
            {
                PostalCodeId = x.PostalCodeId,
                PostalCode = x.PostalCode,
                Taluk = x.Taluk,
                officename = x.officename,
                regionname = x.regionname,
                statename = x.statename

            };
        }).OrderByDescending(a => a.PostalCodeId).ToList();

        if (string.IsNullOrWhiteSpace(Search_name))
        {
            model.pagePostalCodeList = model.discountList.OrderByDescending(x=>x.statename).ToPagedList(pageIndex, pageSize);
            //model.pagePostalCodeList = model.discountList.ToPagedList(currentPageIndex, pageSize).ToList();
        }
        else
        {
            //var students = from s in model.discountList
            //               select s;
            //model.pagePostalCodeList = students.Where(s => s.PostalCode.Contains(Search_name)).ToPagedList(currentPageIndex, pageSize);

            model.pagePostalCodeList = (from p in model.discountList
                                        where p.PostalCode.Contains(Search_name) || p.PostalCode.ToLower().Contains(Search_name.ToLower())
                                        || p.statename.Contains(Search_name) || p.statename.ToLower().Contains(Search_name.ToLower())

                                        select p).ToPagedList(pageIndex, pageSize);

            //model.pagePostalCodeList = jobSearchList.Where(k => k.JobName.ToLower().Contains(schKey.ToLower()) || k.JobDescription.ToLower().Contains(schKey.ToLower()) || k.JobSkill.All(x => x.SkillName.ToLower().Contains(schKey.ToLower()))).ToList();
        }

        if (Request.IsAjaxRequest())
        return PartialView("_PostalcodeList", model.pagePostalCodeList);
       else

           return View(model);
    }

public ActionResult GetDistrict(string statename)
        {
            int statId;

            List<SelectListItem> districtNames = new List<SelectListItem>();

        if (!string.IsNullOrEmpty(statename))
            {

                var LocalareaList = objcity.GetAllLocalareaname();

                List<usp_City_GetAllCityName_Result> districts = db.usp_City_GetAllCityName().Where(x => x.statename == statename).ToList();

                districts.ForEach(x =>
                {
                    districtNames.Add(new SelectListItem { Text = x.regionname, Value = x.regionname.ToString() });
                });

        }
            return Json(districtNames, JsonRequestBehavior.AllowGet);

    }

jQuery code:
    function getCityList1(obj) {

        var selectedText2 = $("#ddlState option:selected").text();

        $.ajax({
            type: "GET",
            url: "/Zipcode/GetDistrict",
            data: { statename: selectedText2 },
            datatype: "json",
            traditional: true,
            success: function (data) {

                var localarea = "<select id='LocalId'>";
                localarea = localarea + '<option value="">--Select--</option>';

                var district = "<select id='CityId'>";

                district = district + '<option value="">--Select--</option>';

                for (var i = 0; i < data.length; i++) {
                    district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';

                }

                district = district + '</select>';
                $('#CityId').html(district);

                $('#CityId').selectpicker('refresh');

                $('#LocalId').html(localarea);

                $('#LocalId').selectpicker('refresh');
                $('#LocalId').html('');
                //var localarea = "<select id='LocalId'>";
                //localarea = localarea + '<option value="">--Select--</option>';
                //localarea.html('');

            }
        });

    }


text:
Q: Solving for constants and initial conditions in differential equation with given solution I'm trying to solve the differential equation $y'' + ay' + by = 0$, and I've found that the solution is $y = 3e^{-x} + 2e^{2x}$.
However, I'm having trouble determining the constants $a$ and $b$, as well as the initial conditions for $x = 0$ that give just this solution.
Correct solution: $a = -1, b = -2$, and initial condition $y(0) = 5$ and $y'(0) = 1$.
Can someone help me understand how to arrive at this answer? I'm really struggling to understand the steps involved.
Plugging this solution into the differential equation, we get
$$\large(3e^{-x} + 2e^{2x})'' + a(3e^{-x} + 2e^{2x})' + b(3e^{-x} + 2e^{2x}) = 0$$
Any help would be greatly appreciated!

A: I find the question a bit strange. Your first paragraph says:

I'm trying to solve the differential equation $y'' + ay' + by = 0$, and I've found that the solution is $y = 3e^{-x} + 2e^{2x}$.

But I don't see how you can arrive at that particular solution, of that differential equation that depends on those apparently unknown parameters $a$ and $b$. We can naively  solve the differential equation and then go back to imposing conditions on $a$ and $b$ as follows.

*

*Solving the DE: $y''+ay'+by=0$ over a real domain:
\begin{align*}
y''+ay'+by&=0,\\
(\lambda^{2}+a\lambda +b)e^{\lambda x}&=0,\quad y(x):= e^{\lambda x},\\
\lambda_{1,2}&=-\frac{a}{2}\pm \frac{1}{2}\sqrt{a^{2}-4b}
\end{align*}
Then, when $\lambda_{1}\not=\lambda_{2}$ and they are real eigenvalues, we have a general solution of the form $y(x)=c_{1}e^{\lambda_{1}x}+c_{2}e^{\lambda_{2}x}$ for arbitrary constant $c_{1}$ and $c_{2}$. Hence, the general solution for DE is give by
$$y(x)=c_{1}e^{\left(-\frac{a}{2}+\frac{1}{2}\sqrt{a^{2}-4b}\right)x}+c_{2}e^{\left(-\frac{a}{2}-\frac{1}{2}\sqrt{a^{2}-4b} \right)x}$$
Then, we can see the that a natural condition to be imposed in this case must be: $a^{2}-4b>0$.


text:
Q: Refund to In App Purchase on Android I have an in app purchase that unlocks part of the app for a year. Its setup as Annual Subscription.
Temporarily running a promotion unlocking premium as one-time purchase.
One of the users emailed me and wanted to take advantage of the promotion. So I'm thinking Cancel / Refund his Subscription, and ask him to purchase again as one-time purchase.
My question is what happens after I cancel / refund his subscription order, does IAB still consider it a valid purchase or not ?
What happens when you queryInventory, is it no longer returned as his purchase or is it stilled returned and I have to handle the status somewhere in code?

A: You have to do it in your Google Wallet Merchant. Read this Google Documentation:
Once an order is refunded - on a non-rooted device - the order will be invalid if queried. IAB considers it as a purchaseState==2 (2 is refunded according to Table 4 in here). Note that the developer will be in charge to handle refunded items. Read this question.


text:
Q: Unable to fetch values from json array tree in codeigniter I have following array tree in json which is passed to view in a variable
   [{
       "root":"0",
       "id":"19",
       "name":"Rose",
       "childs":[{
                    "root":"19"
                    "id":"22",
                    "name":"Ceema",
                    "childs":[{
                                 "root":"22",
                                 "id":"49",
                                 "name":"Chandar"

                              },
                              {
                                 "root":"22",
                                 "id":"50",
                                 "name":"Carol"
                              }]
            },
            {
                "root":"19",
                "id":"23",
                "name":"Ben"
            }]
   }]

now i want that at first it displays the name of array with root 0, when we click on that name, it shows the name contained in arrays within child(if it has any).
M not so good with json, so please help!

A: Use json_decode() function in php or if you want to do it in javascript JSON.parse
This will give you result in array and rest things you need to do or find the code for it.


text:
Q: Getting a URL Rewrite error 500 when prerendering Maybe someone can help me out.
I have two rules in my web.config, one for pre-render and one for Vue.
I have stacked them like this:
<rules>
    <rule name="prerender.io" stopProcessing="true">
        <match url="(\.js|\.json|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff|\.svg)" negate="true" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_USER_AGENT}" pattern="googlebot|bingbot|yandex|baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest\/0\.|pinterestbot|slackbot|vkShare|W3C_Validator|whatsapp" />
            <add input="{QUERY_STRING}" pattern="_escaped_fragment_" />
        </conditions>
        <serverVariables>
            <set name="HTTP_X_PRERENDER_TOKEN" value="<removed>" />
        </serverVariables>
        <action type="Rewrite" url="https://service.prerender.io/https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" logRewrittenUrl="true" />
    </rule>

    <rule name="Vue" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_URI}" pattern="^/api/.*" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
    </rule>
</rules>

The problem is, when googlebot tries to access my site, most of the time it comes back with a URL Rewrite error 500. If I remove googlebot from the prerender rule, it will stop throwing the rewrite error, which leads me to believe the issue is with that rule, but their support team tell me it's not.
Can anyone see any glaringly obvious issues with my rules? Or know something I am missing?

A: It turns out this was due to ARR proxy not being turned on.
Because I host on Azure, it had to create a new file called applicationHost.xdt and add this:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <proxy xdt:Transform="InsertIfMissing" enabled="true" preserveHostHeader="false"
        reverseRewriteHostInResponseHeaders="false" />
        <rewrite>
            <allowedServerVariables>
                <add name="HTTP_X_PRERENDER_TOKEN" xdt:Transform="InsertIfMissing" />
            </allowedServerVariables>
        </rewrite>
    </system.webServer>
</configuration>

If you use IIS,  you can follow this link:
https://learn.microsoft.com/en-us/iis/extensions/configuring-application-request-routing-arr/creating-a-forward-proxy-using-application-request-routing


text:
Q: Garbage collector destroys singleton objects when suspending the app I have an UWP app with two singleton classes, one is for sessioning containing user info and the other one contains a list. When a user minimizes the app, it gets suspended and the garbage collector destroys the session and permission class, so the user has no rights after maximizing the app.
I don't want to use the OnSuspending and OnResume events to save/serialize the classes because the session info is needed because of toast notifications.
Is there a way I can tell the garbage collector to leave them alone completely?
I tried calling GC.Keepalive in the OnSuspending Event but that didn't help.
Edit: As requested, here is the code of my session singleton:
public class Session
{
    private Session()
    {

    }

    ~Session()
    {
        session = this;
    }

    private static Session session;

    public static Session Current
    {
        get
        {
            if (session == null)
                session = new Session();

            return session;
        }
    }

    public async Task<bool> LogIn(string username, string password)
    {
        ///
    }

    public void LogOut()
    {
       ///
    }

    public UserRights Permissions { get; set; }

    public User User { get; set; }

    public int UserId { get; set; }

    public string Token { get; set; }

I tried to bypass it via the finalizer, but there is a small time between suspending and the garbage collection. In this time the problem still exists.
When I maximize the app after the garbage collection, then it works.


text:
Q: AudioKit MIDI - Creating Virtual Outputs in Swift I want to create an Virtual Output port in my app, which can be recognised by other music apps.
Example is iSymphonic, were one is able to select a VO from a list generated by MIDIFlow.
I have tried .createVirtualPorts() which does not throw errors, but at the same time does not create VO's that are visible in iSymphonic.


text:
Q: Insert text in a List fallowing a pattern I have a List<String> of some extracted text, and I want to verify if the list meets this criteria (could contains many times this pattern and every one is an item in the list):
0      // A zero should always be here when two numbers are together
\r\n   // New line
number // any positive number
\r\n   // New line
number // Positive number, .length < = 4
\r\n   // New line

What I want is to verify that the first zero is always present, If not, insert it to match the previous list format.
text  --> Insert a zero after this text
\r\n
4
\r\n
1234
\r\n

To...
text
\r\n
0     --> the inserted zero
\r\n
4
\r\n
1234
\r\n

So, I know I could use the .Insert(index, string) inside a loop, in fact I'm using a for to loop the list with a lot of ugly validations
public Regex isNumber = new Regex(@"^\d+$");

// When the list is been build and a possible match is found call this method:
private void CheckIfZeroMustBeAdded(List<string> stringList)
{
    int counter = 0;

    for (int i = stringList.Count - 1; i > 1; i--)
    {
        if (stringList[i].Equals(Environment.NewLine))
        {
            // Do nothing
        }
        else if (counter == 2)
        {
            if (!stringList[i].Equals("0"))
            {
                stringList.Insert(i, string.Format("{0}{1}", Environment.NewLine,"0"));
                break;
            }
        }
        else if (ExtractionConst.isNumber.Match(stringList[i]).Success && !stringList[i].Equals("0")
        {
            // There are two numbers together
            counter++;
        }
        else
        {
            break;
        }
    }
}

but.. Is there any efficient way of doing this?

A: The best solution for you is using Regex, try this:
//Add using System.Text.RegularExpressions first
string input = ....;// It's up to you
string output = Regex.Replace(input,"([^0])(\r\n([1-9]|\\d{2,})\r\n([1-9]|\\d{2,4})\r\n)","$1\r\n0$2");


text:
Q: reading strings from a file in c I am reading a string from a file in C. The string is supposed to have a specific length and start with thisisnumbr. If both requirements are met, then something else is supposed to happen. Furthermore, I want to prevent that anything unexpected in the file might cause a crash.
My code:
#define MYSTRING "thisisnumb-"

void read_mystring()
{
  int c, i = 0, len =0 ;
  char input[sizeof( MYSTRING)+2] ;
  char check[] =  MYSTRING ;
  FILE *file ;
  file = fopen("/pathto/myfile", "r") ;
  if (file) {
      while ((c = getc(file)) != EOF)
      {
          input[i] = c ;
          i++ ;
          if (i > sizeof(input))
          {
            len = 1 ;
            break ;
          }
      }
      fclose(file) ;
  }
  if(strncmp(input,check,sizeof(check)-1) == 0  && len == 0)
  {
   //do something
  }
}

So input has the size of MYSTRING plus 2 more characters (supposed to be 2 digits.
In the while loop I am reading myfile and storing it in input. With
if (i > sizeof(input))
{
   len = 1 ;
   break ;
}

I make sure that the string reading stops if the string in the file appears to be longer than expected.
Then I compare the beginning of the string with strncmp and check if len==0 to make sure the string starts with MYSTRING AND also has the correct length.
If so, something else happens.
This works, meaning that I don't get an Segmentation fault if there is no file, the string in file is too long, or the string in the file doesn't start with MYSTRING.
I was wondering, if there is anything else that might break my program?
And also, when I do printf("input=%s\n",input) at the end of my function, I get my string but also an additional line with garbage?
Any ideas?

A: There are a number of things you need to look at. Foremost sizeof MYSTRING includes the storage size required for the nul-byte. It is strlen + 1. You must be very careful mixing sizeof string (on a char array) and string length.
Next, if you call this function more than once throughout your code, it may be better to fopen the file in the caller and pass a FILE* parameter to your function. (it's up to you) I would do:
/* open file in caller to prevent repeatedly opening and closing file */
FILE *fp = fopen (fname, "r");

if (!fp) {  /* validate file open for reading */
    fprintf (stderr, "error: file open failed '%s'.\n", fname);
    exit (EXIT_FAILURE);
}

Next, there are many ways to handle your function itself. As mentioned in the comment, you are better served by providing a buffer large enough to handle long strings in the file (and even then you need to validate a complete line read occurred) Reading with fgets the '\n' is read and included in the resulting buffer, so you will need to remove the trailing '\n' by overwriting with a nul-byte, e.g.
    char buf[BUFSZ] = "";
    while (fgets (buf, BUFSZ, fp)) {
        size_t len = strlen (buf);
        if (len > 0 && buf[len - 1] == '\n')
            buf[--len] = 0;
        else {
            /* handle more chars remain in line than buf can hold */
        }

After validating your line read, you simply need to check the length against your requirement and then check that the last two characters are digits, e.g.
        if (len != sizeof MYSTRING + 1) {
            /* not right length - handle error */
        }

        if (strncmp (buf, MYSTRING, sizeof MYSTRING - 1) == 0 &&
            isdigit (buf[sizeof MYSTRING - 1]) &&
            isdigit (buf[sizeof MYSTRING]))
        {
            /* string matches criteria -- do something */
        }
        else {
            /* doesn't meet conditon -- handle error */
        }

Putting it altogether, and adding a moretoread flag to read until the end of a long line if it exceeds BUFSZ, you would have something similar to the following:
void read_mystring (FILE *fp)
{
    char buf[BUFSZ] = "";
    int moretoread = 0;

    while (fgets (buf, BUFSZ, fp)) {
        size_t len = strlen (buf);
        if (len > 0 && buf[len - 1] == '\n') { /* check for newline */
            buf[--len] = 0;                    /* overwrite with nul-byte */
            moretoread = 0;                    /* reset moretoread flag */
        }
        else {
            /* handle more chars remain in line than buf can hold */
            moretoread = 1;
        }
        if (moretoread)    /* you are way over your wanted length */
            continue;      /* just read until newline encountered */
        if (len != sizeof MYSTRING + 1) {
            /* not right length - handle error */
        }

        /* check prefix followed by two digits */
        if (strncmp (buf, MYSTRING, sizeof MYSTRING - 1) == 0 &&
            isdigit (buf[sizeof MYSTRING - 1]) &&
            isdigit (buf[sizeof MYSTRING]))
        {
            /* string matches criteria -- do something */
        }
        else {
            /* doesn't meet conditon -- handle error */
        }
    }
}

Include ctype.h for isdigit().
Like I said, there are many, many different approaches you can take, these are just thoughts based on your conditions and one way of doing it.


text:
Q: Sphinx catch error while reading sources I am using sphinx for documentation. and have used the make html and make latexpdf through a bash script.
when running the bash script, and when make html is run, it shows ERROR in teh rst file after the Reading sources.
make clean
+ make clean
rm -rf _build/*
make html
+ make html
sphinx-build -b html -d _build/doctrees   . _build/html
Running Sphinx v1.3b3
making output directory...
loading pickled environment... not yet created
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 2 source files that are out of date
updating environment: 2 added, 0 changed, 0 removed
reading sources... [100%] index
/home/sphinx/Inder.rst:12:WARNING: Bullet list ends without a blank line; unexpected unindent.
/home/sphinx/Inder.rst:12: ERROR: Document may not end with a transition.
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index

How can i catch this error in the bash script or send it to another variable.
i have tried grep ERROR with the make html, but it gives blank.

A: sphinx-build will probably print output on both stdout and stderr so you likely want to capture both streams.
You can do this like:
out=$(make html 2>&1)
if grep -q 'ERROR: ' <<< "$out"; then
    # do some error handling
fi


text:
Q: resize DIV matching the new content with jquery I have a DIV which shows one image at once coming from an ajax script, the images are all different in height and are showed with fadeIn/fadeOut (just for the  tag)
How can I allow to resize the DIV (that contains the img tag of course) "sliding" based on the new content before the images that fadein changes the DIV height very rudely? :P
Thanks

A: You need to use the jquery animate function to change the width and height of the div.
Hope this helps.

A: Well do Something like this
$(".change").click(function() {
  $(".mydiv").fadeOut('slow');
  $(".myimg").attr("src",'');
  $(".myimg").attr("src","linktonewimage.jpg");
  var newheight = $(".myimg").height();
  $(".mydiv").css("height",newheight+"px");
  $(".mydiv").fadeIn('slow');
});

I am assuming you have a <img> tag with myimg class inside a div with mydiv class.
Check the DEMO HERE

A: Have you tried using lightbox? It might do all you are talking about here, sans having to write it yourself. It can be heavily customized with CSS and uses animation.


text:
Q: How to specify Replace function in VBA I'm using Replace function in SQL query, it is working in access sql query design mode but not working in access VBA. Throwing expected end of statement. I tried all the ways but not working. CM column has a string like this ;#WR_1;#WR_2;#WR_3;#WR_4;# and I'm trying to get value WR_2 where ever the string occurs in CM column
strSQL = "SELECT * FROM WT_table " & _
"WHERE [CM] IS NOT NULL " & _
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*'; ;"

A: Just remove the second semi-colon (;) from the end of the last line - you have two of them, making it appear that there are multiple statements to be executed.
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*';"

In addition, as pointed out by simoco, you have a pair of double-quotes in your Replace function.  I'm not certain whether you mean to have two single-quotes or not, but this would be the right code to use in that case:
"AND (';' & Replace([CM], '#', '') & ';') Like '*;WR_2;*';"


text:
Q: How to change the A3C Tensorflow example to play Atari games? I followed the Tensorflow tutorial which implemented A3C in order to do well in the cartpole environment, and wanted to use it as a starting point for a game-playing bot for some Atari games. However, if I simply change the environment to, say, Frostbite-v0, I get this error when the worker threads start:
Exception in thread Thread-4:
Traceback (most recent call last):
  File "threading.py", line 917, in _bootstrap_inner
    self.run()
  File "a3c.py", line 286, in run
    action = np.random.choice(self.action_size, p=probs.numpy()[0])
  File "mtrand.pyx", line 1135, in mtrand.RandomState.choice
ValueError: object too deep for desired array

I'm a complete noob in Deep Learning, but I guess the problem is in how the network just has Dense Layers taking the input which in this case, taking this as a reference, has an environment with a different shape, meaning not Box(4,) as in the cartpole example but Box(210, 160, 3).
How do I change the example so that it works properly with such an observation? Do I have to add/change layers? And in general so that it performs correctly for the Frostbite-v0 environment?
Edit: Another thing that bugs me is that the state_size parameter in the ActorCriticModel is set but never used, at least from an outside perspective. Does the model use it in any way or does it just sit there as an unused parameter?

A: I am afraid you are going to need to change lots of things: first, to deal with inputs that are images you would need to add convolutional layers. Second, traditionally images of atari games are downsampled from 210x160x3 to 64x64(tiny grayscale images)or something like that. So if you are a beginner I think it might be better to check out some other tutorials. For example famous blog post from a famous guy Karpathy


text:
Q: spring mvc url rewrite by nginx I'm using tag mvc:resources to handle static files in my spring mvc projects.
Well I want to rewrite urls for SEO using, such as /page?id=1 >> /page/1.html .
[spring-context.xml]
<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/view/css/"    mapping="/css/**" />
<mvc:resources location="/WEB-INF/view/images/" mapping="/images/**" />
<mvc:resources location="/WEB-INF/view/js/" mapping="/js/**" />
<mvc:resources location="/WEB-INF/view/jsp/" mapping="/jsp/**" />

[nginx.conf]
rewrite      ^/page/(.*)(.html)$ /page?id=$1 last;
proxy_pass   http://127.0.0.1:8080/project/;

Problems:
All the static files will be added a prefix page, absolutly it can not get the correct file,
such as 'localhost/js/index.js' becoming 'localhost/page/js/index.js'
So how could I solve this problem ? Any suggestions ?
I have tried using urlrewritefilter(org.tuckey) and get the same situation QAQ

A: I am sure by now you would have found your response but I will answer for those after you who would be looking for the same answer.
location ~ ^/script/(.*)$ {
                        alias   /var/lib/tomcat7/webapps/ROOT/assets/js/$1;
                        autoindex off;
                }

    location ~ ^/styles/(.*)$ {
                        alias   /var/lib/tomcat7/webapps/ROOT/assets/css/$1;
                        autoindex off;
                }

    location ~ ^/images/(.*)$ {
                        alias   /var/lib/tomcat7/webapps/ROOT/assets/images/$1;
                        autoindex off;
                }

Above is the equivalent of in nginx of the the following spring resource mapping
<mvc:resources mapping="/images/**" location="/assets/images/"/>
<mvc:resources mapping="/styles/**" location="/assets/css/"/>
<mvc:resources mapping="/script/**" location="/assets/js/"/>

Hope this helps
Best Regards,


text:
Q: Recursive use of make for LaTeX I am using a Makefile to handle building a LaTeX document. I have two directories ./tikz and ./feyn that contain .tex files and Makefiles to compile them. They produce figures which I then include in the main document. I am using the following Makefile to compile the main document:
.PHONY : tikz feyn

main.pdf : main.tex feyn tikz
    pdflatex main.tex

tikz :
    $(MAKE) -C tikz

feyn :
    $(MAKE) -C feyn

The problem is that even if main.pdf is up-to-date, running make will execute its rule anyways since phony targets are never up-tp-date. However, if I do not declare tikz and feyn as phony, their rules will not get executed. How can I fix this?

A: It depends, what do you want to do in the directories feyn and tikz. I guess that in tikz you want to generate some PDFs. Simply use an actual file as dependency. E.g.,
main.pdf : main.tex feyn tikz
    pdflatex main.tex

tikz : tikz/somefile.pdf

tikz/somefile.pdf:
    $(MAKE) -C tikz

# etc.

An alternative is to decouple main.pdf from your phony targets by using order targets:
.PHONY : tikz feyn

main.pdf : main.tex | feyn tikz
   pdflatex main.tex

tikz :
   $(MAKE) -C tikz

feyn :
   $(MAKE) -C feyn

all: feyn tikz main.pdf

A: Don't run pdflatex in the subdirectories. Instead run latexmk in those diectories. The call to latexmk always happens (since the targets are phony), but latexmk will bail if nothing needs to be done for a subdirectory.
And then also probably use latexmk for the top-level target too.


text:
Q: environment variable use in Cloudflare workers node.js I saw many articles setting environment variables in Cloudflare workers. but I am not able to read or retrieve it in node.js
Code:
async function handleRequest(request) {
  if ('OKOK' == process.env.API_KEY) {
    return new Response('found', {
      headers: { 'content-type': 'text/plain' },
    })
  }
}

wrangler.toml
name = "hello"
type = "javascript"

# account_id = ""
workers_dev = true
[env.production]
name = "API_KEY"

A: Cloudflare Workers does not use Node.js. In Workers, environment variables become simple globals. So, to access your environment variable, you would just write API_KEY, not process.env.API_KEY.
(Note: Workers is currently transitioning to a new syntax based on ES modules. In that syntax, environment variables work differently; an env object is passed to the event handler containing all variables. Most people aren't using this new syntax yet, though. You would know if you are using it if your JavaScript uses export default { to define event handlers; on the other hand, if it uses addEventListener("fetch", ...), then it is using the old syntax.)

A: I recommand you use Miniflare now, pretty easy and strenght forward
"start": "miniflare --watch --debug -e .env"

This is an official Cloudflare lib by the way:
https://www.npmjs.com/package/miniflare
Reasone:
Miniflare is a simulator for developing and testing Cloudflare Workers.

 Fun: develop workers easily with detailed logging, file watching
and pretty error pages supporting source maps.
 Full-featured: supports most Workers features, including KV,
Durable Objects, WebSockets, modules and more.
⚡ Fully-local: test and develop Workers without an internet
connection. Reload code on change quickly. It's an alternative to
wrangler dev, written in TypeScript, that runs your workers in a
sandbox implementing Workers' runtime APIs.


text:
Q: Regex to replace between second occurance of symbol A and symbol B I have an example string to match:
s = 'https://john:ABCDE@api.example.com'
I am trying to replace the string ABCDE between the 2nd colon and the first occurrance of @. So my desired output is:
s_out = 'https://john:REPLACED@api.example.com'
My current code is:
import re
s_out = re.sub(r":*(.+)@api.example.com", 'REPLACED', s)

But i am unable to replace this currently.

A: You can start the match with the colon, and then prevent matching either : or @ using a negated character class
Capture in a group starting from the @ sign, which you can then use in the replacement.
:[^\s:@]*(@api\.example\.com)

And replace with
:REPLACED\1

See a regex101 demo.
Example
import re

s = 'https://john:ABCDE@api.example.com'
pattern = r":[^\s:@]*(@api\.example\.com)"
s_out = re.sub(pattern, r":REPLACED\1", s)
print(s_out)

Output
https://john:REPLACED@api.example.com


text:
Q: Jacobian and determinants Start with variables $(a_1, a_2, a_3, … a_n)$ and transform it to the system $(x_1, x_2, x_3, … x_n)$ where the xi's are the solutions to $x^n + a_1x^{n-1} + a_2x^{n-2} + a_3x^{n-3} +…+ a_n$. The Jacobian transformation seems to be $da_1 da_2 da_3 … da_n = J' dx_1 dx_2 dx_3 … dx_n$ where $J'$ is the square root of the negative of the determinant of $x^n + a_1x^{n-1} + a_2x^{n-2} + a_3x^{n-3} +…+ a_n$. Is this true? Is it well known?

A: Let the polynomial be $p(x).$ If you write down the Jacobian of the map which maps the $x_i$ to the $a_i$ (which are symmetric functions of the $x_i$), you will see that the columns just have the coefficients of $p(x)/(x-x_i)$ (in other words, the symmetric functions of all but the $i$-th variable). This determinant, as a polynomial in the $x_i$ will have degree $n(n-1)/2,$ and will vanish whenever two of the $x_i$ are equal, so it is a constant multiple of the product of $(x_i - x_j),$ for $i>j$ (which is a square root of the discriminant). Computing the constant is easy by induction.

A: You find a lot of information in:
Dmitri Alekseevky, Andreas Kriegl, Mark Losik, Peter W. Michor: Choosing roots of polynomials smoothly, Israel J. Math 105 (1998), p. 203-233. (pdf),
and in related later papers. The formula that you seek (or the inverse) is on page 7.


text:
Q: Soft Keyboard doesn't show on focus I have a small function to open the soft keyboard when a EditText is programmatically focused as shown here...
public void getUserName() {
    EditText tv = (EditText)findViewById(R.id.user_info_name);
    tv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (b) {
                showDialog("Focused!");
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            }
        }
    });
    tv.selectAll();
    tv.requestFocus();
}

However, the soft keyboard doesn't appear automatically but the dialog DOES show stating focused. In order to get the keyboard to appear I have to click inside the EditText.
My XML is as follows...
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:id="@id/user_info_name"
        android:editable="true"
        android:hint="@string/user_info_name"
        android:inputType="textCapWords|textPersonName"
        android:textColor="@color/blue_gray"
        android:maxLength="50"
        android:layout_centerInParent="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:enabled="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

Can someone please advise why it's not working or what I am missing / failing to address.
Thanks in advance as always.
SOLVED: The following change to the function fixed the issue...
public void getUserName() {
    EditText tv = (EditText)findViewById(R.id.user_info_name);
    tv.selectAll();
    tv.requestFocus();
    InputMethodManager imm = (InputMethodManager)this.getSystemService(this.INPUT_METHOD_SERVICE);
    imm.showSoftInput(tv,InputMethodManager.SHOW_IMPLICIT);
}


text:
Q: Why using  with Font Awesome more semantically correct than ? I've been using Font Awesome for a while and I wonder one thing which tag should I use for it.
Here is said that they like the  tag for brevity, but using a  is more semantically correct.
I read specification for  and . Unfortunately, I can't find the difference, they're both have the same context in which they can be used.

A: The difference between   and  is that  was originally intended for italics font, while  is intended to encapsulate a piece of content without changing any css rules immediately. In other words,  can be used for any custom css action you want to apply.
Therefore, from a theoretical and historical perspective,  would be a more proper choice.
However,  is much shorter and the effect in the browser is identical, so choose  in order to optimize your page speed with a few microseconds, and your coding speed with a few seconds.

A: It is because  is for italic text in html and  can contain any inline element. Thus using span instead of i is more semantically correct. But still  is also not denoting for using icons in html, so this is also not more semantically correct until you add a role as img like this:


text:
Q: UML - may a uml diagram contain different types of uml models? ^ e.g. is it allowed to link directly from a use case to an activity diagram - or-
from a class diagram to a use case by connecting them with an association note -or - form a component diagram to a object diagram?
also, if it's allowed, and I firmly believe it is since I saw such diagrams, where does it say so in the omg formal/15-03-01 document?
Edit:
For example where does the specification say something like this is even allowed?

A: I'm looking at what is currently the latest UML specification, the Unified Modeling Language v2.5, released in June 2015. It is specified in an English language specification and four XMI documents.
I think there are two things to consider to provide a complete answer.
The first thing to keep in mind is the difference between a "model" and a "diagram". Annex A defines models and diagrams. Elements, such as classes and nodes and associations and actors and use cases, are part of a model. Different models have different valid elements, which are described in the standard. Diagrams are graphical views of the model. A repository contains one or more models of a software system.
The second thing to consider is the usage of UML. UML is a language, a set of standard notations with defined meanings. Martin Fowler identified different UML modes, such as sketch, blueprint, programming language. Sketches and blueprints are designed for human consumption. They take advantage of the defined notations to reduce ambiguity in a diagram and make it easy to communicate ideas in a shared language. UML as a programming language is a mode designed to be consumed by a tool, such as for autogenerating code.
The combining of models is not allowed by the formal specification. The definition of an Activity model doesn't allow for the inclusion of elements such as actors, lifelines, and objects. You can see this in the XMI documents, or in Section 15 of the English-language standard. There's simply no concept of this.
However, when creating a diagram (either by hand or with a software package), there's nothing that precludes this. For example, Figure 18.12 shows a use case diagram that is associated with a state machine diagram. Tools may show these in different formats. I'd have to dig deeper to see if it's possible to link all of the diagrams that you mentioned, but it is possible to associate an element of one model with an element in a different model, so that the output diagram may contain visual representations of multiple models in one view.
Annex A specific supports this:

This taxonomy provides a logical organization for the various major kinds of diagrams. However, it does not preclude mixing different kinds of diagram types, as one might do when one combines structural and behavioral elements (e.g., showing a state machine nested inside an internal structure). Consequently, the boundaries between the various kinds of diagram types are not strictly enforced.

A: Your example looks a lot like one of the example diagrams in the official UML 2.5 specification:

So I guess if it is in the specification we can be reasonably sure this is valid UML.

A: I didn't really expect a nitpicking about what a diagram and what a model is.
Nevertheless I think I found one notation that does the trick flawlessly.
It is known as 'Information Flow' and uses the dependency association and the keyword flow in double chevrons/guillemets.
A book in my hands says: "An information flow specifies that one or more information items circulate from its sources to its targets. Information flows require some kind of 'information channel for transmitting information items.'"
So this is what it looks like
And the official formal/15-03-01 document says in
20.1.3 Semantics (about InformationFlows) :

In practice, a constraint on InformationFlow requires that sources and targets must be one of the following types: Actor, Node, UseCase,
  Artifact, Class, Component, Port, Property, Interface, Package,
  ActivityNode, ActivityPartition, Behavior, and InstanceSpecification.

..so perfect, that's exactly what I was looking for. Well there might be other ways to link models directly, but I had to find something in the official OMG docs.


text:
Q: Birthday "Paradox" -- with a different perspective Background: Many people are familiar with the so-called Birthday "Paradox" that, in a room of 23 people, there is a better than 50/50 chance that two of them will share the same birthday. In its more general form for n people, the probability of no two people sharing the same birthday is $p(n) = \frac{365!}{ 365^n *(365-n)!}$. Similar calculations are used for understanding hash-space sizes, cryptographic attacks, etc.
Motivation: The reason for asking the following question is actually related to understanding a specific financial market behavior. However a variant on the "Birthday Paradox" problem fits exactly as an analogy and is likely to be of wider interest to people with different backgrounds. My question is therefore framed along the lines of the more familiar  "Birthday Paradox", as follows.
Situation: There are a total of 60 people in a room. Of these, it turns out that there are 11 (eleven) PAIRS of people who share the same birthday, and one TRIPLE (i.e. group of 3 people) who have the same birthday. The remaining 60 - 2*11 - 3 = 35 people have different birthdays. Assuming a population in which any day is equally likely for a birthday (i.e. ignore Feb 29th & possible seasonal effects) and, given the specified distribution of birthdays, the questioner would like to understand how likely (or unlikely) it is that these 60 people were really chosen at random. This question was originally posed on another site where it was left unanswered, but the questioner was advised to re-state the question in the form that now follows below.
Question: "If 60 people are chosen at random from a population in which any day is equally likely to be a person's birthday, what is the probability that there are 11 days on which exactly 2 people share a birthday, one day on which exactly 3 of them share a birthday, and no days on which 4 or more people share a birthday?"

A: When in doubt, simulate. (I'm sure that you can actually put together a formula, but it will likely be painful to look at.) I'll work with the criterion being "at least one triple birthday" and "at least eleven double birthdays" -- changing the code below to checking for exactly so many birthdays is not hard.
n.sims <- 1e5
n.persons <- 60
counter <- 0
pb <- winProgressBar(max=n.sims)
for ( ii in 1:n.sims ) {
    setWinProgressBar(pb,ii,paste(ii,"of",n.sims))
    set.seed(ii)
    birthdays <- sample(x=365,size=n.persons,replace=TRUE)
    birthday.table <- table(birthdays)
    if (    sum(birthday.table>=4) == 0  &
                sum(birthday.table==3) >= 1  &
                sum(birthday.table==2) >= 11 ) counter <- counter+1
}
close(pb)
counter/n.sims

Out of 100,000 simulations, I get six hits, for a $p$-value of $p=0.00006$. If you twiddle the set.seed() command, e.g., to set.seed(2*ii), you will get slightly different results (in this case $p=0.00004$), which serves as a sort of sensitivity analysis.

A: Assuming you aim for the case that exactly (so not at least) 11 double birthdays and 1 triple birthdays occur:
$$\begin{align}p(60,n_2=11,n_3=1) &= \frac{\text{possibilities with 11 double birthdays and 1 triple birthdays}}{\text{all possibilities}}\\
&= \frac{\frac{60!}{35!22!3!} 21!! \,\cdot \,365 \cdot 364 \cdot \, ...  \, \cdot (365-n+1+1\cdot11+2\cdot1)}{365^{60}}\end{align}$$
which my calculation in R
factorial(60)/(factorial(35)*factorial(22)*factorial(3))*
pracma::factorial2(21)*
cumprod(319:365)[47]/365^60

approximates as $3.64 * 10^{-5}$
Explanation of the terms in the calculation

*

*$365^{60}$ is the number of ways to select random 60 birthdays among equally probable 365 days.

*$365 \cdot 364 \cdot \, ...  \, \cdot (365-n+1+1\cdot11+2\cdot1)$ is the number of ways to select random 60-11-2 unique days among equally probable 365 days.

*$\frac{60!}{35!22!3!}$ is the number of unique ways to partition 60 people in groups of 35, 22, and 3 (the numbers of people with single birthdays, double birthdays, and triple birthdays)

*$21!! = 21 \cdot 19 \cdot ... \cdot 3 \cdot 1$ is the number of ways that we can partition the 22 people in the double birthdays group into pairs.


text:
Q: Why doesn't rails honor my date formats in en.yml? I want to have a custom format, :results so I can do a @obj.date.to_s(:results) call in my views.
If I put my custom format in an initializer then it works:
Time::DATE_FORMATS[:results] = "%D"

However if I try and put that in my en.yml file then it does not work (as in it will not format it as expected):
en:
  time:
    # See also config/initializers/time_formats.rb for lambda based configs
    formats:
      results: '%D'
  date:
    formats:
      default: '%m/%d/%Y"'
      results: '%D'

Everything I read suggests that this should work.  What am I missing?
EDIT: This is basically a duplicate of Rails not picking up custom date & time formats in en.yml So I guess the question is how can I set the defaults in yml rather than an initialize (it is easier to manage).  Is there a built in way, or do I need to manually load the yaml file and set the Time::DATE_FORMAT hash myself?

A: The answer is in Rails not picking up custom date & time formats in en.yml
The second way you mentioned is using I18n (internationalization) which means to use it you hace to call it.
In your views you can do
<%= l @obj.date, format: :result %>


text:
Q: How to accomplish tangential shading (i.e. not radial shading)? I want to produce an open ring with a color gradient that goes from white (or faint red) to red and then back to white (or faint red) in the angular/tangential direction.
In the image attached below, the gradient is linear and not to my liking. What I want is a gradient that goes (anti clock wise): white at two o'clock -- red at 9 o'clock -- back to white at 4 o'clock.

.
Ideally, I would like a flexible approach where the start and stop angle can be set arbitrarily.
I have spent many hours reading the pgf/tikz-manual and also this forum. I have not been able to find a solution. Any ideas?
Code example:
\documentclass[tikz,]{standalone}
\usepackage{tikz}
\begin{document}
\begin{centering}
\begin{tikzpicture}[scale=1]

\def\aStartA{30}
\def\aStopA{330}

\filldraw[gray!50,left color=white!25, right color=white!25, middle color=red!25] (\aStartA:2cm)--(\aStartA:2cm)--(\aStartA:3cm) arc (\aStartA:\aStopA:3cm)--(\aStopA:2cm)--(\aStopA:2cm) arc (\aStopA:\aStartA:2cm);
\draw[thin, color=gray] (\aStartA:0)--(\aStartA:3.5cm);
\draw[thin, color=gray] (\aStopA:0)--(\aStopA:3.5cm);
\end{tikzpicture}
\end{centering}
\end{document}

A: UPDATE: A solution based on the color wheel modification.
\documentclass[tikz,border=3.14pt]{standalone}

\makeatletter
\newtoks\pgf@ps@toks
\newcount\c@pgf@ps

\def\pgf@ps@sp{ }

\def\pgf@ps@esettoks#1{\edef\pgf@ps@tmp{#1}\pgf@ps@toks\expandafter{\pgf@ps@tmp}}

\def\pgf@ps@repop#1#2{%
  \c@pgf@countb=#2\relax%
  \def\pgf@ps@op{#1}%
  \def\pgf@ps@ops{}\pgf@ps@@repop}
\def\pgf@ps@@repop{%
  \ifnum\c@pgf@countb<1\relax%
  \else%
    \edef\pgf@ps@ops{\pgf@ps@op\pgf@ps@ops}%
    \advance\c@pgf@countb by-1\relax%
    \expandafter\pgf@ps@@repop%
  \fi%
}

\def\pgf@ps@generate@ps{%
  \c@pgf@counta=\pgf@ps@ncol\relax%
  \c@pgf@countb=\c@pgf@counta%
  \advance\c@pgf@countb by-1\relax%
  \pgf@ps@esettoks{ \noexpand\pgf@ps@interp{col@\the\c@pgf@counta}{col@\the\c@pgf@countb} }%
  \pgfmathloop
  \ifnum\c@pgf@counta<2\relax%
  \else%
    \c@pgf@countb=-\c@pgf@counta%
    \advance\c@pgf@countb by\pgf@ps@ncol\relax%
    \advance\c@pgf@counta by-1\relax%
    \pgf@ps@repop{pop\pgf@ps@sp}{\c@pgf@countb}%
    \c@pgf@countb=\c@pgf@counta%
    \advance\c@pgf@countb by-1\relax%
    \ifnum\c@pgf@countb=0\relax%
      \c@pgf@countb=\pgf@ps@ncol\relax%
    \fi%
    \pgf@ps@esettoks{ \the\c@pgf@counta\pgf@ps@sp eq { \pgf@ps@ops \noexpand\pgf@ps@interp{col@\the\c@pgf@counta}{col@\the\c@pgf@countb} }{ \the\pgf@ps@toks } ifelse}%
  \repeatpgfmathloop%
  \c@pgf@counta=\pgf@ps@ncol\relax%
  \advance\c@pgf@counta by-2\relax%
  \pgf@ps@repop{dup\pgf@ps@sp}{\c@pgf@counta}%
  \pgf@ps@esettoks{ \pgf@ps@ops \the\pgf@ps@toks }%
}

\def\pgf@ps@colorstorgb#1{%
  \c@pgf@ps=1\relax%
  \pgfutil@for\pgf@ps@:={#1}\do{%
     \pgf@ps@coltorgb{\pgf@ps@}{col@\the\c@pgf@ps}%
     \advance\c@pgf@ps by1\relax}%
}

\def\pgf@ps@coltorgb#1#2{%
 \edef\pgf@ps@marshal{\noexpand\pgfshadecolortorgb{#1}}%
 \expandafter\pgf@ps@marshal\expandafter{\csname#2\endcsname}%
}

\def\pgf@ps@rgb#1{\csname#1\endcsname}
\def\pgf@ps@interp#1#2{%
  \pgf@ps@rgb{#1red} mul exch \pgf@ps@rgb{#2red} mul add
    5 1 roll
  \pgf@ps@rgb{#1green} mul exch \pgf@ps@rgb{#2green} mul add
    3 1 roll
  \pgf@ps@rgb{#1blue} mul exch \pgf@ps@rgb{#2blue} mul add
}

\def\pgfdeclarecolorwheelshading#1#2#3{%
  \pgf@ps@getcols{#3}%
  \pgfmathparse{mod(#2+360/\pgf@ps@ncol-90,360)}%
  \pgf@x=\pgfmathresult pt\relax%
  \ifdim\pgf@x<0pt\relax%
    \advance\pgf@x by360pt\relax%
  \fi%
  \edef\pgf@ps@rot{\pgfmath@tonumber{\pgf@x}}%
  \pgf@ps@generate@ps%
  \pgf@ps@esettoks{%
    \noexpand\pgfdeclarefunctionalshading[#3]{#1}%
    {\noexpand\pgfpoint{-50bp}{-50bp}}{\noexpand\pgfpoint{50bp}{50bp}}%
    {\noexpand\pgf@ps@colorstorgb{#3}}%
    {%
      2 copy abs exch abs add 0.0001 ge { atan } { pop } ifelse
      \pgf@ps@rot\pgf@ps@sp add dup 360 ge { -360 add } { } ifelse
      360 \pgf@ps@ncol\pgf@ps@sp
      div div dup floor dup 3 1 roll neg add dup neg 1 add exch
      2 copy 2 copy 7 -1 roll 1 add
      \the\pgf@ps@toks}}%
  \edef\pgf@ps@marshal{\the\pgf@ps@toks}%
  \pgf@ps@marshal}

\def\pgf@ps@getcols#1{%
  \c@pgf@ps=0\relax%
  \pgfutil@for\pgf@ps@:={#1}\do{\advance\c@pgf@ps by1}%
  \edef\pgf@ps@ncol{\the\c@pgf@ps}%
}

\pgfdeclarecolorwheelshading{Austria}{0}{white,red!80,red,red!80}
\usetikzlibrary{shadings}
\usepgfmodule{nonlineartransformations}
\makeatletter

\begin{document}
\begin{centering}
\begin{tikzpicture}[scale=1]

\def\aStartA{30}
\def\aStopA{330}

\draw[thin, color=gray] (\aStartA:0)--(\aStartA:3.5cm);
\draw[thin, color=gray] (\aStopA:0)--(\aStopA:3.5cm);
\begin{scope}
\clip (\aStartA:2cm)--(\aStartA:2cm)--(\aStartA:3cm) arc (\aStartA:\aStopA:3cm)--(\aStopA:2cm)--(\aStopA:2cm) arc (\aStopA:\aStartA:2cm);
\shade[shading=Austria,rotate=45] [even odd rule]
        (0,0) circle (3);
\end{scope}
\end{tikzpicture}
\end{centering}
\end{document}

This is the output with acroread. It looks very different with preview.
Original answer: Here is a proposal using nonlinear transformations. The nonlinear transformation from section 103.4 of the pgfmanual transforms a horizontal box precisely to an arc as shown in your figure. So I just shade a horizontal box linearly and then subject it to the nonlinear transformation.
\documentclass[tikz,]{standalone}
\usepackage{tikz}
\usetikzlibrary{shadings}
\usepgfmodule{nonlineartransformations}
\makeatletter
\def\polartransformation{%
% \pgf@x will contain the radius
% \pgf@y will contain the distance
\pgfmathsincos@{\pgf@sys@tonumber\pgf@x}%
% pgfmathresultx is now the cosine of radius and
% pgfmathresulty is the sine of radius
\pgf@x=\pgfmathresultx\pgf@y%
\pgf@y=\pgfmathresulty\pgf@y%
}
\makeatother

\begin{document}
\begin{centering}
\begin{tikzpicture}[scale=1]

\def\aStartA{30}
\def\aStopA{330}

\filldraw[gray!50,left color=white!25, right color=white!25, middle color=red!25] (\aStartA:2cm)--(\aStartA:2cm)--(\aStartA:3cm) arc (\aStartA:\aStopA:3cm)--(\aStopA:2cm)--(\aStopA:2cm) arc (\aStopA:\aStartA:2cm);
\draw[thin, color=gray] (\aStartA:0)--(\aStartA:3.5cm);
\draw[thin, color=gray] (\aStopA:0)--(\aStopA:3.5cm);
\clip (\aStartA:2cm)--(\aStartA:2cm)--(\aStartA:3cm) arc (\aStartA:\aStopA:3cm)--(\aStopA:2cm)--(\aStopA:2cm) arc (\aStopA:\aStartA:2cm);
\pgftransformnonlinear{\polartransformation}
\shade[left color=red,right color=white](-6.33,2) -- (-1,2)--(-1,3) --(-6.33,3) -- cycle;
\shade[left color=red,right color=white](6.33,2) -- (1,2)--(1,3) --(6.33,3) -- cycle;
\end{tikzpicture}
\end{centering}
\end{document}

ADDENDUM: I tried to make the code cleaner by switching to low level commands and using \pgfsetadditionalshadetransform on the shading. Unfortunately with very limited success
\documentclass[tikz,]{standalone}
\usepackage{tikz}
\usetikzlibrary{shadings}
\usepgfmodule{nonlineartransformations}
\makeatletter
\def\polartransformation{%
% \pgf@x will contain the radius
% \pgf@y will contain the distance
\pgfmathsincos@{\pgf@sys@tonumber\pgf@x}%
% pgfmathresultx is now the cosine of radius and
% pgfmathresulty is the sine of radius
\pgf@x=\pgfmathresultx\pgf@y%
\pgf@y=\pgfmathresulty\pgf@y%
}
\makeatother

\begin{document}
\pgfdeclarehorizontalshading{myshadingG}{5.34cm}
 {color(0cm)=(red); color(1cm)=(red!90);  color(3.34cm)=(red!10);
 color(4.34cm)=(white)}

\begin{centering}
\begin{tikzpicture}[scale=1]

\def\aStartA{30}
\def\aStopA{330}

\draw[thin, color=gray] (\aStartA:0)--(\aStartA:3.5cm);
\draw[thin, color=gray] (\aStopA:0)--(\aStopA:3.5cm);
\begin{scope}
\clip (\aStartA:2cm)--(\aStartA:2cm)--(\aStartA:3cm) arc (\aStartA:\aStopA:3cm)--(\aStopA:2cm)--(\aStopA:2cm) arc (\aStopA:\aStartA:2cm);
\pgftransformnonlinear{\polartransformation}
\pgfsetadditionalshadetransform{\polartransformation}
\pgfpathrectangle{\pgfpoint{-6.34cm}{2.00cm}}{\pgfpoint{5.34cm}{1cm}}
\pgfpathrectangle{\pgfpoint{-6.34cm}{2.00cm}}{\pgfpoint{-5.34cm}{1cm}}
\pgfshadepath{myshadingG}{0}
\end{scope}
\end{tikzpicture}
\end{centering}
\end{document}

(Yes, I also see that there is a small gap, but that's not the point.) The point is that \pgfsetadditionalshadetransform{\polartransformation} doesn't seem to have an effect. However, there is no error message either. To me it seems a bit like this just gets ignored.