Q:

Approximation of Hilbert Transform Using Very Short Hilbert Transform FIR / IIR Filter

Hilbert transform is a quite sensitive topic here, since Gabor's paper,  Theory of Communication,  J. Inst. Electr. Engineering, London, 1946. Perhaps even more important than the Fourier transform.
There are short Gaussian FIR approximations, smoothing filters, or polynomial fits.
What would be methods for very short (say, less than $16$ taps) Hilbert tranform approximations of a signal, possibly including a weighting factor? I am intending to use them on small chunks of signals, in moving frames that progress along data as new samples are acquired. Signals can be considered freed from a potential low-frequency trend (e.g. polynomial).
Fey features would be:

a management or reduction of small-sized frame artifacts (I am aware of those for short Fourier frames, much less with short Hilbert transforms),
potential asymmetric windowing to add a forgeting factor to older samples,
a recursive formulation, in the spirit of the sliding DFT, would be a plus.

Finally, an IIR formulation, such as the one of the recursive least squares (RLS) adaptive filters, or the exponentially-weighted moving average filter, would be very interesting as well.

A:

This is more like an extended comment to chart the possible answers.
Hilbert transform is a frequency domain 90-degree phase shift of the signal. It has an antisymmetrical impulse response around time = 0. You specify that the approximation shall be causal (EDIT: this requirement has since been removed), so I think you need to reference the phase shift to that provided by another filter. If we denote the two filters F1 and F2, some usable alternatives are:
Case | Filter F1    | Filter F2           | Phase diff     | Magnitude frequency responses
-----+--------------+---------------------+----------------+------------------------------
  C1 | pure delay   | antisymmetrical FIR | exactly 90 deg | F2 has ripple
  C2 | pure delay   | all-pass IIR        | approx 90 deg  | No ripple
  C3 | all-pass IIR | all-pass IIR        | approx 90 deg  | No ripple

In all those cases you have two filters whose phase frequency responses have a phase difference of exactly or close to 90 degrees over the desired frequency band.
If the filter outputs are used "in quadrature" (summed, with the other multiplied by the imaginary unit) to create an analytic signal, any phase frequency response ripple will become magnitude frequency response ripple of the composite negative frequency removal filter.


Q:

android - add done to default android keyboard in portrait mode

I need to add done button in my keyboard
my tries I add

android:imeOptions="actionDone"
              android:imeActionLabel="DONE"
  to my Edittext

<EditText
            android:singleLine="true"
            android:id="@+id/passwordtext"
            android:layout_width="match_parent"
            android:imeOptions="actionDone"
            android:imeActionLabel="DONE"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/password"
             />

but I get done in landscape mode only , how can I have done inside off Enter

A:

What the keyboard displays is completely up to the keyboard (which is its own app).  It may decide to honor your request, it may not.  There is no way to force it-  you've done as much as you can to ask it to do so.


Q:

UIPanGestureRecognizer isn't firing up. Swift 3

My view hierarchy is following:

View

View For User's Img + Emoji (A)
View With UI elements. (B)

In viewDidLoad, I create UIImageViews for emojis, add them to the A and add gesture recognizers (pan,pinch,rotate):
 let emojiView = UIImageView(image: emoji)
            emojiView.tag = n
            emojiView.frame = CGRect(x: 153, y: 299, width: 70, height: 70)
            emojiView.isUserInteractionEnabled = true

            let pan = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
            pan.delegate = self
            emojiView.addGestureRecognizer(pan)

            let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
            pinch.delegate = self
            emojiView.addGestureRecognizer(pinch)

            let rotate = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
            rotate.delegate = self
            emojiView.addGestureRecognizer(rotate)

Later, I declare IBActions:
@IBAction func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.viewForImgAndEmoji)
    if let view = recognizer.view {
        view.center = CGPoint(x:view.center.x + translation.x,
                              y:view.center.y + translation.y)
    }
    recognizer.setTranslation(CGPoint.zero, in: self.viewForImgAndEmoji)
}

@IBAction func handlePinch(recognizer: UIPinchGestureRecognizer) {

    let pinchPoint = recognizer.location(in: viewForImgAndEmoji)
    let ourEmojiView = viewForImgAndEmoji.hitTest(pinchPoint, with: nil)

    ourEmojiView!.transform = ourEmojiView!.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
    recognizer.scale = 1

}

@IBAction func handleRotate(recognizer: UIRotationGestureRecognizer){

    let rotatePoint = recognizer.location(in: viewForImgAndEmoji)
    let ourEmojiView = viewForImgAndEmoji.hitTest(rotatePoint, with: nil)

    ourEmojiView!.transform = ourEmojiView!.transform.rotated(by: recognizer.rotation)
    recognizer.rotation = 0
}

Problem: the pan func isn't firing up. Rotate and pinch works. But panning isn't.
(Can't disable user interaction for overlaying view since it has buttons)

A:

OK, I took a look at the code and I see two possible issues:
1: You have pinch, pan, and rotate gesture recognizers set in the storyboard as well. These might be superfluous. Just mentioning that. This really isn't the issue your pan gesture recognizer isn't working though.
2: The UIView for controls covers your emoji and image view and will take over touches. You don't need a full-screen view for the UI controls since you don't seem to do anything with the view itself. Instead, you can simply put the button at the right position on the main screen over the viewForImgAndEmoji. This way, any on screen touches reach viewForImgAndEmoji except at the spots where you have the buttons.
I modified the storyboard that way and I could get the pan gestures fine at that point. Do let me know if you need me to clarify anything since I am not sure if I was clear enough about the issue :)
Note: One issue that you will run into when you fix the above is that you will find that not all touches register because the gesture recognizer is attached to each sticker and the sticker itself might be too small to detect something like a pinch gesture. You might be better off adding viewForImgAndEmoji as the gesture handler and activating each sticker/emoji as the recipient of the the gesture based on selecting the emoji by a tap before you try to pinch, rotate, or pan. Just a suggestion :)


Q:

Reading files from a txt file and placing contents in a List

I have a file in my project folder containing the data for properties in a Vehicle class. If the class was hardcoded into the XAML it would look like this:
  Vehicle v1 = new Car() { Make = "Ford", Model = "Fiesta", Price = 10000, Year = "1999", Colour = "Red", Mileage = 40000, Description = "Lovely red car, 4 wheel, optional steering wheel.", VehicleType = "Car" };
  VehicleList.Add(v1);

I don't want to hardcode this class object in, Instead I want to read it from a .txt file, each part separated by a comma ',' and place these into each property and add that vehicle into the Vehicle List<> 'VehicleList' and then display this new read list into a listbox.
Both the hardcode and the .txt follow the same structure with the hardcode containing the variable names and the .txt file containing just the data.
Here is what I have so far, as you can see I tried using System.IO however I am open to alternative methods.
        private void Button_Click(object sender, RoutedEventArgs e)
    {
        string location = @"PATH";
        VehicleList = File.ReadAllLines(location).ToList();

        var logFile = File.ReadAllLines(location);
        foreach (var v[i] in logFile) VehicleList.Add(s);
    }
}

A:

public static List<Car> FromTextFile(string fileName)
{
    var lines = File.ReadAllLines(fileName);

    var cars = new List<Car>();
    foreach (var line in lines)
    {
        var car = FromLine(line);
        if (car == null)
            continue;

        cars.Add(car);
    }

    return cars;
}

private static Car FromLine(string line)
{
    var values = line.Split(',');

    if (values.Length != 8) // There is no specification on what to do, if the amount of items is not sufficient.
        return null;

    // There is also no specification on what order to use, or how to map the ordering.
    return new Car
    {
        Make = values[0],
        Model = values[1],
        // There is also no specification on how to handle in-correct formats.
        // This assumes the Price property to be type of int.
        Price = int.Parse(values[2]),
        Year = values[3],
        Colour = values[4],
        // Again; how to handle in-correct formats?
        Mileage = int.Parse(values[5]),
        Description = values[6],
        VehicleType = values[7]
    };
}

This code should do what you described. Please be aware of the limitations of this code;

It expects a file that contains some lines, in comma seperated format.
It expects lines to contain 8 non-empty items, otherwise those lines will not be mapped.
It assumes the comma-seperated items to be exactly in this order; Make, Model, Price, Year, Colour, Mileage, Description, VehicleType.
It will not handle in-correct formats for converted types (e.g int). Because you did not ask so.

Keep in mind that this is not a desired code, it is not well written.
Now, as to your code;
Firstly, you've two different values for lines. I don't know why. One of them should be ok.
Second, you try to loop through one of them using foreach, but it doesn't work like that. You don't give or take an index from the foreach loop. The correct what is just foreach (TYPE VARIABLE_NAME in COLLECTION). So your code would be foreach (var v /* not v[i] */ in logFile) // ...
And then you add this to a list which contains those seperated lines again. At the end of the day, you have a list that contains the same lines twice. What you should have done in the adding part is, you should have converted the line to a Car object. Now how you do that, is absolutely up to you. Here are some question that comes to my mind, when the task is something such as mapping a string collection to an object.

What do I do if some members do not exist? (i.e when there is 5 items in the line, even though we have 8 properties)
How do I know which property to map the i'th item? What is the ordering? Do I get it from a "Columns" line? Do I just assume some ordering of my desire? How do I handle, if the user does not follow those rules?
What do I do, when there is something wrong about formatting of some of the members?

Now, this is not really an un-common problem. Everyone somehow needs to transport the data from place A to place B. For your specific instance, it is from disk storage, to memory, in the form of an object.
How do people solve these sorts of problem? They invent generic ways of "serialization" and "deserialization". What are some examples? The most known ones and the most used ones that comes to my mind are XML (eXtensible Markup Language) and JSON (JavaScript Object Notation). What do these actually do? They serialize programming objects to non-binary string formats. Here is an example XML output for your Car class.
<?xml version=\"1.0\" encoding=\"utf-16\"?>
<Car xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
  <Make>Ford</Make>
  <Model>Fiesta</Model>
  <Price>10000</Price>
  <Year>1999</Year>
  <Colour>Red</Colour>
  <Mileage>40000</Mileage>
  <Description>Lovely red car, 4 wheel, optional steering wheel.</Description>
  <VehicleType>Car</VehicleType>
