text:
Q: iOS Fastlane Gym - Extra Incorrect Provisioning Profile When Building App I'm in the process of setting up Fastlane so that it uses manual provisioning profiles, which i'm managing via Match. Match is set up and working fine, and i've managed to set the correct provisioning profiles correctly in XCode via XCConfig files that point to each of the required targets (one for the main app and two for notifications related targets).
However, when I build the app in Fastlane, Gym is having problems detecting the correct provisioning profile because an extra, unwanted provisioning profile is being incorrectly identified. This is the code from my fastfile with placeholder bundles/provisioning profile names. You can see that I'm only specifying 3 profiles, and that I want an app-store build.
I'm receiving this warning that there are multiple profiles for bundle identifiers as part of the output.
And in the gym summary, I can see that there is an extra unrequested provisioning profile being displayed, which I've circled in blue.
The app does build successfully, in spite of the errant profile, but I'd prefer that it wasn't there at all. Where is gym pulling the errant provisioning profile from, and how do I stop it from being detected as one of the profiles for the build.
Thanks


text:
Q: Using Zend Mail Pop3 as a module I would like to use the Mail module of Zend Framework. I have extracted all the Zend lib in my project lib folder.
So how can I load the Mail module for using this module: http://framework.zend.com/manual/1.0/en/zend.mail.read.html?
I have tried this:
include("lib/Zend/Loader.php");
Zend_Loader::loadClass('Mail');

$mail = new Zend_Mail_Storage_Pop3(array('host'     => 'xxxxx',
                                         'user'     => 'xxxxx',
                                         'password' => 'xxxxx'));

My project structure is this:
-project->lib->Zend->All the Zend lib files

-projects/index.php

For example:
 Warning: require_once(Zend/Mail/Transport/Abstract.php) [function.require-once]: failed to open stream: No such file or directory

Do I really have to modify all the require_once manually?
But I have returned errors about include path in others module files.
Thanks a lot.

A: Try:
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

See the autoloader reference:

*

*http://framework.zend.com/manual/en/learning.autoloading.usage.html
and php's __autoload function if you want to write custom autoloader.
You may also add the paths with the libraries to the include_path (see set_include_path/get_include_path)
e.g.
set_include_path(implode(PATH_SEPARATOR, array(
    'path/to/zend/lib/',
    get_include_path(),
)));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my applet have warning signs? For some reason beyond my knowledge, my applet is displaying these little warning signs every time I interact with one of its controls.
This does not happen when I use Applet Viewer, so I assume that this is happening since it's not signed.
What is the reason and purpose for this annoying behavior, if this problem is exclusive to unsigned applets?
Also, is it possible to remove these signs?

A: It's a Java "feature" for letting users know that it is a Java Applet window.
http://www.oracle.com/technetwork/articles/javase/appletwarning-135102.html#6u12
The link also shows how to change the positioning of the warning sign.
Even my signed applets show this warning sign.
I found that my signed applet warning sign disappears if you set the applet to use all-permissions (instead of sandbox).
But that's not exactly recommended.
To change the applet to use all-permissions, edit the jar's MANIFEST.MF to have the line
Permissions: all-permissions instead of sandbox.


text:
Q: Change automatically CSS via JS at a certain breakpoint I am building a responsive navigation therefore I have a button that changes the styling of the div #navigation via Javascript. (toggle between display: none; and display: block; .
On small screens it works perfectly. However, when I show and hide the navigation on the a small screen and resize the window after it the navigation is still hidden.
Is there a way to change the css automatically if the window has a certain size?
Here is the code I'm using (by the way: I'm new to Javascript)
Again: See what happens when you make the window smaller, open and close the navigation and resize the window again. The navigation is (not as wanted) still hidden:
http://codepen.io/HannesDev/pen/grjdqK

HTML:

Navigation

One

Two

Three

CSS:
html{
  background: lime;
}
/* The Button */
.btn-Nav{
  border: 2px solid grey;
  cursor: pointer;

}
/* The button changes to the greyed out closed area on the right */
.btn-Nav_open{
  position: fixed;
  margin-left: 80vw;
  left: 0;
  top: 0;
  width: 20vw;
  height: 100vh;
  background-color: black;
  color: white;
  opacity: .2;
  padding: .2em;
  text-align: center;
  font-size: 3em;
}

/* The Navigation on small screens */
#nav-hor{
  display: none;
  position: fixed;
  overflow-y: scroll;
  top: 0;
  width: 80vw;
  height: 100vh;
  background-color: white;
  z-index: 999;
  border-right: 1px solid grey
}

@media (min-width: 50em) {
  html{
    background: red;
  }
  /* Don't show the button on bigger screens */
  .btn-Nav{
    display: none;
  }

 /* The Navigation for bigger screens */
  #nav-hor {
    /* Clean up */
    display: flex;
    position: relative;
    overflow: visible;
    width: 100%;
    height: auto;

}

JS:
window.onload = function(){
  document.querySelector('.btn-Nav').onclick = function(){
    // closed
      if(this.className.match('btn-Nav btn-Nav_open')) {
          this.className = 'btn-Nav';
          document.getElementsByClassName("btn-Nav")[0].innerHTML = "Navigation";
          document.getElementById('nav-hor').style.display = "none";
          document.body.style.overflow = "auto";

      }
      // open
      else {
          this.className = 'btn-Nav btn-Nav_open';

          document.getElementsByClassName("btn-Nav")[0].innerHTML = "×";
          document.getElementById('nav-hor').style.display = "block";
          document.body.style.overflow = "hidden";
      }
  };
};

A:
Is there a way to change the css automatically if the window has a certain size?

Absolutely, however, you don't need Javascript to do it. CSS offers something called media queries, which allows you to change the styles of elements based on certain conditions. For your specific case, something along the lines of
@media only screen and (max-width: 500px) {
    #navigation {
        display: block;
    }
}

This will change the display of the #navigation element to block only when the browser window is smaller than 500px. The max-width value can most definitely be changed. There are some other awesome things you can do with media queries, and examples of them can be found at: http://www.w3schools.com/css/css_rwd_mediaqueries.asp.


text:
Q: get file path of a zipped folder cross-zip I am using cross-zip node module to zip a directory. This works great when I run this locally , I see the folder. The code looks like this
var zip = require('cross-zip');
zip.zip('./directory', 'zip-folder-name', function(){})
But when I run this on bitbucket pipeline I don't see the zipped folder. I am assuming this has to do with the path but cant seem to figure out what am I missing here

A: cross-zip has dependency with Dot net framework and the image that is used in Bitbucket pipeline may not support that. Either we need to explicitly add the framework or switch to "archiver" - https://www.npmjs.com/package/archiver
Archiver works well with node image on Bitbucket pipeline


text:
Q: How to retrieve JSONObject from JSONArray request using Flickr API? I want to retrieve comments from a Flickr photo in my Android app, and have created a JSONObjectRequest using the following code:
public void loadComments(ImageInfo photo) {

        //clear the comments arraylist ready for new request
    NetworkMgr.getInstance(this).commentsList.clear();
    NetworkMgr netMgr = NetworkMgr.getInstance(getApplicationContext());
    RequestQueue requestQueue = netMgr.requestQueue;

    String id = photo.id;

    String url = "https://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=MY_API_KEY&format=json&nojsoncallback=1&extras=authorname,_content&photo_id=" + id;

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, responseListener, errorListener);

    requestQueue.add(request);

    adapter.notifyDataSetChanged();
}

The photo ID is correctly being retrieved and appended to the String url, and below I use a response listener to get authorname and _content, from each comment object:
private Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            JSONObject comments = response.getJSONObject("comments");
            JSONArray commentList = comments.getJSONArray("comment");

            for (int i = 0; i < commentList.length(); i++) {
                ImageInfo newComment = new ImageInfo();

                JSONObject comment = commentList.getJSONObject(i);

                newComment.authorname = comment.getString("authorname");
                newComment.commentContent = comment.getString("_content");

                //add data to arraylist
                NetworkMgr.getInstance(DetailsActivity.this).commentsList.add(newComment);
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        adapter.notifyDataSetChanged();
    }
};

private Response.ErrorListener errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    }
};

However when I put this url in my browser to view the JSON data, the comment JSONObject is non-existent.
How The JSON Response Should Look <<<< How My JSON Response Looks <<<<
Does anybody know why I cannot retrieve the JSON comment object and its data?

A: Try this

*

*Put this in your loop
   JSONObject allvaluesJsonObject=new JSONObject();
   allvaluesJsonObject=jsonArray.getJSONObject(i);

*remove this ImageInfo newComment = new ImageInfo();


text:
Q: Tensorflow - Retrieving weights/biases of the trained feedforward neural network after training I'm currently trying to create a simple web application for interactive neural network training with Flask. What I'm struggling with is retrieving the weights of the hidden layers after a feedforward neural network has been trained - my goal is to make a real back-end for the Tensorflow's Playground.
Take into consideration the following weights initialisation:
# Weight initializations
tW1 = init_weights(shape=(n_features, hidden_nodes))
tW2 = init_weights(shape=(hidden_nodes, output_nodes))

How does one go about retrieving the calculated weights of tW1 and tW2 after the training has been completed in Tensorflow?
Here's a sample of the code:
def retrieve_data():
    """Retrieves the data - to be expanded for custom database access + S3 retrieval + URL"""

    result = pd.read_csv('snp_data.csv', parse_dates=['Date'], index_col=['Date'])
    return result

def get_columns(data, columns):
    features = data.ix[:, columns]
    return features

def preprocess(data):
    """Data preprocessing"""
    result = (data - data.mean()) / data.std(ddof=0)
    result = result.fillna(0)
    return result

def init_weights(shape):
    """ Weights initialization """
    weights = tf.random_normal(shape=shape, stddev=0.1)
    return tf.Variable(weights)

def forwardprop(X, w_1, w_2):
    """Forward propagation"""
    h = tf.nn.relu(tf.matmul(X, w_1))
    y_hat = tf.matmul(h, w_2)
    return y_hat

# @app.route('/train')
def train():
    data = retrieve_data()

    train_x = get_columns(data, columns=['Open', 'Close'])
    train_x = preprocess(data=train_x).as_matrix().astype(np.float32)
    train_x = train_x[:(len(train_x) - (len(train_x) % 32))]

    train_y = get_columns(data, columns=['Adj Close']).as_matrix().astype(np.float32)
    train_y = train_y[:(len(train_y) - (len(train_y) % 32))]

    # Number of input nodes
    n_features = train_x.shape[1]

    # Number of output nodes
    output_nodes = train_y.shape[1]

    # Number of hidden nodes
    hidden_nodes = 20

    # TF Placeholders for the inputs and outputs
    tx = tf.placeholder(tf.float32, shape=(None, n_features))
    ty = tf.placeholder(tf.float32, shape=(None, output_nodes))

    # Weight initializations
    tW1 = init_weights(shape=(n_features, hidden_nodes))
    tW2 = init_weights(shape=(hidden_nodes, output_nodes))

    # Forward propagation
    y_hat = forwardprop(tx, tW1, tW2)

    # Backward Propagation
    tMSE = tf.reduce_mean(tf.square(y_hat - ty))
    learning_rate = 0.001
    tOptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    tOptimize = tOptimizer.minimize(tMSE)

    batch_size = 32
    n_epochs = 8

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        for i_e in range(n_epochs):
            for i in range(0, train_x.shape[0], batch_size):
                batch_X = train_x[i:i + batch_size, ...]
                batch_y = train_y[i:i + batch_size]

                _, loss = sess.run([tOptimize, tMSE], feed_dict={tx: batch_X, ty: batch_y})
                print(i, loss)
    return 'Flask Dockerized'

A: This should be as simple as final_tW1, final_tW2 = sess.run([tW1, tW2]) after the for loop has completed.  You don't need to feed anything because the variables maintain their own values that don't depend on placeholders.


text:
Q: Redirect page/subfolder to new domain url without changing url in browser have been looking for an answer this without any luck (searched everywhere)
Basically, I want to rewrite a page (subfolder) to a new domain without changing the url. The link should stay the same but show the other website
The following below works but it breaks the images as it replaces everything with the old url:
 RewriteEngine On
 RewriteBase /
 RewriteRule ^test/(.*)$ http://newdomain/$1 [P,L]


text:
Q: python: py2exe cryptography Multibackend cannot be initialized with no backends I am using python 2.7.11 on windows 7 64bit with py2exe 0.6.9, I got the following error after running the .exe file.

ValueError: Multibackend cannot be initialized with no backends.
If you are seeing this error when trying to use default_backend() please try uninstalling and reinstalling cryptography.

A: i wrote bellow code then the problem has been solved.
def patch_crypto_be_discovery():

"""
Monkey patches cryptography's backend detection.
Objective: support pyinstaller freezing.
"""

from cryptography.hazmat import backends

try:
    from cryptography.hazmat.backends.commoncrypto.backend import backend as be_cc
except ImportError:
    be_cc = None

try:
    from cryptography.hazmat.backends.openssl.backend import backend as be_ossl
except ImportError:
    be_ossl = None

backends._available_backends_list = [
    be for be in (be_cc, be_ossl) if be is not None
]

patch_crypto_be_discovery()


text:
Q: Advanced gradients? Is it possibly to have a gradient where there's a colour in each corner of a UIView?

A: There's no built-in way to do this, and no simple way to do this via Quartz either. However, you can do it via Quartz by creating 4 different 2-D gradients going in different directions, and masking each one with a black-white gradient running perpendicular.
Assuming your colors are defined as: tlColor, trColor, blColor, brColor (for top-left, top-right, etc.).

*

*Vertical gradient from tlColor (top) to blColor (bottom).

*Horizontal gradient from white (left) to black (right), convert to image, use as image mask with image from #1.

*Vertical gradient from trColor (top) to brColor (bottom).

*Horizontal gradient from black (left) to white (right), convert to image, use as image mask with image from #3.

*Horizontal gradient from blColor (left) to trColor (right).

*Vertical gradient from white (top) to black (bottom), convert to image, use as image mask with image from #5.

*Horizontal gradient from tlColor (left) to brColor (right).

*Vertical gradient from black (top) to white (bottom), convert to image, use as image mask with image from #7.

*Then just draw each of the 4 results to the view.

You might want to try this in Acorn or Photoshop first... so it's clear what's involved before you translate it into code. Then the Quartz reference @lxt pointed you to has sections on gradients (CGGradientRef is sufficient, don't try to use shadings), and a separate section on image masks.

A: I have 2 gradients placed diagonal. With overlay-blending
- (void)drawRect:(CGRect)rect
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat locations2[2] = { 1.0, 0.0 };
    CGFloat components[8] = {
        1.0, 1.0, 0.0, 1.0 ,//Yellow
        0.0, 0.0, 1.0, 1.0};//Blue

    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGPoint point1 = CGPointMake(0, 0);
    CGPoint point2 = CGPointMake(self.bounds.size.width, self.bounds.size.height);
    CGContextDrawLinearGradient(currentContext, gradient, point1, point2, 0);

    CGFloat components1[8]  = {
        0.0, 1.0, 0.0, 1.0,//Red
        1.0, 0.0, 0.0, 1.0}; //Green

    gradient = CGGradientCreateWithColorComponents(rgbColorspace, components1, locations2, num_locations);

    CGContextSetBlendMode(currentContext, kCGBlendModeOverlay);

    point1 = CGPointMake(self.bounds.size.width, 0);
    point2 = CGPointMake(0, self.bounds.size.height);

    CGContextDrawLinearGradient(currentContext, gradient, point1, point2, 0);

    CGGradientRelease(gradient);
    CGColorSpaceRelease(rgbColorspace);
}

To change the color you should have 4 UIColors as members on the view and change this fragment accordingly.

A: Here is a working solution.
One vertical gradient bitmap mask used both as is and mirrored when drawing two color gradients.
FourTimesRGBAcomponents is the R,G,B,A components of the four corner colors UL, UR, LL and LR, i.e. ULR, ULG, ULB, ULA, URR etc.
void DrawFourGradientRect(CGContextRef Cgc,
                          const CGRect * Rect,
                          const CGFloat FourTimesRGBAcomponents[16])
{
   int            w;
   int            h;
   void          *MaskData;
   CGColorSpaceRef GrayCS;
   CGColorSpaceRef CS;
   CGContextRef   BC;           //Bitmap context
   CGFloat        GrayComp[4] = {1.0, 1.0, 0.0, 1.0}; //2 * Gray+Alpha
   CGGradientRef  Gradient;
   CGImageRef     Mask;

   w = Rect->size.width;
   h = Rect->size.height;

   //Start filling with white
   CGContextSetRGBFillColor(Cgc, 1, 1, 1, 1);
   CGContextFillRect(Cgc, *Rect);

   //Then create vertical gradient mask bitmap, white on top, black at bottom
   MaskData = malloc(w * h);
   if (!MaskData)
      return;
   GrayCS = CGColorSpaceCreateDeviceGray();
   if (!GrayCS)
   {
      free(MaskData);
      return;
   }
   BC = CGBitmapContextCreate(MaskData, w, h, 8, w, GrayCS, kCGImageAlphaNone);
   if (!BC)
   {
      CGColorSpaceRelease(GrayCS);
      free(MaskData);
      return;
   }
   Gradient = CGGradientCreateWithColorComponents(GrayCS, GrayComp, NULL, 2);
   if (!Gradient)
   {
      CGContextRelease(BC);
      CGColorSpaceRelease(GrayCS);
      free(MaskData);
      return;
   }
   CGColorSpaceRelease(GrayCS);
   CGContextDrawLinearGradient(BC, Gradient, CGPointZero, CGPointMake(0, h), 0);
   CGGradientRelease(Gradient);
   Mask = CGBitmapContextCreateImage(BC);
   CGContextRelease(BC);
   free(MaskData);
   if (!Mask)
      return;

   //Now draw first horizontal color gradient from UL to UR
   CS = CGColorSpaceCreateDeviceRGB();
   if (!CS)
   {
      CGImageRelease(Mask);
      return;
   }

   CGContextSaveGState(Cgc);
   CGContextTranslateCTM(Cgc, Rect->origin.x, Rect->origin.y);
   CGContextClipToMask(Cgc, CGRectMake(0, 0, w, h), Mask);

   Gradient = CGGradientCreateWithColorComponents(CS,
                                        FourTimesRGBAcomponents, NULL, 2);
   if (Gradient)
   {
      CGContextDrawLinearGradient(Cgc, Gradient, CGPointZero, CGPointMake(w, 0), 0);
      CGGradientRelease(Gradient);
   }

   CGContextRestoreGState(Cgc);

   //Finally draw second horizontal color gradient from LL to LR
   CGContextSaveGState(Cgc);
   CGContextTranslateCTM(Cgc, Rect->origin.x, Rect->origin.y + Rect->size.height);
   CGContextScaleCTM(Cgc, 1, -1);   //Use vertical gradient mask upside-down
   CGContextClipToMask(Cgc, CGRectMake(0, 0, w, h), Mask);

   Gradient = CGGradientCreateWithColorComponents(CS,
                                    FourTimesRGBAcomponents + 8, NULL, 2);
   if (Gradient)
   {
      CGContextDrawLinearGradient(Cgc, Gradient, CGPointZero, CGPointMake(w, 0), 0);
      CGGradientRelease(Gradient);
   }

   CGContextRestoreGState(Cgc);

   CGImageRelease(Mask);
   CGColorSpaceRelease(CS);
}                               /* DrawFourGradientRect                      */

A: To be a little more helpful than Carl, the answer is 'yes', but how you implement it would depend on the tech you wanted to use. The Quartz gradient system is described here:
http://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_shadings/dq_shadings.html
...but OpenGL is another possibility. It would depend on your application.


text:
Q: Coldfusion WCF api implementation Below is the example of calling API that I got from Provider, I am facing problem converting this code to coldfusion. Any help will be appriciated
    var parameters = new List<RegaloPayBillerFieldWithValue>
   {
    new RegaloPayBillerFieldWithValue
    {
      Name = "NPE",
      Value = "1234567890"
    }
  };
  var preReceipt = client.RegaloPayPreReceipt(accessId: "2FC60D63-9091-4530-BC08-AF0D5742BBF2", billerPublicId: 3, localAmount: 0, billParameters: parameters);

The part where I am facing the problem is the upper part i.e.
   var parameters = new List<RegaloPayBillerFieldWithValue>
   {
    new RegaloPayBillerFieldWithValue
    {
      Name = "NPE",
      Value = "1234567890"
    }
  };

Two variables here i.e. Name and value are not being posted correctly.Test url is http://regalocashservice.cloudapp.net:8085/RegaloCashService.svc?wsdl

A:
 var parameters = new List<RegaloPayBillerFieldWithValue>
   {
    new RegaloPayBillerFieldWithValue
    {
      Name = "NPE",
      Value = "1234567890"
    }
  };

From the example, and WSDL, it looks like they are just creating an array of structures, which is then passed via a wrapper object ie another structure.  I think it should work if you create the array, then wrap it like so:
<cfscript>
  // create ArrayOfRegaloPayBillerFieldWithValue wrapper object
  parameters = [ {Name="NPE", Value="1234567890"} ];
  billParameters  = { RegaloPayBillerFieldWithValue=parameters };

  // create web service
  ws = createObject("webservice", "http://regalocashservice.cloudapp.net:8085/RegaloCashService.svc?wsdl");
  // debug
  writeDump(ws);

  // get result code
  result = ws.RegaloPayPreReceipt( "2FC60D63-9091-4530-BC08-AF0D5742AAF2"
                                    , 3 , 0, billParameters  );
  writeDump(result.getResponseCode());