</Car>

Generated with this simple code;
var car = new Car
{
    Make = "Ford",
    Model = "Fiesta",
    Price = 10000,
    Year = "1999",
    Colour = "Red",
    Mileage = 40000,
    Description = "Lovely red car, 4 wheel, optional steering wheel.",
    VehicleType = "Car"
};

var serializer = new XmlSerializer(typeof(Car));

// https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
using (StringWriter textWriter = new StringWriter())
{
    serializer.Serialize(textWriter, car);
    var output = textWriter.ToString();
}

And this is, how you would easily read "Car"s from a text file, if it was formatted correctly;
var serializer = new XmlSerializer(typeof(List<Car>));
// If your file should contain one car and one car only, you should change the above line to;
// var serilizer = new XmlSerializer(typeof(Car));

using (var reader = File.OpenRead(@"PATH"))
{
    var cars = (List<Car>)serializer.Deserialize(reader);
    reader.Close();
}

Similar code can be written for JSON. But I think you get the idea.
In short, most of the times, XML, JSON or a similar generic format is sufficient. When they are not, you can develop your very own format. But comma-seperated line is a very simplistic way of doing serialization. The reasons are exactly my question (see above). And XML, JSON answers those questions easily. Implementations do a very good job as well, most of the time.

Edit
Here is an answer to a very similar question. The  answer to that question would high likely also answer your question. How to split csv whose columns may contain ,


Q:

How to ignore value after first decimal point first value if it is 0 else take it if greater than 0?

I am having a value like below :
decimal val = 1.100;

Now what i am trying to do is if i am having 0 after first decimal point value then i want to take only 1.1 and ignore rest and if i am having 1.11 then i want to take whole 1.11
This is how i am thinking to do :
1) Convert decimal to string.
2) Split string by dot.
3) Check if length is 2 and if second position is greater than 0 then take whole like 11 for decimal value 1.11 else if decimal is like this 1.10 then take 1.1 else take 1.0 in case of decimal 1.000
Sample input and output:
1.000 // output 1.0
1.100 // output 1.1
1.110 // output 1.11
1.111 // output 1.111
1.102 // output 1.102

But this is dirty logic which i want to avoid.Isnt there is any inbuilt way or better way to do this??
Note: I dont want to do any kind of round up.

A:

You can use a custom numeric format string:
val.ToString("0.0##")


Q:

pygame how to rotate image properly?

In pygame I am unable to rotate an image/surface. The image is drawing properly just not rotating.
self.other1 = pygame.image.load("enemy.png").convert_alpha()
self.other2 = pygame.transform.rotate(self.other1, math.radians(270))
self.screen.blit(self.other2, (0, 0))

What exactly am I doing wrong?

A:

1.- Which version are you using (both pygame and python)?
2.- You don't need radians
3.- You must specify a problem your description seems ambiguous
Anyway I leave an example here. Good luck.
import pygame
from pygame.locals import *

SIZE = 640, 480
pygame.init()
screen = pygame.display.set_mode(SIZE)

done = False
screen.fill((0, 0, 0))
other1 = pygame.image.load("enemy.png").convert_alpha()
other2 = pygame.transform.rotate(other1, 270)
screen.blit(other2, (0, 0))
pygame.display.flip()

while not done:
    for e in pygame.event.get():
        if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
            done = True
            break


Q:

Specific software metrics for Clojure programs

We are considering writing a static analyzer to collect software metrics for Clojure code. Of course it will handle the obvious stuff like number of files, functions, parameters per function, etc. I wonder if there are any metrics that are specific for Clojure code. Any ideas?

A:

On average - I think that software metrics are a dubious idea - they usually distract you from the really important question which is "how much value are we delivering to the customer??".
Having said that, I recognise they can be a necessary evil in some contexts and can occasionally give you some useful insights about your code base.
So here's a few that might be Clojure-specific.

Number of top-level defines (perhaps expressed as a ratio to total symbol count?)
Java coupling: % of symbols related to Java interop (new, ClassName., .someMethod etc.) - ideally keep coupling confined to specific modules responsible for Java interop, i.e. should be verey low % everywhere except libraries that manage the interop.
Average maximum nesting level of function defns (I guess 5ish good, 10+ bad??)
Macro density: % of forms that require macro expansion
% of functions with docstrings
% of symbols or function parameters defined with type hints
Average size of anonymous functions (these should probably be small!)
% of functions in clojure.core used (gives some idea of the "vocabulary range" and sophistication of the code)
(Thanks nickik!) number of ref-types created (dynamic vars, atom, ref and agent) - essential if you want to keep careful control of your mutable state!

p.s. if you get this working it would be really interesting to see the variation in results across some of the different open source clojure projects!


Q:

Distributed TensorFlow: about the using of tf.train.Supervisor.start_queue_runners

I'm looking into the code for distributed inception model in TF, in which I have below questions about the use of tf.train.Supervisor.start_queue_runners in inception_distributed_train.py:

Why do we need to explicitly call sv.start_queue_runners() in line
264 and line 269 in inception_distributed_train.py? In API
doc. of start_queue_runners, I see there is no need for such
calls due to:

Note that the queue runners collected in the graph key QUEUE_RUNNERS
  are already started automatically when you create a session with the
  supervisor, so unless you have non-collected queue runners to start
  you do not need to call this explicitly.

I noticed the values of queue_runners in calling
sv.start_queue_runners are different in line 264 and line
269 in inception_distributed_train.py. But aren't
chief_queue_runners also in the collection of
tf.GraphKeys.QUEUE_RUNNERS (all QUEUE_RUNNERS are obtained in line 263)? If
so, then there is no need for line 269 since the chief_queue_runners has already
been started in line 264.
Besides, could you please explain to me or show me some references about what queues are created in tf.train.Supervisor?

Thanks for your time!

A:

Not an answer, but some general notes how to find an answer :)
First of all, using github's blame, inception_distributed was checked in on April 13, while that comment in start_queue_runners was added on Apr 15th, so it's possible that functionality was changed but didn't get updated in all the places that use it.
You could comment-out that line and see if things still work. And if not, you could add import pdb; pdb.set_trace() in the place where queue runner gets created (ie here) and see who is creating those extra unattended queue runners.
Also, Supervisor development seems to have slowed down and things are getting moved over to FooSession (from comment here). Those provide a more robust training architecture (your workers won't crash because of temporary network error), but there are not many examples on how to use them yet.


Q:

Can't launch anything from terminal after uninstalling fink! Mac Lion

I've got a big problem, I can't launch anything from the terminal, not python, not emacs (or aquamacs), not even 'which'.
I was using homebrew to try to install ffmpeg and was having difficulties so I decided to pay attention to the warning that always come up advising me to uninstall fink. I removed the sw directory from my root directory, which is what the fink website told me to do and was confirmed on many blogs and message boards after a quick google search.
And since then nothing has worked, I'm almost certain that this was the cause of the problem because after removing sw I immediately tried home brew again and it said 'brew: command not found'. I get the same warning with any and every program I try to launch.
I use Mac OS Lion on a 6 year old MacBook.
Any ideas?

A:

You probably busted your PATH.  You can use absolute paths to commands until you get it fixed.  For example:
/bin/mv ~/.profile ~/.profile.bak
/bin/mv ~/.bash_profile ~/.bash_profile.bak

Then open a new Terminal window, where standard things should now work. and repair your profile script.


Q:

How do I get the amount of child that has the same value?

How do I get the amount of child (Ex. "1234" & "fdsasda") that has the same value for the category.
Lets say I want to know how many items are in category C, how will I go on about that with a value event listener.
 // removed unimportant things
  "1234" : {
    "category" : "C",
  },
  "fdsasda" : {
    "category" : "B",
  },

A:

For this, first you have to make sure that there are no parent nodes between the root node and these child nodes that you have shown in your structure.
Then what you can do is, use orderByChild() to order your database with the child category and use equalTo() to compare it to your desired value and count the occurrences.
What I am saying, looks something like this in code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

Query query = rootRef.orderByChild("category").equalTo("C");

query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long count = dataSnapshot.getChildrenCount();
                Log.d("TAG", count + "");

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "onCancelled", databaseError.toException());
            }

        });


Q:

Optimizing a Dictionary for comparison when the key is based upon several identifying attributes

I have the following code:
if (!this._masterAccountDefinitions.ContainsKey(
     outletName.ToLower(CultureInfo.CurrentCulture) + "/" +
     officeName.ToLower(CultureInfo.CurrentCulture))
   ) {
     //Add new item to list
}

Essentially, the dictionary is keyed by the combination of an Outlet Name and Office Name.  This code will be called extensively and it just seems to do some pretty harsh string transformation.  I'm looking for suggestions on a more efficient way of keying the dictionary than simply concatenating the string values.

A:

Assuming that by efficiency you mean performance - it's hard to speculate what changes to the approach of concatenating strings as a key will yield better performance - you have to first understand what the bottlenecks are.
However, one idea that comes to mind is to create a separate class to just represent the key and override its Equals() and GetHashCode() methods. They would use the individual fields using case-insensitive comparison in Equals() and XOR'ing the hash codes in GetHashCode().
This may help avoid the cost of converting the strings to lower-case and eliminate the need to concatenate them. However, it introduces the cost of keying the collection with a custom class that needs to be instantiated for each item stored in the dictionary. Also, the hashing algorithm may be less optimal (ie cause more collisions) than hashing a concatenated string.
I would strongly advise you to spend some time profiling your code to determine that just concatenating the strings isn't efficient enough in your case - before converting to a more complicated alternative.
Here's a very crude prototype to start with:
public class AccountKey
{
   private readonly string m_OutletName;
   private readonly string m_OfficeName;