</cfscript>

A: You could write-
    <cfset wsdlurl = "http://regalocashservice.cloudapp.net:8085/RegaloCashService.svc?wsdl">
    <cfset parameters = StructNew()>
    <cfset RegaloPayBillerField = ArrayNew(1)>
    <cfset vars = structNew()>

    <cfset ArrayAppend(RegaloPayBillerField, {Name="NPE", Value="1234567890"})>
    <cfset StructAppend(parameters, {RegaloPayBillerFieldWithValue = RegaloPayBillerField })>
   <cfset vars["billerPublicId"] = 2>
   <cfset vars["localAmount"] = 0>
   <cfset vars["accessId"] = "2FC60D63-9091-4530-BC08-AF0D5742AAF2">

   <cfinvoke webservice="#wsdlurl#" method="RegaloPayPreReceipt" returnVariable="res" argumentcollection="#vars#" >
<cfinvokeargument name="billParameters" value="#parameters#"/>
   </cfinvoke>
   <cfdump var="#res.getResponseCode()#">

A: Note: the code below was tested in CF 11 Dev Edition environment
<cftry>
  <cfset parameters = StructNew()>
  <cfset StructAppend(parameters, {Name="NPE", Value="1234567890"})>
  <cfinvoke webservice="test" method="RegaloPayPreReceipt" returnVariable="res">
    <cfinvokeargument name="accessId" value="REAL_ACCESSID_HERE"/>
    <cfinvokeargument name="billerPublicId" value="3"/>
    <cfinvokeargument name="localAmount"    value="0"/>
    <cfinvokeargument name="billParameters" value="#parameters#"/>
  </cfinvoke>
  <cfdump var="#res#">
  <cfcatch type="Any">
    <cfdump var="#cfcatch.message#">
  </cfcatch>
</cftry>

Web Service "test" is mapped to http://regalocashservice.cloudapp.net:8085/RegaloCashService.svc?wsdl in CF Admin Tool. Here is dump of the object returned org.datacontract.schemas._2004._07.domainclasses_dtos_results.RegaloPayPreReceiptResult


text:
Q: django-forms-builder. How do I update a form? I am using django-forms-builder in my project and there is just one thing i cant get my head around. How do i set up an update form to edit a filled out form?
Here is my attempt at making an update form for django-forms-builder
urls.py
url('forms/update/(?P<pk>\d+)/$', FormUpdateView.as_view(),
                                 name='form-update'),

views.py
class FormUpdateView(UpdateView):
    model = FieldEntry
    template_name = 'form/update_form.html'
    form_class = FormForForm
    success_url = '/assessments/all/'

update-form.py
{% render_built_form id=form_instance.id %}

A: I haven't used this software yet but it could fill a spot in my arsenal so I took a stab at it.  I'm not using CBV because I'm still just poking around.  This is the get part only, I can expand on how to handle the post part (and preferably do it with CBV) on the weekend.  It's relatively straightforward to implement post with view functions (if request.METHOD == "POST":#update the row).  The render is of course just plain raw HTML but forms_builder doesn't offer any styling input.  You probably want to tack the user onto the FormEntry, I don't have a good idea about authorization yet.  I'll give it some thought and amend the answer.
views.py
from forms_builder.forms.models import Form

def get_form(request, slug, pk):
    form_obj = Form.objects.get(slug=slug)
    form_instance = form_obj.entries.get(pk=pk)
    form = FormForForm(form=form_obj, instance=form_instance, context=request)
    return render_to_response('update_form.html', {'form':form_instance.form, 'request':request})

templates/update_form.html
{{ form.as_p }}


text:
Q: Finding Local Maximum Of Functions If $h=fg$ be the product of two differentiable functions $f$ and $g$ If $f$ and $g$ are positive with local maxima at $x=a$and if $f'$ and $g'$ change sign at $x=a$, does $h$ have a local maximum at $x=a$

A: It is true also if $f$ and $g$ are not differentiable. Infact if they are positive and $x=a$ is a local point of maximum for $f$ and $g$ then there exists two open set $A$ and $B$ of the point $a$ such that
$0\leq f(x)\leq f(a)$ for each $x\in A$
$0\leq g(x)\leq g(a)$ for each $x\in B$
then $A\cap B$ is an open neighborhood of $a$ and you have that
$fg(x)=f(x)g(x)\leq f(a)g(a)$ for each $x\in A\cap B$
so $a$ is a local maximum for $fg$


text:
Q: RewriteCond when REQUEST_URI do not match htaccess apache2 I have a multilingual wordpress website and want to redirect website of given region to given language,
xyz.de --> xyz.de/de/
xyz.co.uk --> xyz.co.uk/en/

direct access to xyz.de/de and xyz.co.uk/en are working properly. So there is no problem on wordpress side.
Now, I am trying to change the htaccess file of xyz.de and xyz.co.uk so that they redirect the website.
Considering xyz.co.uk
I want to add a RewriteCond such that whenever there is no /en trailing after xyz.co.uk it will automatically add /en.
For example xyz.co.uk/<trailing address> results in xyz.co.uk/en/<trailing address>
So far I have the following code, which somehow doesn't seem to work,
RewriteCond %{REQUEST_URI} !^/en
RewriteRule ^(.*)$ http://xyz.co.uk/en/$1 [L]

The negation of /en is not working! I have also tried
RewriteCond %{REQUEST_URI} !/en
RewriteRule ^(.*)$ http://xyz.co.uk/en/$1 [L]

Could someone tell me where I am going wrong? seems like I have gone wrong in writing RegEx and suggest if there is better way to achieve the same, that does not affect the SEO across different domains.

A: Use THE_REQUEST variable instead of REQUEST_URI:
RewriteCond %{HTTP_HOST} \.co\.uk$ [NC]
RewriteCond %{THE_REQUEST} !/en/ [NC]
RewriteRule ^ /en%{REQUEST_URI} [L,R=302,NE]

*

*Make sure to keep this rule as your very first rule in .htaccess.

*Change it to R=301 once you've tested.


text:
Q: Mutual Information for clustering I'm working on a document clustering application and decided to use Normalized Mutual Information as one of the measures of effectivenes. But I don't really understand how to implement this in that situation. In http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html the the formula is transformed to (185), and in this publication (www.shi-zhong.com/papers/comptext2.pdf, page 8, formula 17) it looks slightly different, n(h,l) is not divided by total number of documents N. So, which formula is correct? I would be very grateful for possibly simple explantation.

A: Each clustering algorithm $C=\{C_1,\dots,C_k\}$
defines the probability distribution $P_{\mathcal C}$
$$P_{\mathcal C}(i)=\frac{n_i}{N},$$
where $n_i$ is the number of points in the $i$-th cluster $C_i$ and $n$ is the total number of points in the data cloud. Different cluster algorithms can determine different numbers of clusters, of course.
For any distributions $P_{\mathcal C_1}=(p_1,\cdots,p_n)$ and $P_{\mathcal C_2}=(q_1,\cdots,q_m)$ the mutual information $I(p,q)$ is just
$$I(p,q)=\sum_{i,j}R(i,j)\log\frac{R(i,j)}{P_{\mathcal C_1}(i)P_{\mathcal C_2}(j)},$$
denoting by $R(i,j)$ the joint probability distribution. Using the definition for $P_{\mathcal C_i}$ and $R$, i.e.
$$P_{\mathcal C_1}(i)=\frac{n_i}{N} $$
$$P_{\mathcal C_2}(j)=\frac{m_j}{N} $$
$$R(i,j)=\frac{n_{i,j}}{N}:=\frac{|n_i\cap m_j|}{N}$$
we arrive at
$$I(P_{\mathcal C_1},P_{\mathcal C_2})=\sum_{i,j}\frac{n_{i,j}}{N}\log\frac{\frac{n_{i,j}}{N}}{\frac{n_i}{N}\frac{m_j}{N}}=\sum_{i,j}\frac{n_{i,j}}{N}
\log\frac{N n_{i,j}}{n_i m_j},$$
as in http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html, formula (185).
The same formula for the mutual information contained in http://machinelearning.wustl.edu/mlpapers/paper_files/StrehlG02.pdf and cited in http://www.shi-zhong.com/papers/comptext2.pdf does not contain the factor $\frac{1}{N}$, as you correctly remark.
I would use the above formulation for the mutual information, as it implements the correct probabilitstic view for the univariate and joint distributions.
Remark Note that in http://machinelearning.wustl.edu/mlpapers/paper_files/StrehlG02.pdf the assertion at pag. 589  "I(X,Y) is a metric" is wrong. The mutual information $I(X,Y)$ is equivalent to a Kullback Leibner divergence and it is no metric (or distance). The information value (or variation of information) is a metric, instead. Please look at http://en.wikipedia.org/wiki/Variation_of_information for more details.


text:
Q: Trying to compile code with references to both protobuffers 2.6.1 and 3.4.1 I am trying to compile a single codebase with references to both protobuffers 3.4.1 and 2.6.1. Now the 2.6.1 variant is globally defined as I am using ubuntu xenial, also:
$ protoc --version

yields:
libprotoc 2.6.1

The requirement for protobuffer version 3.4.1 comes from Google Cartographer (https://github.com/googlecartographer/cartographer) while the requirement for 2.6.1 comes from rotors simulator (https://github.com/ethz-asl/rotors_simulator) as it relies on Gazebo-7 (which uses protobuffer 2.6.1). In order to compile Google Cartographer I have added the binaries (added them in a proto3 folder, see below) to the installation by adapting the CMakeList.txt (see original file here: https://raw.githubusercontent.com/googlecartographer/cartographer/master/CMakeLists.txt) for Google Cartographer by adding the following lines:
set(CMAKE_PREFIX_PATH CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/proto3")
...
install(DIRECTORY proto3/ DESTINATION .)

So the binaries of the protobuffer 3.4.1 are added to the install folder. I am utilizing catkin-tools (https://catkin-tools.readthedocs.io/en/latest/) to build the whole workspace. Now in a CMakelist.txt for Rotors Simulator I have the following line:
find_package(Protobuf 2.6.1 REQUIRED HINTS "/usr")

But at the moment while trying to compile it does not seem to be able to find the protobuffer 2.4.1 as it returns the following:
Could not find a configuration file for package "Protobuf" that is
compatible with requested version "2.6.1".

The following configuration files were considered but not accepted:

/home/jochem/catkin_ws/install/lib/cmake/protobuf/protobuf-config.cmake,
version: 3.4.1

As a side-note, if I compile the packages separately I am able to compile and install the packages. This is done with the following commands:
 catkin build cartographer_ros

and
 catkin build rotors_gazebo_plugins

I am at the moment trying to adapt the package of rotors_gazebo_plugins but am so far unsuccessful at making sure the correct protobuffer library is selected, am I missing something by defining references to a local protobuffer version?

A: You will find it possible to build a single executable that references 2 versions of the same library on mac, quite difficult on windows, and pretty much impossible on unix. This is because the symbol names are not distinct between the two libraries, so if you load both libraries, there is no way to know which library should service which call.
If you are building 2 different executables in one makefile package, then you just need to set the right libraries to load in the link stage. In linux, libraries are usually installed on your system with a version-number suffix, and a symlink that publishes the latest version without the version number. Normally you simply link to the unsuffixed latest version, but in your case, in your link command you will need to explicitly add the suffix.
If you really do need to link this cobble-together into a single executable, on unix you can do a lot with objcopy --redefine-syms to rename all the entrypoints in one of the libraries, and all the references in the dependant code all after compilation, but before linking. Note that the intended end result is that both libraries will run independently and will not be aware of each other.

A: If you will be able to wrap up at least one of the libs (i.e. either Cartographer or Rotors or both) into a separate shared library, and if the protobuff is only used internally in each of them, you still might be able to use them both in a single executable by building the shared libs with -fvisibility=hidden gcc flag (to switch the default visibility to hide symbols) and only exporting the symbols that are needed (that the app is using) via __attribute__((visibility("default"))).
This way I recall I was able to use two completely different Boost versions in the past, in the same app (by the shared lib not exporting the boost symbols linked in statically).


text:
Q: Problem in audioElement.src , through which i ran and play another songs .But now showing error 404(not found) Array.from(document.getElementsByClassName('songItemPlay')).forEach(function (element) {

    element.addEventListener('click', (e) => {
        makeAllPlays();
        index = parseInt(e.target.id);

        e.target.classList.remove('fa-circle-play');
        e.target.classList.add('fa-circle-pause');
        audioElement.src = 'songs/${index+1}.mp3.mp3';

        audioElement.currentTime = 0;
        audioElement.play();

    });

})

A: if the error is 404 it means the audio resource was not found. from the code I see you should change the sign (') with the (`) *backtick to make the string accept variables.
audioElement.src = `songs/${index+1}.mp3`;


text:
Q: How to add locale data dynamically using React Intl? Am using React-intl for internationalization of an UI Util Library. The library has a folder say i18n wherein I place json files for different locales.If the user of this library want to add support for additional locales, he/she can place additional json file with key/value pairs for the respective locale.
But React-intl requires to import and addLocaleData for the respective locale in prior.For example,
import fr from 'react-intl/locale-data/fr';
addLocaleData([...fr]);

Is there a way to addLocaleData and import the locale library for the respective locale dynamically in React-intl?

A: If you are using webpack. You can code-split the different locale data from your app and load dynamically. Webpack 1 supports only require.ensure() and webpack 2 also supports System.import(). System.import returns a promise while require.ensure uses a callback. https://webpack.github.io/docs/code-splitting.html
With System.import()
import { addLocaleData } from 'react-intl';

const reactIntlLocaleData = {
  fr: () => System.import('react-intl/locale-data/fr'),
  en: () => System.import('react-intl/locale-data/en')
};

function loadLocaleData(locale){
  reactIntlLocaleData[locale]()
  .then((intlData) => {
    addLocaleData(intlData)
  }
}

With require.ensure()
import { addLocaleData } from 'react-intl';

const reactIntlLocaleData = {
  fr: () => require.ensure([], (require) => {
    const frData = require('react-intl/locale-data/fr');
    addLocaleData(frData);
  }),
  en: () => require.ensure([], (require) => {
    const enData = require('react-intl/locale-data/en');
    addLocaleData(enData);
  })
};

function loadLocaleData(locale){
  reactIntlLocaleData[locale]();
}

Depending on your development environment the code above may or may not work. It assumes you are using Webpack2 along with Babel to transpile your code.

A: Hey I have done this now, as described below and its working :-)
const possibleLocale = navigator.language.split('-')[0] || 'en';
addLocaleData(require(`react-intl/locale-data/${possibleLocale}`));

Here, the locale is fetched from the browser through navigator.language.
Hope this helps :-)


text:
Q: vector space generated by $\{I,A,A^2,\dots,A^{2n}\}$ $A$ be $n\times n$ matrix then the  dimension of vector space generated by $\{I,A,A^2,\dots,A^{2n}\}$ is atmost $n$ right? as $c_0I+c_1A+\dots+c_nA^n=0$ with some nonzero co efficient(cayley hamilton). so $\{I,\dots A^n\}$ will be linearly depenedent so others element $\{A^{n+1},\dots,A^{2n}\}$ may form atmost $n$ dimensional vector space. am I right?

A: Once you can express some power $A^k$ as linear combination of lower powers $A^i$ with $0\leq i<k$, there is no hope finding any higher powers either that are linearly independent of those lower powers. That's proved an easy induction: $A^{m+1}=AA^m$ and if $A^m$ is a linear combination of $A^0,\ldots,A^{k-1}$ then $A^{m+1}$ is a linear combination of $A^1,\ldots,A^k$, but by assumption we can express that final term $A^k$ as  a linear combination of $A^0,\ldots,A^{k-1}$, and this does the job. (This is the linear algebra version of the periodicity phenomenon, the fact that if some power of a group element $g$ gives the identity, then every further power of $g$ will be equal to a lower power of $g$ already seen.) Moreover, the first $k$ for which the above happens satisfies $k\leq n$ where $n$ is the dimension of the vector space acted upon; this follows from the Cayley-Hamilton theorem, but can also be shown by a fairly direct induction on the dimension without using that theorem. So the subspace of the vector space of all $n\times n$ matrices spanned by all the powers of $A$ (no need to stop at $A^{2n}$) has dimension $k\leq n$ and has $A^0=I,A^1,\ldots,A^{k-1}$ as basis.


text:
Q: Workmanager (registerPeriodicTask) with flutter but my application crushes everytime the it runs in background Am working on a flutter application that has to retrieve and update my sqlite database in backgound. And to achieve this, am trying to setup and use workmanager plugin provided by flutter. But everytime it runs in background, it displays 'unfortunately, myapp has stopped'.
here is my main.dart
void callbackDispatcher() {
  Workmanager.executeTask((task, inputData){
    try {
      var connectivityResult = await (Connectivity().checkConnectivity());
      final result = await InternetAddress.lookup('google.com');
      if (connectivityResult == ConnectivityResult.mobile) {
        // I am connected to a mobile network.
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          print('connected');
        }
      } else if (connectivityResult == ConnectivityResult.wifi) {
        // I am connected to a wifi network.
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          print('connected');
        }
      }
    } on SocketException catch (_) {
      print('not connected');
    }
    return Future.value(true);
  });
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager.initialize(
      callbackDispatcher, // The top level function, aka callbackDispatcher
      isInDebugMode:
          false // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
      );
  // Periodic task registration
  Workmanager.registerPeriodicTask("2", "syncfirebase",
      // When no frequency is provided the default 15 minutes is set.
      // Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
      frequency: Duration(minutes: 15),
      initialDelay: Duration(seconds: 10),
      constraints: Constraints(networkType: NetworkType.connected));

  runApp(new MyApp());
}

A: If I had to guess, you're missing a call to WidgetsFlutterBinding.ensureInitialized() in your callbackDispatcher. The callbackDispatcher is the entrypoint for the background isolate (effectively a Dart thread) that WorkManager is spawning, so you'll need to re-initialize the WidgetsFlutterBinding (this should really be done by the plugin, but it doesn't look like the author decided to do that).


text:
Q: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] I get this error when starting sonarqube.
I have tried:
sudo sysctl -w vm.max_map_count=262144

Which returns:
sysctl: setting key "vm.max_map_count"

And then:
sudo sysctl vm.max_map_count

It still says
vm.max_map_count = 65530

Does anyone know why Ubuntu 18.04 doesn't update vm.max_map_count?
Image with response from server commands
Thanks in advace,
Xander

A: The changes have not been applied on system. Run the sudo sysctl -p command to apply them and check the value again sudo sysctl vm.max_map_count.

A: running on docker or kubernetes, it is an optional to Elasticsearch bootstrap check be ignored in docker env
  containers:
    - name: sonarqube
      image: sonarqube
      args:
        - -Dsonar.web.context=/sonar
        - -Dsonar.es.bootstrap.checks.disable=true


text:
Q: Error when parsing retrofit2 response I'm lost as to where and what I need to change to get this to work.
I'm using this API call to yahoo finance.
This is my retrofit instance:
public class ApiClient {
    private static Retrofit retrofit = null;
    private static final String BASE_URL = "https://query.yahooapis.com";

    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Where i make my call:
String query = "select * from yahoo.finance.quotes where symbol in (\"YHOO\",\"AAPL\",\"GOOG\",\"2MSFT\")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

YahooApi yahooApi = ApiClient.getClient().create(YahooApi.class);
Call<GetStockResponse> call = yahooApi.getStock(query);

call.enqueue(new Callback<GetStockResponse>() {
    @Override
    public void onResponse(Call<GetStockResponse> call, Response<GetStockResponse> response) {
        List<Stock> list = response.body().getQuery().getResults().getList();
        if(list!=null)
            Toast.makeText(getContext(), list.size(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFailure(Call<GetStockResponse> call, Throwable t) {

    }
});

Interface (YahooApi):
@GET("v1/public/yql")
Call<GetStockResponse> getStock(@Query("q") String query);

Based on the JSON object I get back, I made the following wrapper classes:
public class GetStockResponse {
    @SerializedName("query")
    @Expose
    private Query mQuery;

    public Query getQuery(){
        return mQuery;
    }
}

public class Query {
    @SerializedName("count")
    @Expose
    private String mCount;
    @SerializedName("results")
    @Expose
    private Result mResults;

    public String getCount(){
        return mCount;
    }

    public Result getResults(){
        return mResults;
    }
}

public class Result {
    @SerializedName("quote")
    @Expose
    private List<Stock> mList;

    public List<Stock> getList(){
        return mList;
    }
}

public class Stock {
    @SerializedName("symbol")
    @Expose
    private String mSymbol;
    @SerializedName("Bid")
    @Expose
    private String mBid;
    @SerializedName("Change")
    @Expose
    private String mChange;
    @SerializedName("PercentChange")
    @Expose
    private String mPercentChange;
    @SerializedName("Name")
    @Expose
    private String mName;

    public String getSymbol(){
        return mSymbol;
    }

    public String getBid(){
        return mBid;
    }
    public String getChange(){
        return mChange;
    }

    public String getPercentChange(){
        return mPercentChange;
    }

    public String getName(){
        return mName;
    }
}

Any information on what i need to change will be greately appreciated!
Edit* added error message:
   java.lang.NullPointerException: Attempt to invoke virtual method 'strahinja.udacity.com.stockhawk.model.Query strahinja.udacity.com.stockhawk.model.GetStockResponse.getQuery()' on a null object reference
             at strahinja.udacity.com.stockhawk.fragment.MainFragment$1.onResponse(MainFragment.java:64)
             at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
             at android.os.Handler.handleCallback(Handler.java:739)
             at android.os.Handler.dispatchMessage(Handler.java:95)
             at android.os.Looper.loop(Looper.java:158)
             at android.app.ActivityThread.main(ActivityThread.java:7229)
             at java.lang.reflect.Method.invoke(Native Method)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

When I inspected the response, the url that was returned was changed to :
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22,%22AAPL%22,%22GOOG%22,%222MSFT%22)%26format%3Djson%26diagnostics%3Dtrue%26env%3Dstore%253A%252F%252Fdatatables.org%252Falltableswithkeys%26callback%3D

Thats all that I've been able to find out.

A: Change your query to following (key issue was that the original query string you had that also included other query params)
String query = "select * from yahoo.finance.quote where symbol in (\"YHOO\",\"AAPL\",\"GOOG\",\"MSFT\")";

Note that I also changed retrofit interface to following to test but you can make those other params dynamic if you need
    @GET("v1/public/yql?format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=")
    Call<GetStockResponse> getStock(@Query("q") String query);


text:
Q: "Memory Trace Upload was successful" message randomly appeared on iPhone While in the Facebook app, a grey box with light grey text appeared randomly at the top of the screen, saying "Memory Trace Upload was successful". I don't have a jail broken iPhone and did not do anything to 'ask' for a memory trace to be uploaded.

If it's a standard debugging thing, how do I turn off this level of access for app developers and/or Apple?

A: Apple and iOS do not have that as a standard dialog or feature - Apple crash reports and memory traces are logged and controlled much differently than how the Facebook App is designed.

*

*https://support.apple.com/en-us/HT202100

*https://developer.apple.com/videos/play/wwdc2018/414/

*https://developer.apple.com/library/archive/technotes/tn2151/_index.html
Apart from the link above on whether you have Apple share analytics you report back to the developer, you can inspect your iOS device in settings to see what the Facebook app is logging to Apple and possibly through them to Facebook when you opt in to Apple's analytics sharing process.

*

*https://support.omnigroup.com/ios-crash-log/

*

*Open Settings.app.

*Tap Privacy, then scroll down and tap Analytics.

*Tap Analytics Data.

*Locate the log for the app that crashed. The filename will use this format: <AppName>_<DateTime>_<DeviceName>

*Tap the crash log to open it.

Assuming you have discovered this message is in-app diagnostics and not iOS / Apple diagnostics and opting out from Apple collection, uninstall the Facebook app as a quick fix to remove the memory upload message that it is sharing with users when it it letting you know a trace has left your device.
You would of course need to use Safari to access your feed until the app developer either explains to you why they are letting you know a trace is uploaded or opt out of analytic / memory trace collection within the Facebook app.


text:
Q: Pandas Histogram buckets and frequency I have the below histogram which I want to plot using pandas

however it's giving me the below when using
dataset.hist(column='frequency')

How would I translate the above into histogram plot?
Per @somiandras answer the plot looks like below:

A: Your current plot is a histogram, showing the frequency of the values in your frequency column.
As you already have the values for the histogram pre-calculated, you don't need hist, just index the dataframe with (range_from, range_to) and plot on a bar plot:
dataset.set_index(['range_from', 'range_to'])['frequency'].plot.bar()


text:
Q: How does Google+ contact process glass shared timeline items? I am testing out the mirror api and so far I have a sample app running nicely.
The issue I am having is that I added a menu item for the action 'SHARE' but when I try to share the timeline card created by my app to Google+ it posts an empty Google+ post. The only text in the Google+ post is #throughglass. The contents of the timeline card is some simple html (see below) which renders find on glass. I also set the speakable text which works great with the 'READ_ALOUD' menu action. What gives on the 'SHARE' action, am I missing something?
Link to Google+ post
Timeline Item html:

    Hello Word.

A: Each application is free to choose what, from the shared timeline item, it will use as part of the share command. The Google+ Glassware appears to use the text field only when sharing a textual item and ignores the html field.
(This makes some sense. Google+ can't display the HTML formatting, so it chooses to go with the text that it knows should be good.)
When you're writing Glassware, you should make sure both the text and html (and speakableText, for that matter) fields contain the correct representation of your item.


text:
Q: How to add a licensing functionality in android? I want to add a application licensing coding to my project this is the coding that i used for checking, i have created a library project and i added that library project as a library to my project, and also added the required permissions in the project manifest but still i am getting force closing
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.widget.Toast;

import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.ServerManagedPolicy;

public class LicenseCheck extends Activity {

    private LicenseChecker mChecker;
    private LicenseCheckerCallback mLicenseCheckerCallback;
    private static final String BASE64_PUBLIC_KEY = "The key i got from the market";
 // Generate 20 random bytes, and put them here.
    private static final byte[] SALT = new byte[] {
     -20, 30, 50, -70, 33, -100, 32, -90, -88, 104, 12,
     -10, 72, -34, 115, 21, 62, 35, -12, 97
     };
    private AESObfuscator mObsfuscator;
    private String android_id;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.splash);
         android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
         mObsfuscator = new AESObfuscator(SALT, getPackageName(), android_id);
         ServerManagedPolicy serverPolicy = new ServerManagedPolicy(this,mObsfuscator);

         mLicenseCheckerCallback = new MyLicenseCheckerCallback();
         mChecker = new LicenseChecker(
             this, serverPolicy,
             BASE64_PUBLIC_KEY  // Your public licensing key.
             );
         mChecker.checkAccess(mLicenseCheckerCallback);
    }

private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
        public void allow(int reason) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
            // Should allow user access.
            Log.w("LicenseChecker", "Allow");
            Intent i = new Intent(LicenseCheck.this, App1_1Activity.class);
            startActivity(i);
            finish();
        }

        public void dontAllow(int reason) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
            Log.w("LicenseChecker", "Don't Allow");
            // Should not allow access. An app can handle as needed,
            // typically by informing the user that the app is not licensed
            // and then shutting down the app or limiting the user to a
            // restricted set of features.
            // In this example, we show a dialog that takes the user to Market.
            showDialog(0);

        }

//      @Override
        public void applicationError(int errorCode) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
//          toast("Error: " + errorCode.name());

        }
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        // We have only one dialog.
        return new AlertDialog.Builder(this)
                .setTitle("Application Not Licensed")
                .setCancelable(false)
                .setMessage(
                        "This application is not licensed. Please purchase it from Android Market")
                .setPositiveButton("Buy App",
                        new DialogInterface.OnClickListener() {
//                          @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent marketIntent = new Intent(
                                        Intent.ACTION_VIEW,
                                        Uri.parse("market://details?id=" + getPackageName()));
                                startActivity(marketIntent);
                                finish();
                            }
                        })
                .setNegativeButton("Exit",
                        new DialogInterface.OnClickListener() {
//                          @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                finish();
                            }
                        }).create();
    }

    public void toast(String string) {
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
    super.onDestroy();
    mChecker.onDestroy();
  }
}