   public AccountKey( string outlet, string office )
   {
      m_OutletName = outlet;
      m_OfficeName = office;
   }

   public string OutletName { get { return m_OutletName; } }
   public string OfficeName { get { return m_OfficeName; } }

   public override bool Equals( object otherKey )
   {
      AccountKey otherAccountKey = otherKey as AccountKey;
      if( otherAccountKey == null )
         return false;

      // uses Compare( s1, s2, ignoreCase ) overload - which assumes current culture
      // alternative culture can be passed in as another parameter after ignore case
      // uses short-circuit and to avoid comparing both strings if one already differs
      // you could order these based on your domain knowledge more optimally - for
      // example if Offices vary more frequently than Outlet, make that compare first.
      return String.Compare( m_OutletName, otherAccountKey.OutletName, true ) == 0 &&
             String.Compare( m_OfficeName, otherAccountKey.OfficeName, true ) == 0;
   }

   public override int GetHasCode()
   {
      // this may not be optimal, but it's a starting point
      return OutletName.GetHashCode() ^ OfficeName.GetHashCode();
   }
}


Q:

Tag DIV excedendo a largura

tenho meu portfólio e tenho alguma <div> está estourando a largura, porém não encontro.
Link para o site

na imagem o overflow

A:

O div que está "estourando" a width está localizado na linha 473(basicamente é o div que introduz a informação do facebook).
Adicione:
style="width:auto;"

No Div em causa e o problema deverá ficar resolvido.
Caso não fique, utilize a funcionalidade 3D oferecida pelo firefox e procure pelo elemento que está a sair da resolução do display.


Q:

Thymleaf - Unsupported entity requested with PUBLICID "null"

When using Thymleaf with Spring MVC I ran into this issue which just prints this stack trace.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is
org.thymeleaf.exceptions.TemplateProcessingException: Unsupported entity requested with PUBLICID "null" and SYSTEMID "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd". Make sure a corresponding org.thymeleaf.doctype.resolution.IDocTypeResolutionEntry implementation is provided by you dialect
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
root cause
org.thymeleaf.exceptions.TemplateProcessingException: Unsupported entity requested with PUBLICID "null" and SYSTEMID "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd". Make sure a corresponding org.thymeleaf.doctype.resolution.IDocTypeResolutionEntry implementation is provided by you dialect
org.thymeleaf.templateparser.EntityResolver.resolveEntity(EntityResolver.java:72)
org.thymeleaf.templateparser.xmlsax.AbstractNonValidatingSAXTemplateParser$XmlSAXHandler.resolveEntity(AbstractNonValidatingSAXTemplateParser.java:708)
org.thymeleaf.templateparser.xmlsax.AbstractNonValidatingSAXTemplateParser$XmlSAXHandler.resolveEntity(AbstractNonValidatingSAXTemplateParser.java:716)
com.sun.org.apache.xerces.internal.util.EntityResolver2Wrapper.resolveEntity(EntityResolver2Wrapper.java:173)
com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1190)
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1088)
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1001)
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647)
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:513)
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:815)
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:744)
com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:128)
com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1208)
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:543)
javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
org.thymeleaf.templateparser.xmlsax.AbstractNonValidatingSAXTemplateParser.doParse(AbstractNonValidatingSAXTemplateParser.java:209)
org.thymeleaf.templateparser.xmlsax.AbstractNonValidatingSAXTemplateParser.parseTemplateUsingPool(AbstractNonValidatingSAXTemplateParser.java:133)
org.thymeleaf.templateparser.xmlsax.AbstractNonValidatingSAXTemplateParser.parseTemplate(AbstractNonValidatingSAXTemplateParser.java:116)
org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:277)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

I am documenting this as a reference for future users who come across this issue, as this is not documented even in in the thymleaf site.

A:

The problem was that I was using the wrong declaration in the DOCTYPE, since I was using spring mvc I should have used
For Spring 4
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">

For Spring 3
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">

A:

Setting so helped me in spring boot, Spring version 4:
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">


Q:

Data Type Mismatch in code - why now?

up to now my code has been working fine - but for some unknown reason it doesn't work anymore and is throwing as error:
Run-time error '13':
Type mismatch

Here is where the error is occurring:
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("qryGetEventsByNonPharmacists")

The query exists and it a basic SELECT query. This has never been a problem before so why is this throwing an error?
Thanks

A:

That should probably be:
Dim rst As DAO.Recordset

While you can get away with Recordset as long and you do not have a reference to the ADO libraries, or when the ADO libraries come after the DAO library, for the most part your are much better off always using an explicit reference to the library for the Recordset.


Q:

How to calculate exchange rate with python script

A bank has the following exchange rates: 83.5 ($ to tzsh), 86.8 (tzsh to $). A customer wants to repeatedly exchange 1,000 dollars back and forth from dollars to shillings and vice versa. Develop a simple program (in any language) to show after how many exchanges the customer ends up with zero.
I am new at Python and I am sure there is something wrong with my code:
x=0
y=1000
while x<1000:
    x=(83.5*y)/86.8
    print x
    y=x

A:

The problem is it only approaches but never actually reaches 0. So, you might want to either set it less than 1 or check when it's really really close to 0 depending on your requirement.
balance = 1000
transactions = 0

while balance > 1:
    shillings = balance * 83.5
    balance = shillings / 86.8
    transactions += 1
print(transactions, balance)

Output:
179 0.9701710363275966

So on transaction number 179, the balance becomes less than $1.
If you want to count conversion from $ to shillings and back as two transactions, instead of transactions += 1, use transactions += 2

A:

My answer is going to deviate from Ashish's answer because he considers the exchange from $ to tzsh and tzsh to $ as 1 transaction, while my approach considers $-to-tzsh and tzsh-to-$ as separate transactions:
i = 0
currency = 1000
while currency > 1:
    if i % 2 == 0:  # if converting from $ to tzsh
        currency = 83.5 * currency
    else:  # if converting from tzsh to $
        currency = currency / 86.8
    i += 1
print(i)

Result:
358


Q:

What is the difference between CRC-16/CCITT-FALSE and CRC-16/X-25?

I want to implement CRC-16/X-25. I have a code written in C for CRC-16/CCITT_FALSE, but I don't know what changes do I need to make in that code for CRC-16/X-25 implementation?
The code I am using for CRC-16/CCITT-FALSE is given below:
#include  <msp430.h>

#define CRC_POLYNOMIAL      0x1021
#define USHORT_TOPBIT       0x8000

short crc_ret;

// function initialisation

unsigned short crc16(const char *buf, unsigned int buf_len)
{

    unsigned short ret = 0xFFFF;        // Initial Value
    int bit = 8;

    do {
        if (!buf) {
            break;
        }
        unsigned int i = 0;
        for (i=0; i<buf_len; ++i) {
            ret = (unsigned short)(ret ^ ((unsigned short)buf[i] >> 8));
            for (bit = 8; bit > 0; --bit)
            {
                if (ret & USHORT_TOPBIT)
                    ret = (unsigned short)((ret >> 1) ^ CRC_POLYNOMIAL);
                else
                    ret = (unsigned short)(ret >> 1);
            }
        }
    } while (0);
    return ret;
 }

int main(void)
{
  PM5CTL0 &= ~LOCKLPM5;               // Disable the GPIO power-on default high-impedance mode to activate
                                      // previously configured port settings

  char buf[16];

  buf[0] = 0x5A;                    //buf[0], buf[1] and buf[2] are data bytes

  buf[1] = 0xCF;
  buf[2] = 0x00;

  crc_ret = crc16(buf, 3);   // Calling CRC function

}

A:

According to the website below, CRC16/CCITT_FALSE doesn't match your code. The website indicates it's a left shifting (non-reflected) CRC, while your code is right shifting.
CRC16/X25 is a right shifting (reflected) CRC, and returns ~CRC (CRC xor 0xFFFF). I don't know if this is the same as CRC16/CCITT_X25.
http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
You can use the website to compare your results with it's results.
I started with a simple example to create the two crc16 functions:
uint16_t crc16_ccitt_false(char* pData, int length)
{
    int i;
    uint16_t wCrc = 0xffff;
    while (length--) {
        wCrc ^= *(unsigned char *)pData++ << 8;
        for (i=0; i < 8; i++)
            wCrc = wCrc & 0x8000 ? (wCrc << 1) ^ 0x1021 : wCrc << 1;
    }
    return wCrc;
}

uint16_t crc16_x25(char* pData, int length)
{
    int i;
    uint16_t wCrc = 0xffff;
    while (length--) {
        wCrc ^= *(unsigned char *)pData++ << 0;
        for (i=0; i < 8; i++)
            wCrc = wCrc & 0x0001 ? (wCrc >> 1) ^ 0x8408 : wCrc >> 1;
    }
    return wCrc ^ 0xffff;
}


Q:

jQuery.html() returns invalid IMG

Possible Duplicates:
Jquery html() and self closing tags
Is it expected that jQuery $('span').html() turns XHTML br tag to html syntax?

I have a document like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I want to retrive html for some nodes to do something. But I see one problem with IMG.
$('#content').html();

This returns invalid XHTML

jQuery version is 1.4.2.

A:

This is a duplicate, but none of the answers in the original question gives an actual  workaround. (Probably rightly so. I can't but agree with what @Cletus says in his - as always excellent - answer.)
But if you're stuck with XHTML: there is a jQuery plugin providing a innerXHTML() function (poorly maintained though, last updated 2007, and never made it from Beta) and a JavaScript tool named innerXHTML that promises to do what you need. If you need this, that may be your best bet.

A:

innerHTML/html() won't give you an XHTML serialisation unless you've actually served the page as XHTML, under the application/xhtml+xml media type. (And that doesn't work on IE<9.) If you are serving your page as text/html, then your self-closing tags are nothing but ignored clutter to the browser when it's parsing your source into a DOM. You cannot expect to get the same format HTML out of the DOM serialised from that as you put in.
In fact in some cases in IE innerHTML won't even give you a valid HTML serialisation: it omits quotes around attr in some cases where it shouldn't. In short, you cannot rely on innerHTML giving you any particular format of markup. It might re-order attributes, it might HTML-escape different characters, it might normalise attribute values, it might change whitespace. So doing string operations on the html() return value is a non-starter. All you can rely on is that you can assign the serialised markup back to the innerHTML of another element and the browser will be able to parse it.
What's your purpose in trying to retrieve XHTML? You may be able to achieve more using normal DOM-style manipulations.
ETA re comment:
Then XHTML validity is the least of your worries. It doesn't matter if the HTML isn't well-formed, you will still be able to write it back to html(). But:
What you can't reliably do with the html() is tell what sentences are in text content and what are in attribute values. For example  is markup and if you start putting s inside the title attribute, you're obviously going to have difficulties.
This is a text-processing task, so you should do it on text nodes, not markup. This is a bit tricky and jQuery doesn't give you any special tools to do it. But see the findText function from this answer and you could use it like:
// Split each text node into things that look like sentences and wrap
// each in a span.
//
var element= $('#content')[0];
findText(element, /.*?[.?!]\s+?/g, function(node, match) {
    var wrap= document.createElement('span');
    node.splitText(match.index+match[0].length);
    wrap.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

A:

.html() doesn't return the HTML or XHTML markup that was provided to make the nodes, it returns the browser's internal representation of the relevant nodes.  This internal representation is not XHTML compliant and is not made to be--it's technically an internal implementation detail.
You can throw any HTML or XHTML at a browser and it will parse it into an internal DOM.  The internal DOM does not differ if the original source was crappy HTML, good HTML, or perfect XHTML.  The resulting DOM for equivalent source documents will be the same, but generating a new HTML document from that will not necessarily be exactly the same as the source.


Q:

How can I add a due date to OS X Reminders?

I would like to know if it is possible to add the due date checkbox shown in my screenshots to the OS X version of Reminders. I am not looking for the notification option, just the old fashioned due date option.
The due date checkbox is not an option normally. "Test item" was created on the OS X Reminders app.
However if I make one, "Test item 2", on iCloud.com, I have the option to add a due date. This is then changed, through iCloud, on my Mac.
This leads me to believe that maybe a file could be changed on my Mac to enable this option to be turned on by default.

A:

You can use AppleScript with this one-liner to create an item with the Due Date independent of the Remind Me Date:
tell application "Reminders" to show (make new reminder with properties {name:"New reminder", due date:(current date)})

Or you can use Automator to create a Service that does the same thing. That way, you can assign a keyboard shortcut to it in System Preferences. See the Services list under System Preferences… Keyboard… Shortcuts… Services.
In Automator, add the New Reminders Item snippet and make sure Due Date is checked. Use menu item File… Save to save the workflow in the default location (~/Library/Services/). The Service should now be visible in the Reminders application, under menu item Reminders… Services….


Q:

Azure ML deploy locally: tarfile.ReadError: file could not be opened successfully

I am trying to deploy(local) using this line:
local_service = Model.deploy(ws, "test", [model], inference_config, deployment_config)

Then I get this output in the terminal:
tarfile.ReadError: file could not be opened successfully

Screenshot of the output

A:

There was a bug with the retry logic when files were being uploaded. That bug has since been fixed, so updating your SDK should fix the issue.
Similar post: Registering and downloading a fastText .bin model fails with Azure Machine Learning Service


Q:

How to use MySQL if statement for column name?

I have table:
mysql> DESCRIBE swaps;
+-------------+----------+------+-----+---------+----------------+
| Field       | Type     | Null | Key | Default | Extra          |
+-------------+----------+------+-----+---------+----------------+
| id          | int(11)  | NO   | PRI | NULL    | auto_increment |
| user1_id    | int(11)  | NO   |     | NULL    |                |
| user2_id    | int(11)  | NO   |     | NULL    |                |
| hasto       | int(11)  | NO   |     | NULL    |                |
| requested   | datetime | NO   |     | NULL    |                |
| accepted    | datetime | YES  |     | NULL    |                |
| swapped1    | datetime | YES  |     | NULL    |                |
| swapped2    | datetime | YES  |     | NULL    |                |
| rejected    | datetime | YES  |     | NULL    |                |
| rejected_by | int(11)  | YES  |     | NULL    |                |
+-------------+----------+------+-----+---------+----------------+

where user1_id and user2_id represents users that are swapping and swapped1/swapped2 represent time when they affirm swap. I need to create mechanism to close swap when both have confirmed swap.
I need something like this:
UPDATE swaps SET if(user1_id = ?, swapped1, swapped2) = ? WHERE id=?

where ? marks represent current user, current time, swap_id. What I want is to insert time into swapped1 if current user is user1 and into swapped2 if current user is user2.
Running this query I get error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if(user1_id = '3', swapped1, swapped2) = '2017-01-13 07:34:08' WHERE id='3'' at line 1

what means that I am not using if statement correctly. Is there a way to perform if statement on column name?

A:

You can't use IF on the left side of an assignment, but you can update both columns conditionally:
UPDATE swaps
   SET swapped1 = IF(user1_id = [current_user], [current_time], swapped1)
     , swapped2 = IF(user2_id = [current_user], [current_time], swapped2)
 WHERE id = [swap_id];


Q:

Odd console.memory results in Chrome, negative numbers in timeline memory dev tools, a Chrome bug?

After running for a very long time (a day or more) a web-based app I wrote (JS/HTML5) starts acting "weird".  Primarily it stops sending the normal data it should to the backend, where I expect it to be sending ~500kb of data it starts sending just a few bytes of nonsense.  I suspected this was memory related (unable to allocate memory or something?) and when I investigated I saw something truly strange and seemingly impossible, which suggests to me that it's a Chrome bug I'm encountering perhaps through high memory usage.  But I could use some confirmation from someone who knows better than I do.
The main oddness seems to be what console.memory spits out.  The linked document says that "usedJsHeapSize can not be greater than totalJsHeapSize" which it very, very much is.  It's also higher than the heap size limit, which I imagine it should not be:

I then tried to see what devtools might tell me and did a timeline of memory at that instant, for a few seconds, and look at what it says....  the memory ranges from some negative insanely big number to 0B.  That sure doesn't seem right.

And I checked the chrome://memory report and while it is using a lot of memory, comparing that to other Chrome browsing sessions I have going it doesn't seem freakish.

Can anyone confirm this is a Chrome bug versus expected dev tools behavior I'm not interpreting correctly.
Thanks!

A:

Values are bucketed to prevent side-channel attacks
Bucketing described here: http://goo.gl/fFspKO
Get precise numbers with Chrome flag: --enable-precise-memory-info


Q:

concatenate key value pairs from python dictionary

I have a dictionary in python. The keys and the values are both strings. In fact the keys are some kind of flag (like -f) and the values are the options (e.g. an int like 20). What I want to do is to create a string with all the keys and values.
The dictionary could look something like this:
{'-f': 20, '-d': 30} and what I would like is something like this:
"-f 20 -d 30"
I think this should be any easy task, but I couldn't find a solution until now...

A:

Here's one approach using a list comprehension:
d = {'-f': 20, '-d': 30}
' '.join([i for k,v in d.items() for i in [k, str(v)]])
# '-f 20 -d 30'

Which is equivalent to:
out = []
for k,v in d.items():
    for i in [k, str(v)]:
        out.append(i)

' '.join(out)
# '-f 20 -d 30'


Q:

Tomcat access logs - are failed requests included?

We have a RESTful web service (Java, hosted in Tomcat on Ubuntu on Amazon EC2). From time to time it fails (not every week). When it fails, Java CPU consumption goes to 100% and it takes all available memory. It does not finish by itself. I have to restart the server.
There is nothing suspicious in Tomcat access logs.
I guess one of our users could submit a very "heavy" request which brought the server down.
Is it possible this request is not in Tomcat logs since it never finished?

A:

Tomcat logs the end-time of the request in the access log so only completed requests are logged. We had a similar issue and a similar suspicion. Using WireShark we monitored all traffic and discovered the requests which caused our problem.
A better idea would be to put an Apache Server in front of tomcat and log there, alternatively a load balance could perform the same function.


Q:

How to copy multiple elements to clipboard in Flex?

My aim is to copy multiple row content from Flex datagrid, to a clipboard enabling users to take pieces of information and pasting them were they are necessary.
I bumped into a problem that in Flex (as far as I know) its not possible to paste whole array of information in the clipboard.
At the moment, I pass selected datagrid items to a textfield, and then run
"System.setClipboard(text_area.text);"
I was wonderng if there is a way to pass it to multiple Clipboard directories, without overwriting previous entry, similar as when you can copy multiple items from different location into a clipboard, pile them up and then paste all at once?

A:

Flex can put any string value into a clipboard.  It doesn't support--as far as I know--complex values, such as arrays.  That said, you can convert your array into something along the lines of a comma or tab delimited file.
Separate rows using carriage return and line feeds.  Separate columns using commas tabs.  Conceptually something like this:
resultString += row1Column1 + ',' + row1Column2 + '\r\n';
resultString += row2Column1 + ',' + row2Column2 + '\r\n';

You didn't tell us how / why you want to preserve formatting.  I know cutting and pasting from Flex to Excel will recongnize the carriage return / line feeds as rows.  I do  not know if it will automatically detect multiple columns using a comma or tab, though.


Q:

Issues Applying css styles conditionally to a twitter-bootstrap table

I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?
my css:
.found {
    background-color: green;
}

my html table and input field:

         Description
         Price
         Qty
         Barcode

            {{item?.ProductDetail_Name}}
            {{item?.Amount}}
            {{item?.Qty}}
            {{item?.Barcode}}

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"> Search</button>
    </form>

//my ts component function that sets spotCheckBarcode
spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}

A:

your class is not applied to td. you need to be bit more specific with css for table here.
.found td { background-color: green; }


Q:

Printing HTML in ng-repeat

I have an ngController which contains, amongst other things, an array of questions and answers:
$scope.faqs = [
        {
            question: "QUESTION 1",
            answer: "ANSWER 1"
        },
        {
            question: "What is the dress code?",
            answer: "See here."
        },
        {
            question: "QUESTION 3",
            answer: "ANSWER 3"
        }
    ];

In my HTML I then cycle through these to display them:

            <button class="collapsible">{{ faq.question }}</button>

{{ faq.answer }}

However, for the middle question in my array, it prints the whole item as a string. I can understand why this is the case, however I would like for it to have the link clickable.
I have tried the suggestion from How to parse HTML in ng-repeat in angular.js by changing my

{{ faq.answer }}

to

but that has just served to stop anything printing. Can anyone help with an alternative suggestion or fix please?

Please note: I am just starting out with angularjs and web development so please  try to keep your answers simple and bear with me if I have to ask for clarification.

A:

You could use ngSanitize and make your answers to be trusted has html like this:
angular.forEach($scope.faqs, function(faq) {
  faq.answer = $sce.trustAsHtml(faq.answer);
});

For this you will need to use the $sce service.
And then bind them like this:

See below working full sample:

angular.module('app', ['ngSanitize']).controller('FAQController', function($scope, $sce) {
  $scope.faqs = [{
      question: "QUESTION 1",
      answer: "ANSWER 1"
    },
    {
      question: "What is the dress code?",
      answer: "See here."
    },
    {
      question: "QUESTION 3",
      answer: "ANSWER 3"
    }
  ];
  angular.forEach($scope.faqs, function(faq) {
    faq.answer = $sce.trustAsHtml(faq.answer);
  });
});

      <button class="collapsible">{{ faq.question }}</button>


Q:

Does undoing a downvote reverse the one reputation point loss?

Possible Duplicate:
How does “Reputation” work?

If I downvote accidentally, or downvote first and later realize that it's not worth downvoting and undo the downvote, do I get back the 1 reputation point lost because of downvoting?

A:

Yes, you get the 1 reputation back. Undownvoting in all senses is literally a reversal of the original downvote. Meaning all reputation effects of the downvote are also reversed.


Q:

Making so that my get python-requests are faster

I have a python-script with a lot of exceptions. I'm trying to make around 50,000 requests. And it is very slow as of now also I'd like for my script to be running therefore I added almost all the exceptions request has which has mostly to do with connectionError etc.
Is there a way I can make this script so it's much faster than it is now and more modular?
for i in range(50450000,50500000):
    try:
        try:
            try:
                try:
                    try:
                        try:
                            try:
                                try:
                                    try:
                                        try:
                                            try:
                                                try:

                                                    check_response = 'http://www.barneys.com/product/adidas--22human-race-22-nmd-sneakers-'+str(i)+'.html'
                                                    make_requests = requests.get(check_response,headers=headers).text
                                                    soup  = BeautifulSoup(make_requests)
                                                    try:
                                                        main_wrapper = soup.find('h1',attrs={'class':'title'}).text
                                                        print main_wrapper + ' ' + str(i)
                                                    except AttributeError:
                                                        arr.append(check_response)
                                                        with open('working_urls.json','wb') as outfile:
                                                            json.dump(arr,outfile,indent=4)

                                                except requests.exceptions.InvalidURL:
                                                    continue
                                            except requests.exceptions.InvalidSchema:
                                                continue
                                        except requests.exceptions.MissingSchema:
                                            continue
                                    except requests.exceptions.TooManyRedirects:
                                        continue
                                except requests.exceptions.URLRequired:
                                    continue
                            except requests.exceptions.ConnectTimeout:
                                continue
                        except requests.exceptions.Timeout:
                            continue
                    except requests.exceptions.SSLError:
                        continue
                except requests.exceptions.ProxyError:
                    continue
            except requests.exceptions.HTTPError:
                continue
        except requests.exceptions.ReadTimeout:
            continue
    except requests.exceptions.ConnectionError:
        continue

A:

First, please replace all these ugly try/except blocks by a single one, like:
for i in range(50450000,50500000):
    try:
        check_response = 'http://www.barneys.com/product/adidas--22human-race-22-nmd-sneakers-'+str(i)+'.html'
        make_requests = requests.get(check_response,headers=headers).text
        soup  = BeautifulSoup(make_requests)
        try:
            main_wrapper = soup.find('h1',attrs={'class':'title'}).text
            print main_wrapper + ' ' + str(i)
        except AttributeError:
            arr.append(check_response)
            with open('working_urls.json','wb') as outfile:
                json.dump(arr,outfile,indent=4)
    except requests.exceptions.InvalidURL:
        continue
    except requests.exceptions.InvalidSchema:
        continue
    except requests.exceptions.MissingSchema:
        continue
    ...

And if everything you do is continue in all cases, use the base class RequestException.  It becomes:
try:
    check_response = 'http://www.barneys.com/product/adidas--22human-race-22-nmd-sneakers-'+str(i)+'.html'
    make_requests = requests.get(check_response,headers=headers).text
    soup  = BeautifulSoup(make_requests)
    try:
        main_wrapper = soup.find('h1',attrs={'class':'title'}).text
        print main_wrapper + ' ' + str(i)
    except AttributeError:
        arr.append(check_response)
        with open('working_urls.json','wb') as outfile:
            json.dump(arr,outfile,indent=4)
except requests.exceptions.RequestException:
    pass

Maybe not faster, but for sure far easier to read!
As for the speed issue, you should consider using threads/processes.  Take a look at the threading and multiprocessing modules.


Q:

Rendering after dispatch in react-redux

I have one doubt with react-redux.
The component must be rendered after finish fetching data. The current code returns always {}. How can I solve this issue?
function Category(props) {
  const [categories, setCategories] = useState([]);
  props.dispatch(categoryActions.fetch());
  useEffect( () => {
    setCategories(props.categories)
  }, [props]);

  return (
    <Container className={classes.root}>
        .....
    </Container>
  );
}

const mapStateToProps = state => ({
    categories: state.categories,
});

function mapDispatchToProps(dispatch) {
    return {
      dispatch,
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Category)

A:

First, I have some questions:

What does const [categories, setCategories] = useState([]); do?
categories are provided as props to Category component by Connect.
useState hook is used to define and control internal state.
It's not conflicting technically since you can call them props.categories and  categories respectively but there might be confusion.
What actions do you want to dispatch in the component?
mapDispatchToProps looks doing nothing.
Have a look at their official example.


Q:

Rake Aborted when doing a migration to a server

Im trying to do a migration in my server but i get this code when i do rake db:migrate . I did it perfectly on my computer.
Please install the sqlite3 adapter: `gem install activerecord-sqlite3-adapter` (sqlite3 is not part of the bundle. Add it to Gemfile.)
/home/magnet/.rvm/gems/ruby-1.9.3-p448@global/gems/bundler-1.3.5/lib/bundler/rubygems_integration.rb:214:in `block in replace_gem'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/connection_adapters/sqlite3_adapter.rb:3:in `<top (required)>'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:50:in `resolve_hash_connection'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:25:in `spec'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:130:in `establish_connection'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/railtie.rb:82:in `block (2 levels) in <class:Railtie>'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:25:in `each'
/home/magnet/liga7/shared/bundle/ruby/1.9.1/gems/activesupport-

.....
Does someone know what to do ?
Thank you very much

A:

Better you could you gem pg,because it will support all database adapter,
Add in Gemfile
gem 'pg'

then
bundle install

then start migrate.


Q:

DataFrame set up using Dicts, Unexpected Setup

I am scraping each of these columns off of a website using XPATH. When I am finised pulling off all the columns, I am trying to put them together in one group of columns and then into a dataframe. I am following instructions I found online exactly, but am getting the image below instead of a normal table. What is going on here?
Also, I organized them in lists and created the dataframe from items the first time I attempted this, but then all of my columns were list and I could not change them to integers so I could do some group-by analysis on them.
Please help!

apt_data = {'Street': [street],
              'House_Number': [house_number],
              'Neighborhood': [areas],
              'Rent': [result_price_info],
              'Listing': [listing],
              'Number of Photos': [num_photos],
              'Rooms': [room_info],
              'Total Area': [size_info],
              'Year Built': [year_info],
              'Floor': [floor_info],
              'Material': [material_info],
              'Item Type': [type_info],
              'Last Updated': [update_info]
            }

# Organize into a Pandas Dataframe
apt_search = pd.DataFrame.from_dict(apt_data)
apt_search

A:

I think there is problem nested lists.
So need remove [] like:
'Street': [street]

to:
'Street': street

for all lists in dictionary.


Q:

Why was ramjet fuel used as hydraulic fluid during Saturn V checkout?

Fuel is also used within the engine as a lubricant and as a hydraulic
  working fluid, though before launch, RJ-1 ramjet fuel is supplied from
  the ground, it being more suited for this purpose.

https://history.nasa.gov/afj/ap11fj/01launch.html
I can't seem to find any more background on why this was done. What properties made RP-1 unsuitable for ground use?

A:

What a fascinating question!
Turns out it's less flammable.

Ground Supply Fluid—Because the flash point of RP-1 fuel, which
  supplies the system in flight, is 110 to 139° F, it is classified as a
  Class Ill flammable liquid, not suitable for ground operations. A
  study was made to find substitute fluids with properties similar to
  RP-1 that could be used in the laboratory and in ground operations.
Such a fluid was found in RJ-1, a ramjet fuel. It has properties very
  similar to RP-1, but a flashpoint ranging from 190 to 208° F. If
  purchased with a specified flashpoint exceeding 200° F, it is not
  classed as a flammable liquid by the National Code and would not have
  the same stringent handling requirements of RP-1 fuels. Therefore, the
  RJ-1 fuel can be used in the laboratories or in GSE with the same
  precautions as taken with MIL-H-5606

GSE = Ground Support Equipment
Source - The December 1963 issue of Hydraulics and Pneumatics magazine


Q:

Worklight server - Error 500: Could not find required filter class - com.worklight.core.auth.impl.AuthenticationFilter.class

I'm using worklight 6.1 for my mobile app project. My problem is, I got this error message when I try to upload war file into worklight server. I already install worklight server into my websphere.
Error 500: javax.servlet.ServletException: Filter [authenticationFilter]: Could not find required filter class - com.worklight.core.auth.impl.AuthenticationFilter.class

These are steps for uploading war file into worklight server.
1.Build project_name.war file from IBM Worklight Studio v6.1.

2.Deploy the .war file to IBM Websphere Integrated Solutions Console v8.5.5.0.

3.Open the WebSphere enterprise application and click install.

4.Choose the project.war file from the worklight project directory.

5.Click on next button for fast path.

6.Click on next button.

7.Choose the server 1.

8.Choose on the target JNDI.

9.Set the Virtual Host to default_host.

10.Set the context root.

11.Click on finish button.

12.Save directly to master configuration.

13.Start the application.

14.Open the server URL to get into the wroklight server to deploy application, adapter and etc, but failed to open the server URL with this error and the error log as below.

[3/6/14 10:18:50:442 MYT] 0000009e webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor]: java.lang.ClassNotFoundException: class java.lang.ClassNotFoundException: com.worklight.core.auth.impl.AuthenticationFilter
at java.beans.Beans.instantiate(Beans.java:195)
at java.beans.Beans.instantiate(Beans.java:80)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager._loadFilter(WebAppFilterManager.java:533)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.loadFilter(WebAppFilterManager.java:475)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterInstanceWrapper(WebAppFilterManager.java:308)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterChain(WebAppFilterManager.java:380)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:892)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)

My latest error message on 10 March 2014
Error 500: javax.servlet.ServletException: Worklight Console initialization failed.Logged Exception: java.lang.RuntimeException: FWLSE0206E: The project /rmbp failed to initialize, because the project database schema for data source jdbc:db2://192.168.1.80:50001/APPCNTR is from version N/A, which is not supported by the server from version 6.1.0.00.20131126-0630. Use the Worklight ant tasks to upgrade the project database schema.

A:

You may want to look at this similar post for suggestions:
IBM Worklight 6.0 - Worklight Console does not show up after installing WL 6.0 server on Liberty profile - Error 500
Importantly "you need to make sure that your worklight-jee-library.jar is in the application classloader." Like Idan suggested above you can easily use the ant scripts we provide in order to accomplish this in a more automated fashion:
https://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/index.jsp?topic=%2Fcom.ibm.worklight.deploy.doc%2Fdevref%2Ft_transporting_apps_and_adapters.html


Q:

SQL Server 2008 :: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

I have [ReconcileUserInformationComputed] trigger on Userinformation table
Userinformation table has below rows
    [ID] ,[CompanyID] ,[Status] ,[FirstName] ,[LastName]
UserinformationComputed table has below rows
    [id] ,[CompanyID] ,[law_id] ,[Status] ,[FirstName] ,[LastName]
Below is my trigger
USE [einvoice]
GO
/****** Object:  Trigger [dbo].[ReconcileUserInformationComputed]    Script Date:    08/27/2014 10:53:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[ReconcileUserInformationComputed] ON [dbo].[UserInformation] AFTER INSERT,DELETE,UPDATE
AS
    IF @@ROWCOUNT = 0 -- exit trigger when zero records affected
    BEGIN
        RETURN
    END
    SET NOCOUNT ON;
    IF EXISTS (SELECT * FROM INSERTED)
    BEGIN
        IF EXISTS (SELECT * FROM DELETED)
        BEGIN
            --UPDATE
                UPDATE [dbo].[UserInformationComputed]
                SET -- use new values from inserted
                CompanyID = (SELECT CompanyID from inserted),
                law_id = (SELECT ID FROM inserted),
                Status = (SELECT Status FROM inserted),
                FirstName = (SELECT FirstName FROM inserted),
                LastName = (SELECT LastName FROM inserted),
    WHERE  -- use original values from deleted
                law_id = (SELECT ID FROM deleted)
    END
    ELSE
    BEGIN
        --INSERT
      INSERT INTO [dbo].[UserInformationComputed] (CompanyID,law_id,Status,FirstName,LastName)
     SELECT CompanyID,id,Status,FirstName,LastName) FROM inserted
   END
END
ELSE IF EXISTS(SELECT * FROM DELETED)
BEGIN
    --DELETE
    DELETE FROM [dbo].[UserInformationComputed]
    WHERE law_id = (SELECT id FROM deleted)
END

when try to update multiple users on Userinformation am getting
below error
Msg 512, Level 16, State 1, Procedure ReconcileUserInformationComputed, Line 16
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I made the changes as per the answer it worked for the above trigger but same changes didnt work for another trigger
ALTER TRIGGER [dbo].[ReconcileCrossRefComputed] ON [dbo].[CrossRef] AFTER INSERT, UPDATE, DELETE
AS
    IF @@ROWCOUNT = 0 -- exit trigger when zero records affected
    BEGIN
       RETURN
    END
    SET NOCOUNT ON;
    IF EXISTS (SELECT * FROM INSERTED)
    BEGIN
        IF EXISTS (SELECT * FROM DELETED)
        BEGIN
            --UPDATE
            UPDATE [dbo].[CrossRefComputed]
            SET -- use new values from inserted
            SenderId = inserted.SenderId,
            ReceiverId = inserted.ReceiverId,
            ForeignRef = inserted.ForeignRef,
            PolicyID = inserted.PolicyID,
        From inserted
        WHERE -- use original values from deleted
        [CrossRefComputed].SenderId = inserted.SenderId
        AND [CrossRefComputed].ReceiverId = inserted.ReceiverId
    END
    ELSE
    BEGIN
        --INSERT
        INSERT INTO [dbo].[CrossRefComputed] (SenderId, ReceiverId, ForeignRef, PolicyID)
        SELECT SenderId, ReceiverId, Effective, PolicyID FROM inserted
    END
END
ELSE IF EXISTS(SELECT * FROM DELETED)
BEGIN
    --DELETE
    DELETE FROM [dbo].[CrossRefComputed]
    WHERE SenderId in (SELECT SenderId FROM deleted)
    AND ReceiverId in (SELECT ReceiverId FROM deleted)
END

COuld anyone please help me how to fix the procedure to handle updating multiple records?

A:

Be aware that an UPDATE or a DELETE can affect more than one record and your trigger will have to deal with them at once, in this case your "inserted" or "deleted" table will have more than one record.
You will have to use a join in your DML. Something like this:
UPDATE [dbo].[UserInformationComputed]
                SET
                CompanyID = inserted.CompanyID,
                law_id = inserted.ID,
                Status = inserted.Status,
                FirstName = inserted.FirstName,
                LastName = inserted.LastName
            from inserted
    WHERE
                UserInformationComputed.law_id = inserted.ID

I haven't perfectly understood your UPDATE logic, so you'll have to adapt my code.
In your DELETE command you may have just to change "=" to "in":
DELETE FROM [dbo].[UserInformationComputed]
    WHERE law_id in (SELECT id FROM deleted)

Take a look at this:
http://msdn.microsoft.com/en-us/library/ms190752.aspx


Q:

Working with Php-Java Bridge

I am having trouble setting up the Php-Java Bridge setup properly.
I will explain what I have done.

My site is in pure php
For our payment transaction process we need to set up a php-java bridge
I followed this link to setup the bridge PHP-JAVA BRIDGE INSTALATION.
Here I learned that I need to have a private jvm to install the bridge.
So 1st i installed apache-tomcat-6.0.14 in Private JVM using my c-panel. After instalation it asked me to Map a domain to private JVM. So I mapped my domain example.com (which is the only option available) to it.
Then it asked to enable a traffic redirection from Apache web server to my Java application server (there was a check box and i clicked it)
Finally it asked me to deploy the WAR File (JavaBridge.WAR was my file) and everthing seems fine
Now when i go to http://example.com/JavaBridge/ I could see the javabridge examples and it works fine.

SO FAR SO GOOD
Now my problem starts here when I try to access a java class file from php. A sample test.php is what I create and put the following code into it.
  <?php
        require_once("http://example.com:portnumber/JavaBridge/java/Java.inc");
        $System = java("java.lang.System");
        echo $System->getProperties(); //This Part echo's correctly and shows the data so it means i can access Java.inc Correctly

        $path_e24class = getcwd(). '/e24PaymentPipe.class'; //This part fails both test.php and java class file e24PaymentPipe.class are in the same directory in publich_html folder
        java_require($path_e24class);
        $pipe = new Java("e24PaymentPipe");
        $pipe->setAction("1");
?>

My site contents reside in the public_html folder and the WAR file are deployed in private jvm.
These are the error message am getting.
  1) Warning: java_require() not supported anymore. Please use tomcat or jee hot deployment instead
  Fatal error: Uncaught [[o:Exception]:"java.lang.Exception: CreateInstance failed: new e24PaymentPipe. Cause: java.lang.ClassNotFoundException: e24PaymentPipe VM:  1.6.0_22@http://java.sun.com/" at: #-10
 org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358) #-9
 org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204) #-8
 java.lang.Class.forName0(Native Method) #-7
 java.lang.Class.forName(Class.java:247) #-6
 php.java.bridge.Util.classForName(Util.java:1518) #-5
 php.java.bridge.JavaBridge.CreateObject(JavaBridge.java:445) #-4
 php.java.bridge.Request.handleRequest(Request.java:458) #-3
 php.java.bridge.Request.handleRequests(Request.java:500) #-2
 php.java.bridge.http.ContextRunner.run(ContextRunner.java:145) #-1
 php.java.bridge.ThreadPool$Delegate.run(ThreadPool.java:60) #0
 http://example.com:portnumber/JavaBridge/java/Java.inc(232): java_ThrowExceptionProxyFactory->getProxy(3, 'java.util.Prope...', 'T', false) #1

Finally I don't know much about the java. So am stuck here not knowing what to do.

A:

Here is a great step by step tutorial you can follow, which shows everything required! It is a little old (2007) but helped me a while ago.
There is also another option. You can install Apache Tomcat and deploy your war there. You can have even multiple tomcat instances simultaneously with your httpd running at the same time on the same machine, as long as you respect the port settings. You can even front them with Apache httpd.


Q:

not saving child entity

In a spring mvc project using hibernate and jpa, I am have a person entity, and a role entity.  Each person can have many roles, but each role can only have one person.  How can I save a new role for an existing person?
I have read many postings on this.  If I try to save the new role, I get an error about not being able to save a detached entity.  But if I try to save the existing person, the role does not get saved.  I read this posting suggesting that the hibernate annotations should be moved to the getters, but when I do that, I get a hibernate mapping error referencing an unknown property.  And this posting says the resolution of the new error is to move the annotations back to the getters, without mentioning that results in the detached entity error.  The various stack overflow questions thus seem to point in a circle.  So how can I fix my code to actually save the new child entity?
Here is the Person:
@Entity(name = "RimPerson")
@Table(name = "rim_person")
public class RimPerson {

    @Id
    @Column(name="hppid")
    @GenericGenerator(name = "generator", strategy = "native")
    @GeneratedValue(generator = "generator")
    private Long hppid;

    @OneToMany(targetEntity = RimRole.class, cascade = {CascadeType.ALL
    }, fetch = FetchType.EAGER)
    @JoinColumn(name = "player_rimperson_HJID")
    private List<RimRole> playedRoles;

    //other properties and getters and setters
}

Role is:
@Entity(name = "RimRole")
@Table(name = "rim_role")
public class RimRole {

    @Id
    @Column(name="hppid")
    @GenericGenerator(name = "generator", strategy = "native")
    @GeneratedValue(generator = "generator")
    private Long hppid;

    @ManyToOne(targetEntity = RimPerson.class, cascade = {CascadeType.ALL
    }, fetch = FetchType.LAZY)
    @JoinColumn(name = "player_rimperson_HJID", nullable=true)
    private RimPerson player;

    //other stuff and getters and setters

}

Here is the JPQL in the repository layer:
@Override
public void saveRIMPerson(RimPerson myperson) throws DataAccessException{
    if (myperson.getHppid() == null) {this.em.persist(myperson);}
    else {this.em.merge(myperson);}
}

The complete code for the relevant classes can be found at this link.

A:

You have a bi-directional one-to-many relationship between entities RimPerson and RimRole. So you need to tell hibernate which is the owner of association using the mappedBy attribute, in case of one-to-many relationship the many side is considered as owner of association, so in RimPerson the mapping should be like this:
 @OneToMany(targetEntity = RimRole.class, mappedBy="player", cascade = {CascadeType.ALL
    }, fetch = FetchType.EAGER)
    private List<RimRole> playedRoles;

Note that we have to remove the @JoinColumn annotation from here. Also the value of mappedBy attribute should match with the property name that you have defined in RimRole which is player.
Now for a bi-directional association you need to set the properties from both sides of entities, this means:
rimPerson.setPlayedRoles(playedRoles);
rimRole.setPlayer(player);

Try to update your code with these changes and run the application, this should fix the issue.


Q:

What if a white light with all the colours of the same phase is produced As a white (LASER)?

What would that kind of white light be useful if is it possible to exist

A:

What would that kind of white light be useful if is it possible to exist

In this link the uses are outlined:

While this first proof-of-concept is important, significant
  obstacles remain to make such white lasers applicable
  for real-life lighting or display applications, says the
  researchers. One of crucial next steps is to achieve
  similar white lasers under the drive of a battery. For
  the present demonstration, the researchers had to use
  a laser light to pump electrons to emit light. This
  experimental effort demonstrates the key first material
  requirement and is expected to lay the groundwork
  ultimately for white lasers under electrical operation

And from here:

A white-light laser has the potential to replace white LEDs in
  lighting, displays, sensing and telecom, with higher energy
  conversion  efficiencies  and  higher  output  powers.


Q:

Download Attachment file using Post in c#

I am trying to download a xlsx-attachment using a post-request but don't have a clue how to recieve the xlsx file. I found several different solutions which used a get-request which is not applicable in this case since i have to send data to the server which creates the file specificqally to the sent filters.
The following is the current situation:
1. I send a Post request with several Parameters
2. The server generates a xlsx file based on the parameters of the post request
3. I receive the data (but i dont know how to obtain the xlsx out of the data)
The data has to be somewhere as shown in the screenshot below but neigther in the response header, nor in the paramenters or the response content I can find data which could be a file.

This is the Header of the response:
Request URL:https://www.example.com/en/list.xlsx
Request Method:POST
Status Code:200
Remote Address:104.25.95.108:443
Referrer Policy:no-referrer-when-downgrade

Response Headers
cache-control:max-age=0, private, no-store, no-cache, must-revalidate
cf-ray:38a32289090a26d8-FRA
content-disposition:attachment; filename="secondary.xlsx"
content-length:2017481
content-type:application/vnd.openxmlformats
officedocument.spreadsheetml.sheet; name=secondary.xlsx
date:Sun, 06 Aug 2017 15:47:40 GMT
expires:Sun, 06 Aug 2017 15:47:28 GMT
pragma:public
server:cloudflare-nginx
set-cookie:alive=1; expires=Sun, 06-Aug-2017 17:47:40 GMT; Max-Age=7200; path=/
status:200
strict-transport-security:max-age=63072000
x-content-type-options:nosniff
x-content-type-options:nosniff
x-frame-options:sameorigin
x-frame-options:DENY

this is my current code:
public static string POST(string extendURI, IEnumerable<KeyValuePair<string, string>> values)
    {
        var content = new FormUrlEncodedContent(values);
        var response = GlobalVar.client.PostAsync(GlobalVar.baseURI + extendURI, content).Result;
        string responseString = response.Content.ReadAsStringAsync().Result;
        return responseString;
    }

EDIT:
Solution: get the system.io.stream and write to file
public static string Download_XML(string extendURI, IEnumerable<KeyValuePair<string, string>> values)
    {
        var content = new FormUrlEncodedContent(values);
        var response = GlobalVar.client.PostAsync(GlobalVar.mintosURI + extendURI, content).Result;

        string responseString = response.Content.ReadAsStreamAsync().Result.ToString();
        Stream stream = response.Content.ReadAsStreamAsync().Result;
        using (FileStream file = new FileStream("testfile.xlsx", FileMode.Create, System.IO.FileAccess.Write))
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
            file.Write(bytes, 0, bytes.Length);
            stream.Close();
        }
        //string responseString = response.Result.Content.ReadAsStringAsync().ToString();
        return responseString;
    }

A:

Dont forget to safe your code against network failures
public static void Download_File_Post(string extendURI, IEnumerable<KeyValuePair<string, string>> values)
{
    //create post parameters
    var content = new FormUrlEncodedContent(values);
    var response = GlobalVar.client.PostAsync(GlobalVar.baseURI + extendURI, content).Result;

    Stream stream = response.Content.ReadAsStreamAsync().Result;
        using (FileStream file = new FileStream("testfile.xlsx", FileMode.Create, System.IO.FileAccess.Write))
    {
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, (int)stream.Length);
        file.Write(bytes, 0, bytes.Length);
        stream.Close();
    }
}


Q:

Microsoft Poor Documentation on Azure: TableOperation.Merge Method

I am a newbie in Azure so I read the Microsoft TableOperation.Merge Method.

Creates a new table operation that merges the contents of the given
  entity with the existing entity in a table.

That is all... Now, what should I understand from the "merge" concept? How exactly this Merge happens.
Say I have
Body {PK: b, RK: 1, LeftHand: null, RightHand: 1000, LeftLeg: ll} >
Body {PK: b, RK: 1, LeftHand: 9999, RightHand: null, Head: h}

What happens with empty/null values?
What happens if the item is not found?
What kind of exceptions should I expect?
What is the difference between InsertOrMerge and Merge?

How can I guess ?

A:

Merge operation actually creates a superset. To put it simply:

If old entity doesn't have an attribute and the new one does: The resulting entity will have that new attribute.
If old entity has an attribute and the new one does not: That attribute's value will not be changed. It will be the same as that of the old value.
If old entity has an attribute and the new one also has that attribute: The resulting entity will replace the attribute value.

So in your example:
Old Entity:
{PK: b, RK: 1, LeftHand: null, RightHand: 1000, LeftLeg: ll}

New Entity:
{PK: b, RK: 1, LeftHand: 9999, RightHand: null, Head: h}

Entity After Merge Operation:
{PK: b, RK: 1, LeftHand: 9999, RightHand: 1000, LeftLeg: 11, Head: h}


Q:

Fragment cannot be converted

i want to create an instance of my fragment in parent activity but it show this error :
Error:(16, 81) error: incompatible types: Fragment cannot be converted to TextFragment
my code:
TextFragment frag =(TextFragment)getFragmentManager().findFragmentById(R.id.textFragment);

TextFragment code:
public class TextFragment extends Fragment{

private long workoutId;

public TextFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_text, container, false);
}

public void setWorkoutId(long workoutId) {
    this.workoutId = workoutId;
}

}

A:

i solve it.
in my TextFragment i import android.support.v4.app.Fragment and in my MainActivity
import android.app.Fragment If both must be the same.


Q:

jquery webservice login

I've been trying to get this working for a good amount of time but I can't seem
to get my head around it.
I'm trying to login using jquery mobile calling an ASP.net webservice.
The webservice is working normally and can be used.
When using the debugger web page it results like this: (true)
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<boolean xmlns="http://tempuri.org/">true</boolean>

I don't believe there's something wrong with my service so here's my page code:

    <title></title>

    <link href="res/js/mobile/jquery.mobile-1.3.0.min.css" rel="stylesheet" type="text/css" />

Login

    <form id="login_form" name="login_form" data-ajax="false">
            <input type="text" name="usr" id="usr" value="" placeholder="user"/>
            <input type="password" name="psw" id="psw" value="" placeholder="password"/>
            <input type="submit" value="Login" id="submit" name="login"/>
            <input type="checkbox" name="remember_me" id="remember_me" value="checked_remember"/>Remember me!
        </form>

Footer

Webservice code:
Imports connection

Imports System.Data

Imports System.Web
Imports System.Web.Script
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports System.Web.Script.Serialization

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(Name:="services", ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class services
    Inherits System.Web.Services.WebService

    Public connection As New connection

    <WebMethod()> _
    <SoapDocumentMethod(Binding:="services")> _
    <SoapHeader("connection")> _
    Public Function Execute(sql As String, type As Operation) As Result

        Dim r As New Result

        Select Case type
            Case Operation.SelectMultipleRows

                Try
                    r.Data = connection.Execute(sql, type)
                Catch ex As Exception
                    r.ErrorMessage = ex.Message
                    r.SQL = sql
                End Try

        End Select

        Return r

    End Function

    <WebMethod()> _
    <SoapDocumentMethod(Binding:="services")> _
    <SoapHeader("connection")> _
    Public Function Login(user As String, password As String) As Boolean

        Return connection.Login(user, password)

    End Function
End Class

I get an alert "error" but I don't know why...
I've put the webservice in debug and it runs through fine but it seems
like the jquery post is getting error before the service has being processed..?
Maybe I'm doing something wrong here?
Please help me!
Thx
Stanny

A:

I managed to solve this by myself by redesigning. Question is obsolete.


Q:

Expected output is returned but still wrong?

Let's say I am trying to solve this problem:
https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
I wrote this code:

function breakingRecords(arr) {
    let n = arr.length;
    let best = 0;
    let worst = 100000000; // 10^8 (constraints :. cannot get higher)
    let rec1 = 0; // times broken best
    let rec2 = 0; // times broken worst
    for (let i = 0; i < n; i++) {
        if (arr[i] > best) {
            best = arr[i];
            if (i != 0) {
                rec1++;
            }
        } else if (arr[i] < worst) {
            if (i != 0) {
                worst = arr[i];
                rec2++;
            }
        }
    }
    return [rec2, rec1];
}

//And for one test case, I say:

console.log(breakingRecords([3, 4, 21, 36, 10, 28, 35, 5, 24, 42]))

The output is [4, 2], which is equal to the expected output (the expected output is 4 2, but they add the space themselves). But, when I enter this code, my output is shown as 4 0. I test it in my browser and I still get [4, 2].

Can someone explain why this is so, and what I can do to fix it? Refreshing doesn't work, and neither does closing and reopening.

A:

Actually, your code was wrong. The expected results were 4 0, but your code returned 4 2.
That was because of the first iteration. The first match's result is both the current best and worst but doesn't count into the score. Your code set it only as the best score (because of the else if), but not as the worst.
So, let's treat this as a special case, and shift the first element out of the array (we can do that safely, as constraints list that the array must contain at least 1 element):

function breakingRecords(arr) {
    let best;
    let worst;
    best = worst = arr.shift() //Get and remove the first element
    let n = arr.length;
    let recBest = 0;  //Use more descriptive names here
    let recWorst = 0; //...and here as well
    for (let i = 0; i < n; i++) {
        if (arr[i] > best) {
            best = arr[i];
            recBest++;
        } else if (arr[i] < worst) {
            worst = arr[i];
            recWorst++;
        }
    }
    return [recBest, recWorst];
}

//And for one test case, I say:

console.log(breakingRecords([3, 4, 21, 36, 10, 28, 35, 5, 24, 42])) //[4, 0]


Q:

When should you use a mutex over a channel?

For the past few weeks I've been wrestling with one (not-so) simple question:
When is it best to use a sync.Mutex and, conversely, when is it best use a chan?
It seems that for a lot of problems either strategy is interchangeable with the other - and that's just the problem!
Take this video found in the Golang documentation. Below, I've taken the liberty to dictate the code in the playground and also translate it to a sync.Mutex equivalent.
Is there a certain problem - encountered in the real world - that warrants the use of one other?
Notes:

I am a huge fan of this use of chan and struggle to think of a more elegant implementation using sync.Mutex.
It's worth noting that the chan implementation does more work in the same time (reaches 12)*

Playgrounds:

Chan implementation
Mutex implementation

Ping/pong with chan:
package main

import (
    "fmt"
    "time"
)

type Ball struct { hits int }

func main() {
    table := make(chan *Ball)
    go player("ping", table)
    go player("pong", table)

    table <- new(Ball)
    time.Sleep(1 * time.Second)
    <-table
}

func player(name string, table chan *Ball) {
    for {
        ball := <-table
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        table <- ball
    }
}

Ping/pong with sync.Mutex:
package main

import (
    "fmt"
    "time"
    "sync"
)

type Ball struct { hits int }

var m =  sync.Mutex{}

func main() {
    ball := new(Ball)
    go player("ping", ball)
    go player("pong", ball)

    time.Sleep(1 * time.Second)
}

func player(name string, ball *Ball) {
    for {
        m.Lock()
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        m.Unlock()

    }
}

A:

In most cases prefer channels, in some sync.Mutex:
Use channels if:
 - transferring ownership (transferring data itself not a pointer to data)
 - coordination and synchronization
Use primitives if:
 - guarding internal state of a struct
 - performance critical (algorithm and use case dependent, not a general rule)
Note: For concurrent safe code using primitives needs more care.

Micro-benchmark
To make it clear, imagine we need a one second counter, so in the following examples we count for a second then print the counter value to see how fast it counts:
No |         Count |       Method
------------------------------------------------------
 1 |     17_729_027 | Using sync.RWMutex for increment
 2 |     12_180_741 | Using channel for increment
 3 |    106_743_095 | Using channel for timer
 4 |    104_178_671 | Using time.AfterFunc and channel sync

Note: go version go1.13.5 linux/amd64

Codes:
1 - Using sync.RWMutex for increment:
package main

import (
    "sync"
    "time"
)

func main() {
    var i rwm
    go func() {
        for {
            i.inc() // free running counter
        }
    }()
    time.Sleep(1 * time.Second)
    println(i.read()) // sampling the counter
}

type rwm struct {
    sync.RWMutex
    i int
}

func (l *rwm) inc() {
    l.Lock()
    defer l.Unlock()
    l.i++
}
func (l *rwm) read() int {
    l.RLock()
    defer l.RUnlock()
    return l.i
}

2 - Using channel for increment:
package main

import (
    "time"
)

func main() {
    ch := make(chan int, 1)
    ch <- 1
    timeout := time.NewTimer(1 * time.Second)
loop:
    for {
        select {
        case <-timeout.C:
            timeout.Stop()
            break loop
        default:
            ch <- 1 + <-ch
        }
    }

    println(<-ch)
}

3 - Using channel for timer:
package main

import "time"

func main() {
    ch := make(chan int)
    go func() {
        timeout := time.NewTimer(1 * time.Second)
        defer timeout.Stop()
        i := 1
        for {
            select {
            case <-timeout.C:
                ch <- i
                return
            default:
                i++
            }
        }
    }()

    println(<-ch)
}

4 - Using time.AfterFunc and channel sync:
package main

import (
    "fmt"
    "time"
)

func main() {
    d := 1 * time.Second
    i := uint64(0)
    ch := make(chan struct{})

    time.AfterFunc(d, func() {
        close(ch)
    })

loop:
    for {
        select {
        case <-ch:
            break loop
        default:
            i++
        }
    }

    fmt.Println(i) // 104_178_671
}


Q:

R Shinyapp works locally but not on Shinyapp.io server

I am trying to make a shinyapp which let users upload a certain format of file. After uploading the file, the shinyapp will automatically plot some table and charts using dplyr and rCharts.
It works well when I run it locally using “Run App”. However, when I publish to shinyapp.io, I got this error:
path1="": No such file or directory
After searching on the internet, I haven’t found any solution to solve this problem. Could anyone help me on what the possible reason causing this issue?
Here is my code and my sessionInfo().(It's a little bit long and messy)
https://github.com/johnnychiuchiu/Cheetah_ShinyApp/blob/master/server.r
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.4 (Yosemite)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods
[7] base

other attached packages:
[1] stringr_1.0.0 dplyr_0.4.2   rCharts_0.4.5 shiny_0.12.2

loaded via a namespace (and not attached):
[1] Rcpp_0.12.1       lattice_0.20-33   assertthat_0.1
[4] digest_0.6.8      mime_0.3          grid_3.2.2
[7] plyr_1.8.3        R6_2.1.0          DBI_0.3.1
[10] xtable_1.7-4      jsonlite_0.9.16   magrittr_1.5
[13] stringi_0.5-5     lazyeval_0.1.10   rstudioapi_0.3.1
[16] whisker_0.3-2     RJSONIO_1.3-0     tools_3.2.2
[19] parallel_3.2.2    httpuv_1.3.3      yaml_2.1.13
[22] rsconnect_0.4.1.4 htmltools_0.2.6

A:

The "h" in "Highcharts" needs to be lowercase, e.g.:
showOutput("h5", "highcharts"),

If that doesn't work: For the deployment, showOutput needs you to detail the path to your rcharts-lilbrary (at least in my case, for whatever reason ^^).
I had a problem which was very similar to yours. Here's my solution:
"ERROR: path[1]="": No such file or directory" when publishing Parallel Coordinates Chart with Shiny