And this is the logcat message
    08-06 15:01:33.301: E/AndroidRuntime(887): FATAL EXCEPTION: main
08-06 15:01:33.301: E/AndroidRuntime(887): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iexemplar.pray4me/com.iexemplar.pray4me.LicenseCheck}: java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.os.Looper.loop(Looper.java:123)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-06 15:01:33.301: E/AndroidRuntime(887):  at java.lang.reflect.Method.invokeNative(Native Method)
08-06 15:01:33.301: E/AndroidRuntime(887):  at java.lang.reflect.Method.invoke(Method.java:507)
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-06 15:01:33.301: E/AndroidRuntime(887):  at dalvik.system.NativeStart.main(Native Method)
08-06 15:01:33.301: E/AndroidRuntime(887): Caused by: java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.google.android.vending.licensing.LicenseChecker.generatePublicKey(LicenseChecker.java:121)
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.google.android.vending.licensing.LicenseChecker.<init>(LicenseChecker.java:92)
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.iexemplar.pray4me.LicenseCheck.onCreate(LicenseCheck.java:45)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-06 15:01:33.301: E/AndroidRuntime(887):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-06 15:01:33.301: E/AndroidRuntime(887):  ... 11 more
08-06 15:01:33.301: E/AndroidRuntime(887): Caused by: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
08-06 15:01:33.301: E/AndroidRuntime(887):  at org.bouncycastle.jce.provider.JDKKeyFactory.engineGeneratePublic(JDKKeyFactory.java:92)
08-06 15:01:33.301: E/AndroidRuntime(887):  at org.bouncycastle.jce.provider.JDKKeyFactory$RSA.engineGeneratePublic(JDKKeyFactory.java:396)
08-06 15:01:33.301: E/AndroidRuntime(887):  at java.security.KeyFactory.generatePublic(KeyFactory.java:177)
08-06 15:01:33.301: E/AndroidRuntime(887):  at com.google.android.vending.licensing.LicenseChecker.generatePublicKey(LicenseChecker.java:112)
08-06 15:01:33.301: E/AndroidRuntime(887):  ... 15 more
08-06 15:01:39.001: I/Process(887): Sending signal. PID: 887 SIG: 9

Someone help me to solve this issue

A: You have written a class for MyLicenseCheckerCallback but have not instantiated an instance of it.
Instead, you have an instance of LicenseCheckerCallback.
So you are using the LVLs implementation and not your own.


text:
Q: Can someone tell me why this script return NULL instead of give me result? $mysqli = mysqli_connect("localhost", "root", "pass", "test");

function check_login($mail,$pwd){
    global  $mysqli;
    if($stmt=  $mysqli->prepare('SELECT COUNT(*) FROM `users` WHERE mail = ? AND pwd = MD5(?)')){
        $stmt->bind_param("ss", $mail, $pwd);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->close();
        var_dump($count);
    }
    return ($count > 0 ? true : false);
}

check_login('test@gmail.com','pass');

I have write this script by seeing some script on stackoverflow.I tried to run it and found that $count is NULL after script execute.
I want to know why this is not worked for me. I have tried to run same command on Mysql and it's show me result.
someone help me on it..

A: mysqli::bind_result needs to be invoked after the ->execute and before the ->fetch call. The fetch() isn't optional, as the (bound result) variable reference is merely an alternative to extracting the result row manually.
So in your code:
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();  // result array thrown away

A: First, you shouldn't just copy and paste codes, especially ones that require messing with the database; understand what the code is trying to achieve, then, write yours.
Second, replace

  'SELECT COUNT(*) FROM `users` WHERE mail = ? AND pwd = MD5(?)'

with

 'SELECT COUNT(*) FROM `users` WHERE mail =? AND pwd =?'

There's a chance the code didn't run because your passwords were stored in a plaintext on the database.
Let us know if that works.


text:
Q: Converting Modbus Serial Application to Modbus TCP/IP c# I am currently working on an application which communicated with devices using Modbus serial. The application is written in C#.
Our devices have been modified to use Ethernet and I have now been tasked with converting this application to use Modbus TCP/IP.
I initially thought it would be very simple, and would only require changing the Serial connection to a TCP Client connection and Listener.
I have read some documentation on Modbus TCP/IP
https://www.prosoft-technology.com/kb/assets/intro_modbustcp.pdf
https://www.honeywellprocess.com/library/support/Public/Documents/51-52-25-121.pdf
Although I feel like I still may be missing some essential differences.
From what I understand, this is what needs to be done.

*

*Introduce new MBAP header in place of the Additional Address section at the start of a packet.

*Remove checksum from the Modbus packet as this is handled by TCP/IP.

*Open connection with each device using the Socket class. To open these connections I will now need to store each Device IP in my Client/Master configuration. They will be listening on the default Port 502 and the connection must be opened from a random available port > 1024. The connection should also remain open, therefore I will maintain an Array of TcpClient objects. Or should I simply close the connection after I receive a response?  Will I need to have a thread for each Server/Slave?

A: You are in the right direction. But please do not close the TCP connections after receiving the response. I have developed Modbus TCP slaves before, on very resource limited platforms, and it was not fun to handle TCP connection creation/destruction every 1-2 seconds. Keep the connection open, it will be easier both for you and the slaves.
You don't need a thread for each slave. You can use some form of "select" available in C#.


text:
Q: Adding a gif to a larger background I'm using imagemagick to resize uploaded files but while they're processing I want to show a rotating gif wheel to the user where the thumbnail would normally be. I serve about 7 sizes of thumbs and would like the wheel to remain at it's 32x32 size in the middle, that's the simple bit.
What I need to know is, can I do the above while still retaining the animation
Example:
This Image:

Starting at this size

With Animation

A: Check out this fiddle, it might contain what you want: http://jsfiddle.net/TGdFB/1/
It uses jQuery, but should be easily adaptable...

A: Ended up doing this manually by Photoshop after not being able to find an automated way of doing this through imagemagick. I found the 'coalesce' flag but not much else.

A: there is a solution in php witch i use to watermark gif animated images ....
it create an black bacground  put an image on it and then put watermark ...
watermarkpath = 'path to wathermarkimage.jpg|gif|png';
$imagepath= 'path to the image';
$watermark = new Imagick($watermarkpath);
 $GIF = new Imagick();
 $GIF->setFormat("gif");

$animation = new Imagick($imagepath);
foreach ($animation as $frame) {

    $iWidth = $frame->getImageWidth();
    $iHeight = $frame->getImageHeight();
    $wWidth = $watermark->getImageWidth();
    $wHeight = $watermark->getImageHeight();

    if ($iHeight < $wHeight || $iWidth < $wWidth) {
        // resize the watermark
        $watermark->scaleImage($iWidth, $iHeight);

        // get new size
        $wWidth = $watermark->getImageWidth();
        $wHeight = $watermark->getImageHeight();
    }

    $bgframe = new Imagick();
    $bgframe->newImage(($iWidth), ($iHeight + 80), new ImagickPixel('Black'));
    $bgframe->setImageDelay($frame->getImageDelay());

    $x = ($iWidth) - $wWidth - 5;
    $y = ($iHeight + 80) - $wHeight - 5;

    $bgframe->compositeImage($frame, imagick::COMPOSITE_DEFAULT, 0, 0);
     $bgframe->flattenImages();
    $bgframe->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
     $bgframe->flattenImages();
    $GIF->addImage($bgframe);
}

$GIF->writeimages($imagepath,true);


text:
Q: Cannot access file using relative path in local test when developing Google App Engine applications I am trying to write and deploy a simple web-app at Google Cloud Platform. I installed gcloud and the corresponding libraries/plugins on Eclipse in my Mac. I use the following code to try to open a file specified in a HttpServeletRequest:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

    resp.setContentType("text/html");
    resp.getWriter().println("
DEBUG: In Create2.
");

    // get the file info
    // to get the value of each input, always use the name and then
    // req.getParameter(name);
    String fileName = req.getParameter("file");

    // create the file
    File file = new File(fileName);
    resp.getWriter().println("
"+file.getAbsolutePath()+"
");

    if (file.exists()) {
        ...
    }
    else  {
        ...
    }

I put a test.txt file under project/src/main/webapp directory, run this project as an app engine and submit "test.txt" to servelet. But
In my local machine (localhost:8080), file.exists() always fails and the absolute path printed is
   Applications/Eclipse/Contents/MacOS/test.txt

On the contrary, after I deploy the project to Google App Engine, everything works just fine and the absolute path printed is
  /base/data/home/apps/XXXX/20170425t133741.400812218449586767/test.txt

I read a couple discussion threads all saying the file access in GAE/Google Cloud Platform is relative path. But why would my eclipse interpret it as an absolutely path when trying to open the file? Is there a fix on this issue so that I can always use relativ path both locally and on google cloud?
Thank you very much.

A: If you could set the working directory of the local App Engine dev server correctly, you wouldn't have problems using relative paths locally. Unfortunately, as of now, the Cloud Tools for Eclipse plugin doesn't support changing the working directory. Here is what you can do as a workaround:

*

*Run the local dev server and check the server log in the Console view to see the actual web application root the server should use as a working directory. You'll see a log message like this:
WARNING: Your working directory, (<...your current, out-of-sync local server working directory...>) is not equal to your
web application root (<...your workspace...>.metadata/.plugins/org.eclipse.wst.server.core/tmp0/<...your Eclipse project name...>)

*Open the Servers view. Stop the server.

*Double-click on the server. Click Open launch configuration on the Overview page that pops up.

*Select the Arguments tab.

*Enter -Duser.dir=<...the directory of the web application root from the server log...> in the VM arguments: box. Click OK. (The Working directory section below doesn't work unfortunately.)

From now on, you won't see the WARNING message, and the server will use the directory you provided as a working directory.
UPDATE: This has been fixed in recent CT4E versions, which automatically set the working directory properly (unless you run multiple projects in a single local server). Update to the latest CT4E if you encounter this issue.


text:
Q: Are these orders isomorphic? I wanted to ask if these orders are isomorphic - namely if my solutions are correct. Here $\leq$ means the standard order on integer or rational numbers and $\leq_\text{lex}$ means lexicographical defined with the help of standard order on axes.

*

*$(\mathbb{Q},\leq)$ and $(\mathbb{Z},\leq)$ – I think these orders aren't isomorphic, because the set of rational numbers is dense and of integers not,

*$(\mathbb{Z}\times \mathbb{Z},\leq_\text{lex})$ and $(\mathbb{Z},\leq)$ – I think these orders are isomorphic (I do not know how to argue it formally),

*$(\mathbb{Q},\leq)$ and $((0,\infty)\cap \mathbb{Q},\leq)$ – I think these orders aren't isomorphic, because the first set hasn't got the least element in the opposite to the second.

I would really appreciate checking the correctness of these solutions.

A: The first one is correct.
In the second one the orders are not isomorphic. Note that in the lexicographic order on $\mathbb{Z}\times\mathbb{Z}$ there are infinitely many elements between $(1,1)$ and $(2,1)$. Indeed, for each $n\geq 2$ we have $(1,1)<(1,n)<(2,1)$. On the other hand, in $\mathbb{Z}$ there are only finitely many elements between each two elements. Use this to show that there can't be an isomorphism here.
The third one: the orders are isomorphic by Cantor's theorem, which says that any two orders on countable sets which are linear, dense and have no first and last elements are isomorphic to each other.


text:
Q: UL/LI positioning spacing I have been in this problem for a while now, everytime I resize the navigation bar it keeps on adding 1 line at the bottome if the size ddint match. can anyone help me delete that little space after the contact me tab? thanks in advance.
this is the link of the outcome

my codes is this
obj.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet" type="text/css" href="obj1.css">
<title>Objective 1</title>

About Us

Our Team

Education

Health Care

Advertising

Contact Us

obj1.css
body {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
}

ul {
    display: inline-block;
    list-style-type:none;
    margin:0;
    padding:0;
}

li {
    float: left;
}

.header{
width: 900px;
height: 385px;
background-image: url(header.jpg);
}
.navbutton {
position: relative;
top: 310px;
width: 145px;
height: 75px;
margin-left: 0px;
margin-right: 5px;
background-image: url(link.png);
}

.navbutton a {
text-decoration:none;
}

.navbutton:hover{
background-image: url(linkselected.png);
}

A: You can fix this by adding the following rules:
//Change the header width to 901px to fit all the tabs
.header{
width: 901px;
height: 385px;
background-color: #ccc;
}

//Change the navbutton to be 146px wide
.navbutton {
position: relative;
top: 310px;
width: 146px;
height: 75px;
margin-left: 0px;
margin-right: 5px;
background-color: white;
}

//Remove the margin on the last child
.navbutton:last-child {
    margin-right:0;
}

Here is the jsFiddle in case you need it - http://jsfiddle.net/XXczL/

A: Check this jsfiddle for a fluid layout solution.
This solution uses the display: table, display: table-row, and display: table-cell property values.
Markup

              About Us

              Our Team

              Education

              Health Care

              Advertising

              Contact Us

CSS
     body{
        font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
     }

     .nav ul{
        display: table-row;
        list-style-type: none;
        margin: 0;
        padding: 0;
     }

     .header{
        width: 900px;
        height: 385px;
        background: #f00 url(header.jpg);
        overflow: hidden;
        border: 1px solid #000
     }

     .nav{
        display: table;
        width: 100%;
        margin-top: 310px;
     }

     .navbutton{
        display: table-cell;
        height: 75px;
        background-image: url(link.png);
        padding: 0 4px;
     }

     .navbutton a{
        background: none repeat scroll 0 0 #FFFFCC;
        color: #FF0000;
        display: block;
        height: 100%;
        line-height: 75px;
        text-decoration: none;
        text-align: center;
     }

     .navbutton:hover{
        background-image: url(linkselected.png);
     }

     li:last-child, li.the_last_child{ padding-right: 0; }
     li:first-child, li.the_first_child{ padding-left: 0; }

A: place all the
 tags in a

set css for that

#customDiv {
    margin-left:auto;
    margin-right:auto;
}
this will make the left and right margin equal and the extra space is distributed equally on both sides..

A: You have 2 problems going on here.  First, you have margins being applied where you don't actually want them.  Even when you correct this, your header's width still causes the appearance of the undesirable "space"
http://tinker.io/0191d/2
Include the following modifications:
.header {
    width: 895px; /* or modify the width of the button elements */
}

ul {
    margin: 0 0 0 -5px;
}

.navbutton {
    margin-left: 5px;
    margin-right: 0;
}

You could use the :last-child selector to remove the margin on the last element, but it doesn't work very well in instances where you actually want your elements to wrap (see: http://codepen.io/cimmanon/pen/dwbHi).  Also, IE8 doesn't support it.


text:
Q: ASP MVC load new view on selected item I'm sure there's a simple way to do this, but I cannot find a clear answer anywhere.
I have a page, "Index", in my application. Index contains some graphs and various other data. At the top of the page, I have a HTML drop down menu. When the user selects a value from the drop down menu, it affects the data. The desired behaviour is that the page refreshes with updated graphs.
I'm able to get the value of the drop down menu using
 <select id="Menu" onchange="loadGraphs()">

and then access the value in a script using:
var value = $('#Menu').val();

But then I am not able to make a call to my controller to refresh the page. I have a method in the controller that accepts the value, processes the data, and returns the view. How do I call this with the value and have it reload the page?

A: you don't need to reload the page, if all you want is to refresh the data then use a little angular app for example which is able to update the page without refreshing anything.
What you need to do is issue an http request to your controller either GET or POST depending on how you wrote the controller, make it return a JsonResult and then use the result to populate the new data.
The controllers can return data only, not just Views. When it's a view it's an ActionResult, but JsonResult is just that, some json stuff.
A nicer approach would be to add a WebApi2 project and that's where you would put all your data related controllers. It depends on how big your project is though. It could be overkill if all you have is one or two things you need to call. The advantage however is that you could call the same api from multiple clients not just web, like a mobile one for example.


text:
Q: How to bind Datepicker with angular ng-model I have a form with a few fields in HTML. Below is the related lines for the date fields where I use a datepicker.
<input tabindex="3" class="date-picker" name = "startDate" type="text" id="startDate" ng-model = "startDate" ng-required="true">
<input tabindex="4" class="date-picker" name = "endDate" type="text" id="endDate" ng-model = "endDate" ng-required="true">

Here is the javascript for the datepicker.


text:
Q: Ubuntu 14 no way to install Nvidia drivers or get suspend working I'm trying to get an "old" Acer Aspire 5720 operative with Ubuntu 14.04 but the proprietary drivers nor suspend work properly.
My hardware configuration:

*

*Intel Core Duo T5250 @ 1,5Ghz

*4GB DDR2 RAM

*Nvidia GeForce 8400M GS 256MB

*Kingston ssdNow V300 120GB

I've tried legacy drivers ver.173, removing bumblebee, removing nouveau, resetting xorg.conf file, but nothing changes.
My aim is to get suspend working, but with nouveau installed when resuming from suspension the only thing I get is a message saying "nouveau fault", with nvidia drivers instead I get a black screen.
Is it a kernel bug, a driver bug, or is it just my fault?

A: Finally solved! It turned out that the Nvidia GeForce 8400M GS (luckily installed as an MXM card instead of being soldered on motherboard) was defective as many other 8400M, I did the oven trick, now it works flawlessly with full hardware acceleration.

The oven trick consists of removing the defective MXM GPU module and leaving it into the oven at 200°C for 10 minutes (maybe with some SMD flux under the GPU BGA, but it worked fine for me even without flux).


text:
Q: Meaning of "with respect to rotor and stator" In the following example, when it says "with respect to stator" and "with respect to rotor", did they mean the rotor part of the synchronous generator in both cases?
Example: The excitation field in the synchronous generator is stationary with respect to the rotor. When the rotor rotates at synchronous speed, the excitation field rotates with respect to stator.

A: From what I understood from your question you want to know what is "with respect" to refers to in a synchronous motor.
This means relative velocity. If two object are moving at same speed it appears like one object is stationary with respect to other. The phrase "excitation field in the synchronous generator is stationary with respect to the rotor" means that both field and rotor have same speed.
For example let angular velocity of electric field is 40 rps. for synchronous motor, rotor is synchronous to electric field. Therefore speed of rotor is also 40 rps.
Here speed electric field with respect to stator is 40 rps. But speed of electric field with respect to rotor is 0 rps.

A: With respect to stator: does not rotate.
With respect to rotor: rotates with the rotor

excitation field in the synchronous generator is stationary with respect to the rotor.

This says that the electric field rotates around with the rotor.  In fact leading the rotor into it's advancing position.

When rotor rotates at synchronous speed the excitation field rotates with respect to stator.

It's likely referring to a brush-less DC motor (BLDC), that the excitation field from the magnets that are physically attached to the rotor.
The electric drive field also rotates synchronous to the rotor; it must lead the rotor magnets by a fixed angle ahead of them.  As long as the angle is fixed, the excitation in the stator is synchronous to the rotor.

If the stator is not driven correctly, the rotor and electric drive can slip out of synchronization; essentially the field is not properly positioned to pull the rotor around to it's target position and speed.

A: Lets clarify this with example of a induction motor(Referred as IM) for easy understanding.
Things to know before-
1.Synchronous speed (Ns) is 120*f/P.
2.Relative speed concept-Speed of object when seen from other reference.
3.IM has a stator(static) and rotor(rotating or static).
4.Stator magnetic field - Field generated by stator.
5.Rotor magnetic field -Field generated by induced currents in rotor.
In case of induction motor during normal operation.
Stator magnetic field  speed = Ns.
Rotor magnetic field   speed =Ns.
Speed of Rotor magnetic field w.r.t Stator M.F or vice versa =Ns-Ns=0.
Speed of stator = 0 (static).
speed of Rotor = N (actual speed).
speed of stator field w.r.t rotor= Ns-N.
In general speed of X w.r.t Y , we just compute by = Vx-Vy


text:
Q: Can't use canon mx435 scanner with Ubuntu 13.04 I installed the driver for the Canon printer, and it works OK with Ubuntu 13.04 but I can't use the scanner that comes with the printer. Any help?

A: I have installed Ubuntu 13.04 (i386). By now, I could use printer and scanner. Canon Europe helps with manual for Linux. Look for driver and manual for scangear in Canon Europe Web. After decompressing package, install common and specific archives(.deb). Manual guides you how to do it with Gimp or in a console.
Where I did not get success was in Fax tools.


text:
Q: Devolver imagen en un json Tengo la sgte clase, la imagen se guarda en la bbdd en la variable foto:
public class Personas{
  private String name;
  private Date date;
  private Blob foto;

MI pregunta es si creo un servicio rest y si esto me devolvera la foto para poder despues representarla en mi parte web


text:
Q: Open new window on grid view button click in aspx.cs page? I am working on aspx.cs page.When i will click on grid button column,then it should be take some data from present page to new page and open it in to new window without destroy present window.
   protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  {
    if (e.CommandName == "Trans")
    {

      Response.Redirect("APIwiserecharge.aspx?DisplayID=" +
       objdl.Encode(e.CommandArgument.ToString()));
    }

  }

A: To open a new window from codebehind you need to use javascript. You need to handle click event with javascript. You can try this code for your codebehind:
  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  {
    if (e.CommandName == "Trans")
    {

       string url = "APIwiserecharge.aspx?DisplayID=" +objdl.Encode(e.CommandArgument.ToString());

       string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";

        ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
    }

  }

A: Try this..
ScriptManager.RegisterStartupScript(this, this.GetType(), "onclick", "javascript:window.open( 'APIwiserecharge.aspx','_blank','height=600px,width=600px,scrollbars=1');", true);


text:
Q: Could not load module metadata from I am stuck for a day now trying to solve this issue I just updated my android studio but when I open the old project  it is showing error
Could not resolve all dependencies for configuration
':app:debugAndroidTestRuntimeClasspath'.
Could not load module metadata from C:\Users\NEELAY\.gradle\caches\modules-
2\metadata-2.36\descriptors\com.android.support\multidex-
instrumentation\1.0.2\5ac5911800d0dfe0ba2d29f224b8c2fb\descriptor.bin
Unexpected metadata type found.

I followed some question also which say to uninstall the android support repository and reinstall but it is not working tried gradle.setting is also proper . Now i have no idea how to solve this issue any help will be helpfull.
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fireapp.manoj.template">
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

</application>

this is the manifest code but dont know why it is showing as setting.gradle
any idea why is it because of the gradle update

A: Remove the caches.
Step 1 : Open the terminal
Step 2 : paste cd C:\Users\NEELAY.gradle\ (Navigate to .gradle folder)
Step 3 : rm -r caches\
Step 4 : Now clean or rebuild the project

A: Just clear metadata-2.36 folder in caches (no need to remove entire cache folder like suggested above) and do gradle clean build. I also faced the same issue and by following above step, my build became successful.

A: *

*Goto gradle path which is given in error. like: C:\Users\NEELAY\.gradle

*Delete the whole gradle folder (.gradle folder may be)

*Restart android studio and try to run now

If at 3. not worked:

*After all this (after deleting .gradle) uninstall android studio and reinstall it.

This worked for me.

A: This problem may arise when the android studio couldn't update all the dependencies.
Go to
file->project structure->dependencies
And make sure you update all the dependencies listed on the right side.
If it still pops out any issue delete the Gradle folder in the project and rebuild the project.


text:
Q: import error due to bs4 vs BeautifulSoup I am trying to use beautifulsoup compatible lxml and it is giving me an error:
from lxml.html.soupparser import fromstring
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/lxml/html/soupparser.py", line 7, in <module>
    from BeautifulSoup import \
ImportError: No module named BeautifulSoup

I have bs4 installed. How do I fix this issue?

A: The error is caused by soupparser.py trying to import BeautifulSoup version 3 while you have version 4 installed. The module name was changed from BeautifulSoup to bs4 in version 4.
You can trick soupparser.py into importing version 4 by mapping the bs4 module to BeautifulSoup in sys.modules before importing soupparser:
import sys, bs4
sys.modules['BeautifulSoup'] = bs4

from lxml.html.soupparser import fromstring

A: There is now a version of soupparser that works with bs4. It's available here: https://github.com/lxml/lxml/blob/master/src/lxml/html/soupparser.py

A: Try adding :
from bs4 import BeautifulSoup
and make sure you have the correct version of BeautifulSoup for your system installed.


text:
Q: Structure of post types for TV Shows and episodes Dear I would like to know how I can make a structure similar to this in wordpress, that the series seasons and episodes are interconnected, what function could I use?
example.com/serie/the-walking-dead/season-8/episodie-4/

A: You can create the custom post type as usual and then use the Permalinks Customizer plugin to customize the permalinks as per your need.


text:
Q: "Invalid Argument Exception Route [login] not defined " shown in laravel Trying to learn with Laravel today. I am getting the following error when I try to store sign up data via form to database.thanks...tomorrow is my exam.
InvalidArgumentException Route [login] not defined.
web.php
Route::post('/save_contact', 'HomeController@save_contact');

//////////////////////////////////////////////////////////
Homecontroller.php
public function save_contact(Request $request)
    {
       $data=array();
       $data['email']=$request -> email;
         $data['password']=$request -> password;
         DB::table('users')->insert($data);

}

}

A: You are probably referring to the login route somewhere in your app (maybe a view?) but the a route named "login" has not been defined.
Check your routes/web.php and see if you have a login route with the "login" name.
Route::get('/login', 'YourController@login')->name('login');


text:
Q: Sorting array by alphabet will not function correctly Code I am talking about: https://jsfiddle.net/sbe8yzv0/8/
I want to sort my array by the name with two buttons: First button sorts it by length and second buttons sorts it by alphabet.
When I sort by alphabet it doesn't want to function. It randomly puts the data in different positions. I have tried multiple ways of sorting it and they all act funky and doesn't sort it completely alphabetically. What can I do to make it actually sort the name in array by alphabet?
    function sortNameAlphabetically(a, b) {
        return a.name > b.name;
    }

The sort by length is working as intended except when it sorts alpabeticly after length it does it bakwards. How do I make sure it sorts the right way?
    function sortNameByLength(a, b) {
        return b.name.length - a.name.length;
        a.localeCompare(b);

A: change the sortNameAlphabetically method to
  function sortNameAlphabetically(a, b) {
        return a.name.localeCompare( b.name );
    }

updated fiddle
Also, statement after return statement in sortNameByLength method is not reachable and not required anyways.
    function sortNameByLength(a, b) {
        return b.name.length - a.name.length;
    }

A: Part two of the question, to maintain the alphabetical sorting after length sorting, you can use a logical OR with the localeCompare method.
function sortNameByLength(a, b) {
    return b.name.length - a.name.length || a.name.localeCompare(b.name);
}


text:
Q: Link error while trying to use glLoadGen While reading the OpenGL 4 Shading Language Cookbook, I encountered the OpenGL Loader Gen library and immediately wanted to try it out. I started creating a small example program that you can see underneath.
#include "GLFW/glfw3.h"
#include "GL/gl_core_4_1.hpp"

namespace engine
{
    class Window
    {
    private:
        const unsigned int width;

        const unsigned int height;

        const char *title;

        const void refresh()
        {
            glfwSwapBuffers(this -> glfwWindow);
            glfwPollEvents();
        }
    protected:
        GLFWwindow *glfwWindow;
    public:
        Window(const unsigned int width, const unsigned int height, const char title[]): width(width), height(height), title(title)
        {
            if (glfwInit() != GLFW_TRUE)
            {
                throw "Couldn't initialise the required GLFW library.";
            }
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
            if (this -> glfwWindow)
            {
                throw "Cannot create a secondary window.";
            }
            this -> glfwWindow = glfwCreateWindow(this -> width, this -> height, this -> title, NULL, NULL);
            // This is the crucial line that will stop the program from compiling.
            gl::exts::LoadTest context = gl::sys::LoadFunctions();
            if (!context)
            {
                throw "Couldn't initialse the required GL library.";
            }
            glfwMakeContextCurrent(this -> glfwWindow);
            glfwSwapInterval(GLFW_TRUE);
            if (!glfwWindow)
            {
                glfwTerminate();
                throw "Couldn't create a new initially empty window.";
            }
        }

        const bool await()
        {
            this -> refresh();
            if (glfwWindowShouldClose(this -> glfwWindow))
            {
                glfwDestroyWindow(this -> glfwWindow);
                glfwTerminate();
                return false;
            }
            return true;
        }
    };
}

int main(const int argc, const char *argv[])
{
    engine::Window window(1280, 720, "Foundation");
    while (window.await())
    {
    }
    return 0x00000000;
}

My next step was to try compiling the program with the LLVM compiler on computer running on the macOS High Sierra operating system.

clang++ -o Application.exec Subdirectory/*.cpp -lglfw -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo

However, during compilation I receive the following unexpected linker error:
Undefined symbols for architecture x86_64:
  "gl::sys::LoadFunctions()", referenced from:
      engine::Window::Window(unsigned int, unsigned int, char const*) in Application-58a670.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is my actual question: how do I let the program shown above compile using the previously mentioned OpenGL Loader Gen library?

A: from the docs

The above command line will generate gl_core_3_3.h and gl_core_3_3.c files. Simply include them in your project; there is no library to build, no unresolved externals to filter through.

You need to run their generator to produce those source files.


text:
Q: Attribute propagation rule for repeat (%) I have checked this webpage http://www.boost.org/doc/libs/1_44_0/libs/spirit/doc/html/spirit/qi/quick_reference/compound_attribute_rules.html, and many others, but couldn't find an answer to my question.
I have a rule of the form C %= A % B, where B is a parser and NOT a literal, and it is of different type than A. The rule given on the webpage above says:
a: A, b: B --> (a % b): vector<A>

but given that in my case B is a parser and not of type A this rule doesn't seem to do the trick.
I have tried out this:
(a % b): variant<A, tuple<B,A>>

and as a consequence defined this structure:
    struct equality_expression
    {
        variant<A,tuple<B,A>> equexp;
    };

and thereafter
    BOOST_FUSION_ADAPT_STRUCT(
        equality_expression,
        (variant<A,tuple<B,A>>, equexp);
    )

but the compiler complains:
warning C4002: too many actual parameters for macro 'BOOST_FUSION_ADAPT_STRUCT_FILLER_0'

So, what's the correct way of doing this?

A: The way to read a: A, b: B --> (a % b): vector<A> is: "if parser a exposes an attribute A and parser b exposes an attribute B then a%b exposes the attribute vector<A>", meaning that the attribute of B is always ignored in the list parser. The problem with your macro invocation are the commas that separate the template parameters.


text:
Q: Capture image and voice(use AS3) in flv, save to location, not media server How can I use AS3 to record video(with voice) by camera? I want it to be saved to location PC of user.

A: You can try flvRecorder, but what they declare :

The class does not yet support adding sound to the flv-file, this is the next step of development, to enable sound recording and add sound to the flv-file.

and it saves the file directly on the desktop, check the example.

This may be a solution too, that will allow you to record video/sound, give it a try,
Good luck, Cheers !!


text:
Q: Lisp program to check whether a binary tree is a Binary Search Tree
Write a Lisp program to check whether a binary tree is a Binary Search Tree.
The left sub-tree of a node has a key less than or equal to its parent node's key. The right sub-tree of a node has a key greater than to its parent node's key.

A list can be used to represent the structure of a binary tree as follows:
'(8 (3 (1 () ()) (6 (4 () ())( 7 () ()))) (10 (()) (14 (13) ()))) where this would return true.
I am trying to write a binary recursive approach but I'm a beginner and  I have no idea where to go from here.
(defun isBST (L)
   (cond
         ((null (first L)) t)
         ((and (not (null (caadr L)) ) (< (first L) (caadr L)) )  nil)
         ((and (not (null (caaddr L))) (> (car L) (caaddr L)))  nil)
         ((and (not (isBST (cadr L))) (not (isBST (caddr L)))) ))
  )

A: You can express your definitions in code to make your life easier.
A node is represented as a list of three things: a key, a left subtree, and a right subtree.
(defun node-key (node)
  (first node))

(defun node-left-subtree (node)
  (second node))

(defun node-right-subtree (node)
  (third node))

For a tree to be a binary search tree, four conditions must be met, unless both subtrees are empty:

*

*the left subtree must be a binary search tree

*the right subtree must be a binary search tree

*the largest key of the left subtree (if present) must be smaller than the root key

*the smallest key of the right subtree (if present) must be bigger than the root key

Note: the naming convention in Lisp is to write everything in lower case, with word parts separated by dashes.  A predicate, i. e. a function that is used to obtain a truth value, ends with p.  The predicate for a binary search tree might be named bst-p or binary-search-tree-p.  The function to obtain the largest key of a bst might be called bst-largest-key.

In order to get the largest (smallest) key of a BST, you only need to recurse on the right (left) subtree.

A: Here's a scheme procedure that might help you.
(define (is-bst l)
  (define (loop node proc)
    (if (null? node)
        #t
        (and (proc (car node))
             (loop (cadr node)
                   (curry > (car node)))
             (loop (caddr node)
                   (curry < (car node))))))
  (loop l (const #t)))

It can be frustrating to fix a program when your input data is the source of the bugs. I had to fix your (()) and (13). Use multiple lines and the auto-indenter to easily find mistakes.
(is-bst '(8 (3 (1 () ())
               (6 (4 () ())
                  (7 () ())))
            (10 ()
                (14 (13 () ())
                    ()))))

;; #t

Invalidate one of the nodes to ensure is-bst detects a non-bst.
(is-bst '(8 (3 (1 () ())
               (6 (4 () ())
                  (7 () ())))
            (10 ()
                (2 (13 () ()) ;; 14 changed to 2; invalid tree
                   ()))))

;; #f

To make a slight improvement, notice we called (car node) three times in the procedure above. This should be avoided with the use of let.
(define (is-bst l)
  (define (loop node proc)
    (if (null? node)
        #t
        (let ((value (car node)))
          (and (proc value)
               (loop (cadr node)
                     (curry > value))
               (loop (caddr node)
                     (curry < value))))))
  (loop l (const #t)))

Another interesting way is using streams, which can be easily implemented using basic procedures. We could write a generic traverse procedure to traverse our trees.
(define (traverse bst)
  (if (null? bst)
      empty-stream
      (stream-append (traverse (cadr bst))
                     (stream (car bst))
                     (traverse (caddr bst)))))

(define tree
  '(8 (3 (1 () ())
               (6 (4 () ())
                  (7 () ())))
            (10 ()
                (14 (13 () ())
                    ()))))

(stream->list (traverse tree))
;; '(1 3 4 6 7 8 10 13 14)

Now we write is-bst to simply check that the values come out in ascending order.
(define (is-bst l)
  (define (loop x s)
    (if (stream-empty? s)
        #t
        (let ((y (stream-first s)))
          (and (< x y)
               (loop y (stream-rest s))))))
  (loop -inf.0
        (traverse l)))

(is-bst tree)
; #t

(is-bst '(1 (2 () ())
            (3 () ())))
; #f

Because a stream is used, the values come out lazily. If an early #f is found, iteration of the stream is stopped and the computation is finished.