text:
Q: The TFLite Android app throws Fatal Error: "Buffer Overflow Exception" I recerntly tried to build an Object Detection Android App using TFLite model. I built my own custom model (a Keras Model in HDF5 format) and converted the model succesfully into a custom TFLite model using the following command:
tflite_convert --keras_model_file=detect.h5 --output_file=detect.tflite --output_format=TFLITE --input_shapes=1,300,300,3 --input_arrays=normalized_input_image_tensor --output_arrays='TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3' --inference_type=QUANTIZED_UINT8 --mean_values=128 --std_dev_values=127 --change_concat_input_ranges=false --allow_custom_ops

I further added the associated MetaData to this particular model using this code:
import tensorflow as tf from tflite_support import metadata as _metadata

populator = _metadata.MetadataPopulator.with_model_file("detect.tflite") populator.load_associated_files(["labelmap.txt"]) populator.populate()

I then configured this model in the Android Package Example by tensorflow and made some tweaks to the Build.gradle file, DetectorActivity.java and TFLiteObjectDetectionAPIModel.java, respectively. I also made some UI changes according to what and how I needed it to look like. Additionally, I had to change the 'numBytesPerChannel'
value for Float model from '4' to '3' since I was getting an error like this:
Cannot convert between a TensorFlowLite buffer with XYZ bytes and a ByteBuffer with ABC bytes

The build is successful yet the debugger throws me a fatal exception of "BufferOverFlowError".
11/13 14:57:02: Launching 'app' on Physical Device. Install successfully finished in 16 s 851 ms. $ adb shell am start -n "org.tensorflow.lite.examples.detection/org.tensorflow.lite.examples.detection.DetectorActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D Waiting for application to come online: org.tensorflow.lite.examples.detection.test | org.tensorflow.lite.examples.detection Waiting for application to come online: org.tensorflow.lite.examples.detection.test | org.tensorflow.lite.examples.detection Connected to process 22667 on device 'samsung-sm_m315f-RZ8N50B0M5K'. Waiting for application to come online: org.tensorflow.lite.examples.detection.test | org.tensorflow.lite.examples.detection Connecting to org.tensorflow.lite.examples.detection Connected to the target VM, address: 'localhost:46069', transport: 'socket' Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. I/mples.detectio: Late-enabling -Xcheck:jni E/mples.detectio: Unknown bits set in runtime_flags: 0x8000 D/ActivityThread: setConscryptValidator setConscryptValidator - put W/ActivityThread: Application org.tensorflow.lite.examples.detection is waiting for the debugger on port 8100... I/System.out: Sending WAIT chunk I/System.out: Debugger has connected waiting for debugger to settle... I/chatty: uid=10379(org.tensorflow.lite.examples.detection) identical 1 line I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/chatty: uid=10379(org.tensorflow.lite.examples.detection) identical 2 lines I/System.out: waiting for debugger to settle... I/System.out: waiting for debugger to settle... I/System.out: debugger has settled (1478) I/mples.detectio: Waiting for a blocking GC ClassLinker I/mples.detectio: WaitForGcToComplete blocked ClassLinker on ClassLinker for 7.502ms D/tensorflow: CameraActivity: onCreate org.tensorflow.lite.examples.detection.DetectorActivity@4d5b875 D/PhoneWindow: forceLight changed to true [] from com.android.internal.policy.PhoneWindow.updateForceLightNavigationBar:4274 com.android.internal.policy.DecorView.updateColorViews:1547 com.android.internal.policy.PhoneWindow.dispatchWindowAttributesChanged:3252 android.view.Window.setFlags:1153 com.android.internal.policy.PhoneWindow.generateLayout:2474 I/MultiWindowDecorSupport: [INFO] isPopOver = false I/MultiWindowDecorSupport: updateCaptionType >> DecorView@59812d[], isFloating: false, isApplication: true, hasWindowDecorCaption: false, hasWindowControllerCallback: true D/MultiWindowDecorSupport: setCaptionType = 0, DecorView = DecorView@59812d[] W/mples.detectio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) W/mples.detectio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) I/CameraManagerGlobal: Connecting to camera service D/VendorTagDescriptor: addVendorDescriptor: vendor tag id 3854507339 added I/CameraManagerGlobal: Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client com.snapchat.android API Level 1 I/CameraManagerGlobal: Camera 1 facing CAMERA_FACING_FRONT state now CAMERA_STATE_CLOSED for client com.dolby.dolby234 API Level 2 I/CameraManagerGlobal: Camera 2 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client com.whatsapp API Level 1 I/CameraManagerGlobal: Camera 20 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client android.system API Level 2 I/CameraManagerGlobal: Camera 23 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client android.system API Level 2 I/CameraManagerGlobal: Camera 3 facing CAMERA_FACING_FRONT state now CAMERA_STATE_CLOSED for client com.sec.android.app.camera API Level 2 I/CameraManagerGlobal: Camera 4 facing CAMERA_FACING_FRONT state now CAMERA_STATE_CLOSED for client vendor.client.pid<4503> API Level 2 I/CameraManagerGlobal: Camera 50 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client com.sec.android.app.camera API Level 2 I/CameraManagerGlobal: Camera 52 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client android.system API Level 2 I/CameraManagerGlobal: Camera 54 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for client android.system API Level 2 I/tensorflow: CameraActivity: Camera API lv2?: false D/tensorflow: CameraActivity: onStart org.tensorflow.lite.examples.detection.DetectorActivity@4d5b875 D/tensorflow: CameraActivity: onResume org.tensorflow.lite.examples.detection.DetectorActivity@4d5b875 I/ViewRootImpl@a101c3c[DetectorActivity]: setView = com.android.internal.policy.DecorView@59812d TM=true MM=false I/ViewRootImpl@a101c3c[DetectorActivity]: Relayout returned: old=(0,0,1080,2340) new=(0,0,1080,2340) req=(1080,2340)0 dur=31 res=0x7 s={true 532883185664} ch=true D/OpenGLRenderer: createReliableSurface : 0x7c1211ecc0(0x7c12502000) D/OpenGLRenderer: makeCurrent EglSurface : 0x0 -> 0x0 I/mali_winsys: new_window_surface() [1080x2340] return: 0x3000 D/OpenGLRenderer: eglCreateWindowSurface : 0x7c120c3600 I/CameraManagerGlobal: Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_OPEN for client org.tensorflow.lite.examples.detection API Level 1 I/tensorflow: CameraConnectionFragment: Desired size: 640x480, min size: 480x480 I/tensorflow: CameraConnectionFragment: Valid preview sizes: [1920x1080, 1440x1080, 1280x720, 1088x1088, 1024x768, 960x720, 720x720, 720x480, 640x480] I/tensorflow: CameraConnectionFragment: Rejected preview sizes: [800x450, 640x360, 352x288, 320x240, 256x144, 176x144] CameraConnectionFragment: Exact size match found. W/Gralloc3: mapper 3.x is not supported I/gralloc: Arm Module v1.0 W/Gralloc3: allocator 3.x is not supported D/OpenGLRenderer: makeCurrent EglSurface : 0x0 -> 0x7c120c3600 I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread. I/ViewRootImpl@a101c3c[DetectorActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@59812d[DetectorActivity] D/InputMethodManager: getNavigationBarColor() -855310 D/InputMethodManager: prepareNavigationBarInfo() DecorView@59812d[DetectorActivity] D/InputMethodManager: getNavigationBarColor() -855310 V/InputMethodManager: Starting input: tba=org.tensorflow.lite.examples.detection ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus I/ViewRootImpl@a101c3c[DetectorActivity]: MSG_RESIZED: frame=(0,0,1080,2340) ci=(0,83,0,39) vi=(0,83,0,39) or=1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@59812d[DetectorActivity] getNavigationBarColor() -855310 V/InputMethodManager: Starting input: tba=org.tensorflow.lite.examples.detection ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/CameraManagerGlobal: Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_ACTIVE for client org.tensorflow.lite.examples.detection API Level 1 W/TFLiteObjectDetectionAPIModelWithInterpreter: cow1 cow2 cow3 cow4 W/TFLiteObjectDetectionAPIModelWithInterpreter: cow5 cow6 I/tflite: Initialized TensorFlow Lite runtime. I/tensorflow: DetectorActivity: Camera orientation relative to screen canvas: 90 I/tensorflow: DetectorActivity: Initializing at size 640x480 I/tensorflow: DetectorActivity: Preparing image 1 for detection in bg thread. W/System: A resource failed to call close. I/tensorflow: DetectorActivity: Running detection on image 1

E/AndroidRuntime: FATAL EXCEPTION: inference
Process: org.tensorflow.lite.examples.detection, PID: 22667
java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:542)
at java.nio.DirectByteBuffer.putFloat(DirectByteBuffer.java:809)
at org.tensorflow.lite.examples.detection.tflite.TFLiteObjectDetectionAPIModel.recognizeImage(TFLiteObjectDetectionAPIModel.java:187)
at org.tensorflow.lite.examples.detection.DetectorActivity$2.run(DetectorActivity.java:183)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.os.HandlerThread.run(HandlerThread.java:67)
I/Process: Sending signal. PID: 22667 SIG: 9
Disconnected from the target VM, address: 'localhost:46069', transport: 'socket'

The error suggests a change in these lines:
In TFLiteObjectDetectionAPIModel.java:
private static final float IMAGE_MEAN = 127.5f;
private static final float IMAGE_STD = 127.5f;
//...

@override
protected void addPixelValue(int pixelValue) {
imgData.putFloat((((pixelValue >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
}

In DetectorActivity.java:
@override
public void run() {
LOGGER.i("Running detection on image " + currTimestamp);
final long startTime = SystemClock.uptimeMillis();
final List<Detector.Recognition> results = detector.recognizeImage(croppedBitmap);

lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime;

Please let me know if I missed any step or did anything wrong.
P. S. - I used a dull-trained model before this and the app worked just fine, except for the fact that it showed all the boundary boxes at once with negligible changes in any detections. I am currently using a well trained model which looks like this (via netron):
TFLite Model

A: I was able to solve the error. So basically, the tflite model that I used had a highly big input size. This happened since I used a custom model (this means, the fine-tuning was random and the model was hence not compatible with the android's TFLiteObjectDetectionAPI.
Another thing here is, I accidentally used mobilenet-v2 model as a reference model to train my own model whereas the default model that the TFLiteObjectDetectionAPI uses ssd-mobilenet-v1. I don't think this has anything to do with my error but this might throw a compatibility exception and hence lead to some ambiguous errors.
Thus I used this link to train my model with custom parameters and had to make some changes in the pipeline.config file. Otherwise, the model that I've trained apparently works just fine and gives me apt results and is 70% accurate which is enough for my purpose as of now.
Thank you @Saeid, @T.K and @Alex for your help. I appreciate the structure of Tensorflow's training work-flow.
I have solved this issue right now and this was a small error when I think of it. Do let me know if there's anything else too!
Ciao!

A: I have encountered this error before as well. Usually this happens when 2 things are not correct in your code that feeds data into your model:

*

*The image size is incorrect (i.e. you are feeding a buffer larger than the one allocated as input buffer in your model)

*The data type you are feeding the data as is not correct. (i.e. the model expects uint8 but you are feeding a buffer filled with float values).
If you converted the model via the tflite_convert tool, sometimes the inputs can change types between float or int (depending on your arguments)
Is there a way for you to check if either one of these cases are happening?


text:
Q: Custom CMS or Open Source? I am building a site for my friend using PHP and MySQL (Or SQLite, I'm still debating.)  The site is aimed to sell photography online with various options.  The backend shows statistics, recent orders, etc. and allows for the client to upload images, crop them in-browser (using javascript and GD), add a watermark to the image, adjust prices, framing options, coupon codes, etc.  Upon uploading an image, the site must also resize the image, allow for a color change or preset filter, etc.  When a person buys an image on the front end, the site will be contacted using paypals IPN, an email will be sent to the buyer and administrator, and things will resume.
The front end will have the home page showing the 10 most recent uploads, 3 pages where the client can enter contextual information, and a gallery link that will show all of the images (with sorting options, such as sort by color, size, price, tag, category, etc.)
When buying an image, the user will be faced with options such as size, frame or no frame, color, signature, etc.
Given all this information, would it be easier to use a open source CMS (and which one) or design my own.  (I can design a quick system for this site in about a month or so if thats what it comes down to)
What would be the best way to get a project like this taken care of?
Thanks

A: There are a number of open source cms's out there. (Drupal, Joomla, Moodle, etc)
Why waste a month re-inventing the wheel?  We use Drupal for a lot of our sites.  With the theming capabilities, user management and data storage functionality "out-of-the-box", they can give you a big head-start.  Additionally, with the respective communities contributing modules, there is a good chance someone will have already done most of the work for you.  So, instead of spending a month coming up with a "quick" system, you could spend that month polishing a great system. :)
Some people poopoo the open source CMS's as having too steep a learning curve or for being to convoluted...  Yes, they are complicated, but my experience says it's worth it.
Up to you.

A: First of all let me advise you: do not use SQLite for such websites. It is not that this DBMS is poor (it is really great, though!), but it is not best suited for multiple users accessing your site at once. Stick to MySQL, if this is the only choice you have aside SQLite.
Second, it would be easier to use Open Source CMS. You have two popular options as top choices:

*

*WordPress and

*Drupal,

Drupal has great architecture, WordPress is easier to work with. Both of them are really powerful, both of them have countless modules available, both of them can be used to set up a small shopping site.
Take a look at them and decide on your own. But for sure using already written software will save you months (at least) and will help you benefit from the community support (updates, help in development, possible workforce in case you need it).

A: If I were in your shoes, I would shop around for an Open Source CMS that addresses at least 60% of your requirements. You didn't mention your level of coding skill, but chances are you adept enough to custom tailor any requirements the 'out of the box' code doesn't support.
Many open source applications are highly customizable, so you can safely add custom code to support your requirements without mucking up the source code. This is important so you can upgrade the CMS codebase without over-writing any of your custom code.
If needed, you can also stack an open source applciation upon a framework for even more out of the box functionality, for example, drupal can be made to use certain zend framework libraries.
You just need to have the expertise to pull in what you need from what's available and customize so it meets your requirements.

A: This is definitely a subjective question, and may be closed or moved to another venue.
As a small shop, there is every reason to use a service rather than having anyone build software, ever.  Custom software is expensive to create and maintain and you're usually better off with an online product that does about 80% of what you need.
There seem to be 100s of options searching "websites for photographers" in google.  Is there a real reason your friend needs a customized CMS?
If you decide that no online service is sufficient:
Do not design your own CMS unless no other option is possible and you have a large, ongoing budget.
While the project scope may be small today, over time your friend will want to add new features (facebook integration, flickr integration, login via retinal scan, etc).  By using open source they will be able to add these using off-the-shelf plugin code.
When you use an open source CMS, you make it possible for them to get other people to do work on it in the future.  Hiring a Drupal or Wordpress coder to do a couple days of custom work or support is no problem.  For another programmer to learn a custom CMS takes much longer and is more expensive.
You get to focus on the part of the project that is most valuable to your friend.  Not on creating the login system, building a flash uploader, or managing the payment flow.  Those things have been handled before by others.  Take advantage of that.
You gain valuable knowledge of a CMS that is widely used.  You learn how to read other's code and bend it to your will.  This will be helpful later when you have to build custom solutions.
I built and maintained a custom CMS for six years.  That company still has hundreds of clients using it.  If they could move them all to Drupal/Wordrpess, they'd be much happier.
One thing to be careful of: Make sure your friend can keep the CMS up to date.  There are constant security releases for these platforms because they are constantly under attack by script kiddies.  Attackers will find the flaws in your work too, but they won't have direct access to the code so they'll be slower about it.

A: Early this year i was involved in a very similar project, the requirements demanded i used Drupal, i was really new to the whole Drupal scene, and I must say it was a great experience, once you get past the learning curve and discover you get hooks for everything, you will get going doing your custom module that will do GD for image manipulation, I ended up using exec or something like that to use the whole ImageMagick framework, I understand your requirements are unique and different than mine, but I think Drupal will get you there faster than getting your out of the box solution.

A: Yep, I agree with everyone else. Open Source. It will save you a bunch of time. Check out Joomla! with the K2 component (CCK) I believe it will handle much of what you're describing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class Template in C++/CLI I formed class template that represent two dimensional array :
template<class T>
class Array2D {
protected:

public:
      T *data;

        const unsigned rows, cols, size;
        Array2D(unsigned r, unsigned c) : rows(r), cols(c), size(r*c) {

      data = new T[size];
        }
        ~Array2D() { delete data; }
        void setValue(unsigned row, unsigned col, T value) {
                data[(row*cols)+col] = value;
        }
        T getValue(unsigned row, unsigned col) const {
                return data[(row*cols)+col];
        }
};

And there is present one dimensional data array
array<double>^ input={20,4,6,15,7,2,1,8,9};

I have function it's inputs are class template and one dimensional data array.I set one dimensional array values to class template :
void function(Array2d<double> &x,array< double>^ input,int width,int,height)
{

double temp;
temp1=0;

double temp2;

int i,j;

// assign input array values to two dimensional array
for(i=0;i<width;i++)
for(j=0;j<height;j++)
{
{ temp2=input[temp1];
  x.setvalue(i,j,temp2);
  temp1=temp1+1;
}
}

}

After all I declared 3x3 class template:
Array2D<double>A(3,3);

I sent it to function:
function(A,input,3,3);

And I tried to print Array2D values:
double temp;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
{temp=A.getValue(i,j)

Console:Write("{0}",temp);}}

I executed this applicaiton in CLR Application in Visual Studio 2008  amd it worked .But I want to implement this code on Windows Form Application,and it gave error like these on Form Application:
error C2065: 'Array2D' : undeclared identifier
error C2065: 'A' : undeclared identifier

How can I overcome this error or where should I locate class template?
Best Regards...

A: Things to look for when your code won't compile due to an undeclared type:

*

*Have I #included the relevant header (in your case, the one containing Array2D)?  If not, the compiler won't know the definition of your type, and will think it's undeclared.

*Is the code defining the type in the same namespace as the broken code?  If not, am I referring to the type with a qualified name (via the scope resolution operator ::, e.g. std::vector)?  If not, have I used using to make the whole namespace available?

*Is the symbol I'm trying to use #defined to something else in the header but not the client code, or vice versa?  This probably isn't your problem but can happen sometimes in windows development, as many Win32 functions have ASCII and Unicode versions, and which you use depends on which #defines are set in your header files.  This is especially obnoxious when you've unwittingly shadowed a Win32 function name, e.g. a function named SendMessage.

I'd bet that you're missing a header, maybe in some code that your IDE generated for you automatically.

A: Check the namespaces of your code. Often, when I move classes from one project to another, I forget to change the namespace, which causes errors like this.

A: This line will produce undefined behaviour:
~Array2D() { delete data; }

You allocated data with new [], so you need ~Array2D() { delete [] data; }

A: As an aside, there is a lot of benefit to using the standard library containers, even in managed C++. For example, a 2D array of type T is just std::vector< std::vector< T > >. You don't need to concern yourself with memory management, or ensuring that the row+column calculations are correct. If you don't need to compile your code as native C++ then use the .NET containers if desired.


text:
Q: Deploy jar with embedded jetty with maven I have a (large) maven-web-project with many dependencies. The project runs an embedded jetty.
For some (customer related) reasons I cannot package a war to deploy it to some application server like a standalone jetty or tomcat.
Now I need to deploy the whole project with all dependencies-jars and the web-root stuff to some production-server, where I can start by command line the embedded jetty like java -jar myproject.jar.
How can I build such a package with maven. I tried maven-assembly-plugin, but I do not want to re-pack jars. (IMHO this is not a really good idea.)
I need to package some zip or tar like:
myproject.zip
  --myproject.jar
  --META-INF (with the whole classpath and may be the auto-start class)
  --libs
    --slf4j.jar
    --logback.jar
    --hibernate.jar
    --and many, many more.

Any ideas? TIA!

A: If you use Spring you can use Spring Boot which does this by default. By using Spring Boot maven plugin it will build you a uber jar containing all your dependencies and an embed tomcat or jetty.


text:
Q: How to select only certain items from a collection using Streams in Java I am trying to select only names from a collection using streams: These are the entries:
Person{id=4, name=E, color=red}]
[Person{id=0, name=A, color=blue}
Person{id=1, name=B, color=green}
Person{id=2, name=D, color=pink}
Person{id=0, name=C, color=yellow

I've tried using map, but it doesn't seem to alter the list since the function I'm mapping it to is supposed to be a getter method.
list.stream().map(p -> getter.apply(p))collect(Collectors.toList());

A: If you have getter defined for the fields of Person, you can map the names:
List<String> personNames = list.stream().map(Person::getName).collect(Collectors.toList());

A: Use .filter, like the webiste explains you, instead of .map

A: To filter say on the name, do it like this.
Person{id=4, name=E, color=red}]
[Person{id=0, name=A, color=blue}
Person{id=1, name=B, color=green}
Person{id=2, name=D, color=pink}
Person{id=0, name=C, color=yellow

Assuming a List<Person>
To get all the Person objects with a specific name
List<Person> specific = list
                   .stream()
                   .filter(person->person.name.equals("E"))
                   .collect(Collectors.toList());

To get just the names
List<String> names = list
               .stream()
               .map(person->person.name)
               .collect(Collectors.toList());

A: Here is a generic code, that uses filter:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Person {
  int id;
  String name;
  String color;

  @Override
  public String toString() {
    // TODO Auto-generated method stub
    return id + ":" + name + ":" + color;
  }
  public Person(int id, String name, String color) {
    super();
    this.id = id;
    this.name = name;
    this.color = color;
  }
  public int getId() {return id;}
  public void setId(int id) {this.id = id;}
  public String getName() {return name;}
  public void setName(String name) {this.name = name;}
  public String getColor() {return color;}
  public void setColor(String color) {this.color = color;}
}

public class Test {

  public static void main(String[] args) {
    List<Person> list = new ArrayList<Person>();
    list.add(new Person(1,"Ana","red"));
    list.add(new Person(2,"tna","orange"));
    list.add(new Person(3,"Hna","green"));
    list.add(new Person(4,"Ana","blue"));

    List<Person> t = list.stream().filter(p->p.getName().equals("Ana")).collect(Collectors.toList());
    System.out.println(t);
  }

}

For this particular question it is suggestible to use filter instead of map. Because we are only interested in filtering the stream to get the desired output.
On the other hand, map operation is used on the stream if we have the requirement to manipulate the data further in which condition we can apply more functions before the terminal operation (example is provided).
By using map, you transform the object values.
The map operation allows us to apply a function, that takes in a parameter of one type, and returns something else.
For an example:
Stream students = persons.stream()
      .filter(p -> p.getAge() > 18)
      .map(new Function<Person, Customer>() {
                  @Override
                  public Customer apply(Person person) {
                     return new Customer(person);
                  }
              });

Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out.
For in-depth understanding follow the documentation
link


text:
Q: Restart QThread with GUI I am using QThread to do some calculations in a separate Thread.
The Thread gets started by a button click, witch launches the function StartMeasurement().
The Thread can finish the process by itself (after finished the calculations)
and emits the PyQT Signal finished. Or the thread can be stopped by the User by the stopBtn click.
The terminate() function is working, but I get a lot of troubles when I try to start the thread again.
Is it recommendable to use the movetoThread() approach here?
Or how could I ensure that the thread is stopped correctly to enable a proper restart. (means, starting new!)
# starts the measurment in a Thread: StartMeasurement()
    def StartMeasurement(self):

        self.thread = measure.CMeasurementThread(self.osziObj, self.genObj, self.measSetup)

        self.thread.newSample.connect(self.plotNewSample)
        self.thread.finished.connect(self.Done)
        self.stopBtn.clicked.connect(self.thread.terminate)
        self.stopBtn.clicked.connect(self.Stop)

        self.thread.start()

A: It's not a problem. The general practice when working with QThread is to connect its finished() signal to the deleteLater() slot of the objects that have been moved to the separate thread via moveToThread(). It's done in order to properly manage the memory when you then destroy your thread because it's assumed that you will first quit the thread and then destroy its instance. ;) This should tell you that stopping a thread has nothing to do with the destruction of those objects UNLESS you have established the connection I've described above.
It is perfectly fine to restart a thread IF you have stopped it properly using quit() and wait() to actually wait untill the stopping is completed.
However my advice is to not do that unless that extra thread has a huge impact on your application for some reason (highly unlikely with modern machines).
Instead of restarting the thread consider the following options:

*

*implement a pause flag that just makes the thread run without doing anything if it's set to true (I've used this example of mine many times to demonstrate such behaviour (check the worker.cpp and the doWork() function in particular) - it's in C++ but it can be ported to PyQt in no time)

*use QRunnable - its designed to run something and then (unless autoDelete is set to true) return to the thread pool. It's really nice if you have tasks that occur every once in a while and you don't need a constatly running separate thread. If you want to use signals and slots (to get the result of the calculation done inside the QRunnable::run() you will have to first inherit from QObject and then from QRunnable

*Use futures (check the Qt Concurrent module)

I suggest that you first read the Example use cases for the various threading technologies Qt provides.


text:
Q: How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'? I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines  ...
for example:
$(document).ready(function() {
   $("#help-icon1").click(function() {
         $('#help-details1').css('display', 'block');
      });

   $("#help-icon2").click(function() {
         $('#help-details2').css('display', 'block');
      });

   $("#help-icon3").click(function() {
         $('#help-details3').css('display', 'block');
      });

});

Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.

A: I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
    jQuery(this).css('display', 'block');
});

A: You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)

If an element is clicked, you can append a new classname like so:
 $('.target').addClass('newclass');

more info:
http://api.jquery.com/addClass/

A: Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
    elm.click(function(){
      ...
    })
});

A: I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:

so they all have the same behaviour. Give them a class:

Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles

A: If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
    var detailsId = $(this).attr("id").replace("icon", "details");
    $("#" + detailsId).css('display', 'block');
});

A: Let's just ASSUME that you need to use IDs for some unknown reason.  Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
    $(this).css('display', 'block');
});

Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
    $(this).css('display', 'block');
});

But really, you don't need to use unique IDs like this without some pretty good reasons.


text:
Q: HTML Canvas and CSS I am wondering if CSS can be used to style something that in being rendered by a canvas?
For example, flot uses canvas to draw the charts however highcharts uses SVG.  Since SVG seems basically like a XML document, I can see that it would be very easy to style things highcharts creates with CSS.  Since creating a canvas does not create any extra markup, I would think it is not possible to customize the style through CSS (though I am asking this question since I am not very familiar with canvas).

A: I'm not an expert, but I think that using CSS in canvas directly is not possible. But you can try to read style from other HTML element (that uses CSS) and map it to canvas using its JS API. Here is an example how it could be done:
http://tjholowaychuk.com/post/6339741902/styling-canvas-drawings-with-css
But as I mentioned I'm not an expert and maybe someone found easiest solution.


text:
Q: INTO error in SELECT while creating stored procedure in PL/SQL I am trying to create stored procedure where I want to join two tables and save the result into one of the tables, but I am getting INTO clause is required error.
This is my code:
CREATE PROCEDURE DiorItemMaster
AS
SELECT *FROM pcdo_dior_item_master
INNER JOIN pcdo_itemdata on pcdo_itemdata.vpn = pcdo_dior_item_master.vpn;
GO;

ERROR:

Error(4,1): PLS-00428: an INTO clause is expected in this SELECT statement

A: You have a query that selects columns from a table in your pl/sql block. What do you want to do with the result of that query ? You cannot just select and not do anything with the results in pl/sql (you can in sql). Oracle expects that you to store the results of that select in variables. That can be done using the SELECT INTO clause.
Example (based on sample schema emp/dept):
DECLARE
  l_emp emp%ROWTYPE;
BEGIN
  SELECT e.* INTO l_emp FROM emp e WHERE e.ename = 'KING';
END;
/

Note that you can SELECT INTO individual columns and into rows. You cannot use SELECT INTO arrays.
A couple of other remarks about your code:

*

*You perform a SELECT * from a table with a join to another table without using aliases. This will return all columns from both tables. It is a lot more readable to prefix the "*" with a table alias like in the example.

*The GO; is not part of the oracle syntax - this will cause a compilation error.


text:
Q: How to deal with unsigned numbers in JavaScript? I am having difficult time dealing with unsigned numbers in JavaScript. I would like to perform basic math and bitwise operation on unsigned numbers using JavaScript especially shifting bits. Anyone have suggestions how to deal with unsigned numbers in JavaScript?
Example:
 Shifting 0x40000000 to the left gives you a negative number rather than 0x80000000


text:
Q: ISubscription to be passed in CreateFlow method for ITopicEndpoint I am creating a Flow instance for a ITopicEndpoint, the documentation says that ISubscription should be passed to the createFlow method only if endpoint is of type ISubscriberEndpoint.

From the documentation
  subscription Type:
  SolaceSystems.Solclient.Messaging.ISubscription Only valid if endpoint
  is of type ISubscriberEndpoint.

I am creating a Flow for a ITopicEndpoint so why am I getting the below error. What should i pass for ISubscription?
System.ArgumentException: 'subscription must be non-null when endpoint is of type ITopicEndpoint'
topic = ContextFactory.Instance.CreateDurableTopicEndpointEx(topicName);
flow = session.CreateFlow(flowProps, topic, null, HandleFlowMessageEvent, HandleFlowEvent);

A: For a durable topic endpoint, if you have multiple subscribers then each would have to register with a unique subscription name so that the broker can maintain a durable connection with the specific subscriber. Even if the subscriber is down for a while and reconnects, it will not loose out on messages in the interim. The broker will push the messages to the subscriber.
You can create a subscriber  via the Solace Admin client or via code.
Solace Admin -> Select the VPN -> Choose Endpoint tab -> select Durable Topic Endpoint -> click the + sign to create a subscriber -> ensure that consume is chosen for 'All other Permissions'


text:
Q: How to get app runtime on hadoop yarn Will yarn store informations about finished app including runtime on hdfs? I just want to get the app runtime through some files on the hdfs(if there did exist such file, I have checked the logs and there is no runtime informations) without using any monitoring software.

A: You can use the ResourceManager REST to fetch the information of all the Finished applications.
http://resource_manager_host:port/ws/v1/cluster/apps?state=FINISHED

A GET request to the URL will return a JSON response (XML can also be obtained). The response has to be parsed for elapsedTime for each application to get the running time of the application.

A: To look up persistent job history file, you will need to check Job History Server or Timeline Server instead of Resource Manager:

*

*Job history is aggregated onto HDFS, and can be seen from job history server UI (or REST API). The history files are stored on mapreduce.jobhistory.done-dir on HDFS.

*Job history can also be aggregated by timeline server (filesystem based, aka ATS 1.5) and can be seen from timeline server UI (or REST API). The history files are stored on yarn.timeline-service.entity-group-fs-store.done-dir on HDFS.


text:
Q: Minimization problem with latent function and splines I have a dataset consisting of pairs $(x_i, y_i)$. I want to determine the function $f$, so
$$
f(x)f(y) = 1
$$
with the constraint that $f(x) \leq x$, $f'(x) \geq 0$ and $f''(x) \geq 0$.
I was thinking that using splines in some way while constraining the parameters should let me find $f$ satisfying the constraints but I'm unsure how to define the minimization problem in the context of these splines. Any ideas?
Data is available here:
"x" "y"
0.8 1.111
0.76 1.163
0.98 0.92
0.66 1.316
0.9 1
0.78 1.136
1.031 0.87
1.042 0.86
0.85 1.053
1.087 0.82
0.83 1.075
1.099 0.81
0.93 0.97
0.4 2
0.34 2.273
1.053 0.85
1.075 0.83
1 0.9
0.89 1.01
0.91 0.99
0.92 0.98
0.95 0.95
0.82 1.087
0.86 1.042
0.88 1.02
0.41 1.961
0.72 1.22
0.96 0.94
0.7 1.25
1.02 0.88
1.111 0.8
0.81 1.099
1.136 0.78
0.94 0.96
1.19 0.74
0.31 2.439
0.39 2.041
1.25 0.7
0.99 0.91
0.87 1.031
0.97 0.93
1.064 0.84
0.44 1.852
0.84 1.064
0.38 2.083
1.163 0.76
0.68 1.282
0.42 1.923
0.33 2.326
0.75 1.176
0.62 1.389
0.77 1.149
0.61 1.408
0.74 1.19
0.51 1.639
0.6 1.429
0.58 1.471
1.176 0.75
1.124 0.79
0.5 1.667
1.01 0.89
0.46 1.786
1.205 0.73
0.65 1.333
0.48 1.724
0.55 1.538
0.54 1.563
0.37 2.128
0.79 1.124
0.45 1.818
1.149 0.77
0.73 1.205
0.3 2.5
1.22 0.72
0.28 2.632
0.71 1.235
0.35 2.222
0.64 1.351
0.53 1.587
0.63 1.37
0.36 2.174
0.49 1.695
0.32 2.381
0.56 1.515
0.59 1.449
0.67 1.299
0.43 1.887
0.25 2.857
0.69 1.266
0.47 1.754
0.52 1.613

A: Function $y(x)$ looks monotonical and continued. At the same time, there is a noise due to the discretization. The best approach is the least square method.
$$\color{brown}{\textbf{Linear model}}$$
Let $f(x) = ax+b,$ then should be minimized the function
$$G(a,b)=\sum_{i=0}^{n-1}\left((ax_i+b)(ay_i+b)-1\right)^2$$
$$=\sum_{i=0}^{n-1}\left(a^2p_i+abs_i)+b^2-1\right)^2,$$
or
$$G(a,b)= a^2(W_{20}a^2+2W_{11}ab+W_{02}b^2)+2a(b^2-1)(W_{10}a+W_{01}b)+W_{00}(b^2-1)^2,$$
where
$$
p_i=x_iy_i,\quad s_i - x_i +y_i,\\[4pt]
\begin{pmatrix}
W_{00} \\ W_{01} \\ W_{10} \\ W_{02} \\ W_{11} \\ W_{20}
\end{pmatrix}=\sum_{i=0}^{n-1}
\begin{pmatrix}
1 \\ s_i \\ p_i \\ s_i^2 \\ p_is_i \\ p_i^2
\end{pmatrix}=
\begin{pmatrix}
91\\
189.336\\
78.15834\\
400.527798\\
161.52697\\
67.315936\\
\end{pmatrix}
$$
Minimizing leads to the solution with the positive $a:$
$$a_0\approx1.069214,\quad b_0\approx 0.006625$$
(see also Wolram Alpha).
The plot with the values of $\mathbf{\color{lightgreen}{x_i}},$ $\mathbf{\color{blue}{y_i}}$ and $\mathbf{\color{red}{f(x_i)f(y_i)}}$ is shown below. The dotted plots are $f(x_i)$ and $f(y_i).$

$$\color{brown}{\textbf{Quadratic model}}$$
Let $f(x) = ax^2+bx+c,$ then should be minimized the function
$$G(a,b,c)=\sum_{i=0}^{n-1}\left((ax_i^2+bx_i+c)(ay_i^2+by_i+c)-1\right)^2$$
$$=\sum_{i=0}^{n-1} \left((a^2p_i+abs_i+b^2)p_i+ac(s_i^2-2p_i)+bcs_i+c^2-1)\right)^2$$
$$=\sum_{i=0}^{n-1} \left((a^2p_i+abs_i+b^2-2ac)p_i+((as_i+b)cs_i+c^2-1))\right)^2$$
$$= a^4W_{40}+2a^3bW_{31}+a^2b^2W_{22}+2(b^2-2ac)(a^2W_{30}+abW_{21})+(b^2-2ac)^2W_{20}$$
$$+2a^2(acW_{22}+bcW_{21}+(c^2-1)W_{20}))$$
$$+2ab(acW_{13}+bcW_{12}+(c^2-1)W_{11}))$$
$$+2(b^2-2ac)(acW_{12}+bcW_{11}+(c^2-1)W_{10}))$$
$$+a^2c^2W_{04}+2abc^2W_{03}+b^2c^2W_{02}+2(c^2-1)(acW_{02}+bcW_{01})+(c^2-1)W_{00},$$
where
$$
\begin{pmatrix}
W_{00} \\ W_{01} \\ W_{02} \\ W_{03} \\ W_{04} \\ W_{10} \\ W_{11} \\ W_{12} \\ W_{13} \\ W_{20} \\ W_{21} \\ W_{22} \\ W_{30} \\ W_{31} \\ W_{40} \\
\end{pmatrix}=\sum_{i=0}^{n-1}
\begin{pmatrix}
1 \\ s_i \\ s_i^2 \\ s_i^3 \\ s_i^4 \\ p_i \\ s_ip_i \\ s_i^2p_i \\ s_i^3p_i \\ p_i^2 \\ s_ip_i^2 \\ s_i^2p_i^2 \\ p_i^3 \\ s_ip_i^3 \\ p_i^4 \\
\end{pmatrix}=
\begin{pmatrix}
91\\
189.336\\
400.527798\\
863.931994\\
1905.452187\\
78.15834\\
161.52697\\
338.997886\\
724.521647\\
67.315936\\
138.255465\\
288.018453\\
58.12748\\
118.699206\\
50.313345\\
\end{pmatrix}
$$
Minimizing via MathCAD with the initial point
$$a_1=0,\quad b_1=a_1\approx1.069214,\quad c_1=b_0\approx 0.006625$$
leads to the solution
$$a_1\approx 0.314097,\quad b_1\approx 0.75514,\quad c_1=0.006678.$$
The plot with the values of $\mathbf{\color{lightgreen}{x_i}},$ $\mathbf{\color{blue}{y_i}}$ and $\mathbf{\color{red}{f(x_i)f(y_i)}}$ is shown below. The dotted plots are $f(x_i)$ and $f(y_i).$
The values of the quadratic residuals are $g_0=0.228178$ for linear model and $g_1 = 0.006671$ for the quadratic one.

$$\color{brown}{\textbf{Exponential models}}$$
Let $f(x) = e^{h(x)},$ then the condition $f(x)f(y)$ transtorms to
$$h(x)+h(y)=0.$$
Let $h(x)=Ax^3+Bx^2+Cx+D,$ then can be minimized the function
$$G(a,b)=\sum_{i=0}^{n-1}\left(A(x_i^3+y_i^3)+B(x_i^2+y_i^2)+C(x_i+y_i)+2D\right)^2$$
$$=\sum_{i=0}^{n-1}\left(As_i^3+Bs_i^2+Cs_i+2D-(3As_i+2B)p_i\right)^2,$$
or
$$G(a,b)= 9a^2W_{22}+12abW_{21}+4b^2W_{20}-2(3a^2W_{14}+5abW_{13}+(2b^2+3ac)W_{12}+(2bc+6ad)W_{11}$$
$$+4bdW_{10}+a^2W_{06}+2abW_{05}+(2ac+b^2)W_{04}+(4ad+2bc)W_{03}+(4bd+c^2)W_{02}+4cdW_{01}+4d^2W_{00},$$
where
$$
p_i=x_iy_i,\quad s_i - x_i +y_i,\\[4pt]
\begin{pmatrix}
W_{00} \\ W_{01} \\ W_{02} \\ W_{03} \\ W_{04} \\ W_{05} \\ W_{06} \\ W_{10} \\ W_{11} \\ W_{12} \\ W_{13} \\ W_{14} \\ W_{20} \\ W_{21} \\ W_{22} \\
\end{pmatrix}=\sum_{i=0}^{n-1}
\begin{pmatrix}
1 \\ s_i \\ s_i^2 \\ s_i^3 \\ s_i^4 \\ s_i^5 \\ s_i^6 \\ p_i \\ p_is_i \\ p_is_i^2 \\ p_is_i^3 \\ p_is_i^4 \\ p_i^2 \\ p_i^2s_i \\ p_i^2s_i^2 \\
\end{pmatrix}=
\begin{pmatrix}
91\\
189.336\\
400.527798\\
863.931994\\
1905.452187\\
4308.022154\\
10003.30059\\
78.15834\\
161.52697\\
338.997886\\
724.521647\\
1581.452913\\
67.315936\\
138.255465\\
288.018453
\end{pmatrix}
$$
Minimizing via MathCAD with the initial point
$$a_2=b_2=d_2=0,\quad c_2=1$$
leads to the solution
$$a_2\approx 0.00886,\quad b_2\approx-0.075331,\quad c_2\approx0.241154,\quad d_2\approx
-0.168262.$$
The plot with the values of $\mathbf{\color{lightgreen}{x_i}},$ $\mathbf{\color{blue}{y_i}}$ and $\mathbf{\color{red}{f(x_i)f(y_i)}}$ is shown below. The dotted plots are $f(x_i)$ and $f(y_i).$
The values of the quadratic residuals are $g_1 = 0.006671$ for the quadratic model and $g2=0.000016$ for the exponential one.

$$\color{brown}{\textbf{Conclusions.}}$$
The most effective model is quadratic one. The linear model has low accuracy, and the exponentional one does not use the negative coefficients.


text:
Q: Custom error formatting I have implemented my own custom error:
function MyError() {
    var temp = Error.apply(this, arguments);
    temp.name = this.name = 'MyError';
    this.stack = temp.stack;
    this.message = temp.message;
}

MyError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: MyError,
        writable: true,
        configurable: true
    }
});

And what I'm missing is to make it display itself on screen as it would when a regular unhanded error occurs, i.e. if we do throw new Error('Hello!'), we get output:
throw new Error('Hello!');
^

Error: Hello!
    at Object.<anonymous> (D:\NodeJS\tests\test1.js:28:7)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:138:18)
    at node.js:974:3

Now I want the same nicely formatted output when I'm doing this:
try {
    throw new MyError("Ops!");
} catch (e) {
    console.log(e);
}

but instead I'm getting:
{ [MyError: Ops!]
  name: 'MyError',
  stack: 'MyError: Ops!\n    at MyError.Error (native)\n    at new MyError (D:\\NodeJS\\tests\\test1.js:2:22)\n    at Object.<anonymous> (D:\\NodeJS\\tests\\test1.js:22:11)\n    at Module._compile (module.js:425:26)\n    at O
bject.Module._extensions..js (module.js:432:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:313:12)\n    at Function.Module.runMain (module.js:457:10)\n    at startup (node.js:138:18)\n
at node.js:974:3',
  message: 'Ops!' }

What else needs to be done to make console.log(e) output the same nicely formatted presentation for MyError automatically, without having to use explicit e.stack reference?
UPDATE: At first I saw some recommendations regarding method toJSON to be implemented, which I did, but it didn't quite work. I assume there must be an overridable method that console.log uses in order to format an error object, but what is it then?

A: Instead of overriding the toJSON method (or, toString as is frequently assumed), you should override inspect, which is used when trying to console.log an object in V8.
For example:
MyError.prototype.inspect = function () {
    return this.stack;
};

should probably do the trick.

A: Try this
try {
  throw new MyError("Ops!");
} catch (e) {
  console.log(e.stack);
}

If you execute this code in the console of your browser it will display like this:
MyError: Ops!
  at MyError.Error (native)
  at new MyError (<anonymous>:3:22)
  at <anonymous>:18:11
  at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
  at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
  at Object.InjectedScript.evaluate (<anonymous>:664:21)

If I understand correctly what you want is to print the stack of your error?

A: I have written a function to handle uncaughtException Errors so that the server does not stops on unhandled errors.
Function
function errorHandler (){
  process.on('uncaughtException', function (err) {
    console.log(err); // Displays the Error;
    console.error((new Date).toUTCString() + ' uncaughtException:', err.message); // Displays the Date and Error Message.
    console.error(err.stack);  // Stack in Which the error occurred.
  });
}

Output
ISODate("2015-07-28T04:56:20.000Z") uncaughtException: Cannot read property 'asset' of undefined

TypeError: Cannot read property 'asset' of undefined\n
 at /Path/file.js:31:31\n
 at /path/node_modules/mongodb/lib/mongo_client.js:436:11\n
 at process._tickDomainCallback (node.js:463:13)

Hope This Helps.

A: It's not very recommended, but you could always hook the console.log handler:
var oldhandler = console.log;
console.log = function () {
    if (typeof(arguments[0].stack) != "undefined" && arguments[0] instanceof(Error) && typeof(arguments[0].stack) != "undefined") {
        oldhandler.apply(console,[arguments[0].stack]);
    } else {
        oldhandler.apply(console,arguments);
    }
}

try {
    throw new Error("qweqew");
} catch (ex) {
    console.log(ex);
}

Fiddle: http://jsfiddle.net/xagpf5ff/


text:
Q: How to get additional information associated to a python concurrent.future? I am trying to download a bunch of files from S3 in python. To speed it up, I use
def sync(self):
    def wait_for_job(job):
        (src_filename, dst_filename, f) = job
        try:
            result = f.result()
            logging.info("Download ok: {}, result={}".format(dst_filename, result))
        except IOError as e:
            logging.info("Download error: {} - {}".format(dst_filename, e))
            self.projectInfo.downloaded_files[src_filename] = 0

    while self.pending_jobs:
        wait_for_job(self.pending_jobs.pop(0))

def getFiles(files_to_download):
    for src, dst in files_to_download:
        self.pending_jobs.append( (src, dst, self.executor.submit(s3_ops.copy_file, src, dst)) )

Now, I'd like to use concurrent.futures.as_completed(). As it takes a list of futures, I can't pass self.pending_jobs to it (it's a list of tuples).
I could make self.pending_jobs just a list of futures, whose function would return not only result, but also src and dst:
def sync(self):
    def wait_for_job(f):
        try:
            (src_filename, dst_filename, result) = f.result()
            logging.info("Download ok: {}, result={}".format(dst_filename, result))
        except IOError as e:
            ### Can't get the value of dst_filename
            logging.info("Download error: {} - {}".format(dst_filename, e))
            self.projectInfo.downloaded_files[src_filename] = 0

    for job in concurrent.futures.as_completed(self.pending_jobs):
        wait_for_job(job)

def getFiles(files_to_download):
    for src, dst in files_to_download:
        l = lambda s, d: (s, d, ops.copy_file(s, d))
        self.pending_jobs.append( self.executor.submit(l, src, dst) )

I would get them after calling future.result(), as part of the tuple it returns. But in the case of an exception, I wouldn't be able to get anything.
Is there any way to accomplish this? I would expect as_completed including some parameter in the line of key in sorted (i.e., to let it know how to extract the future from an item in the list), but it doesn't seem to be there.


text:
Q: Microsoft quantum Development Kit with another PC I think that quantum teleportation can be realized by the Microsoft Quantum Development Kit, but by placing one piece of data (name A) on a PC not connected to the Internet and acting on one side (name B) Is it possible to react experimentally?
In the sample code, I do not feel realized just by comparing two variables in one code in one PC.

A: At the moment, Microsoft's Quantum Development Kit is focused on making it easier to write programs that act on stationary qubits such as topological qubits built using Majorana fermions. In that context, teleportation is a useful procedure for moving information around inside a single quantum device.
That said, you are quite right in that teleportation can also be used to transfer quantum states between distinct quantum devices — qubits such as polarization modes of photons that are used in such procedures are often called "flying qubits" to distinguish from stationary qubits. If you're interested in quantum networking protocols such as quantum key distribution that focus on what you can do by sending flying qubits, I'd recommend looking at the SimulaQron project. Their implementation of teleportation can be run on two distinct classical computers that share a classical network connection to simulate sending flying qubits.


text:
Q: Does glsl texture2d disable blending? I try to blend several deformations of a texture, each time in a different color, but the colors are not blended.
When I change only one line in my fragment shader: to use vec4 instead of texture2D, the colors are blended perfectly.
My code:
// set color mask to red only
glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
// draw
glDrawElements(GL_TRIANGLES, deformation_grid->mesh().triangles().size(),
        GL_UNSIGNED_SHORT, deformation_grid->mesh().triangles().data());

// set color mask to green only
glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE);
// draw
glDrawElements(GL_TRIANGLES, deformation_grid->mesh().triangles().size(),
        GL_UNSIGNED_SHORT, deformation_grid->mesh().triangles().data());

My Fragment shader:
const char fragment_shader[] = "precision highp float;\n"
    "uniform sampler2D u_texture;\n"
    "varying vec2 v_uv;\n"
    "void main() {\n"
    "  vec4 texColor = vec4(texture2D(u_texture, v_uv).rgb, 0.5);\n"
    "  vec4 oneColor = vec4(1.0, 1.0, 1.0, 0.5);\n"
    "  gl_FragColor = texColor;\n"
    "}\n";

I would expect to always get yellow, but I actually get yellow when I set
gl_FragColor = oneColor

and green when I set
gl_FragColor = texColor

Changing the alpha value in glColorMask() and in the fragment shader didn't have any effect.
Does texture2D disable the blending that is set by glColorMask?
If it does, how can I avoid it?


text:
Q: HowTo break out of a Tapestry loop? So, i am trying to break out of tapestry loop here.
This is my -more or less- simplified scenario:

    <t:loop source="firstSource" value="firstValue">

                <t:loop source="firstValue" value="secondValue">

${secondValue}

                </t:loop>
                <t:loop source="secondSource" value="thirdValue">

${thirdValue}

                </t:loop>

    </t:loop>

What I do not want to have is:
Tapestry loops through all entries in firstValue - then loops through all entries in secondSource. I do not want to iterate through secondSource inside the loop of fristValue as this would iterate through all entries in secondSource - and I just want to do 1 iteration at a time.
What I want to have is:
Tapestry enters the loop for firstValue and does some printing or whatever, then breaks after the first iteration and jumps into secondSource to do the first iteration . After it has finished it jumps back to firstValue and repeats these steps.
This is what in Java the "break;" would do.
I did not find a clue in the Tapestry documentation on how to do this, nor in their forums.
But it has to be possible in some way. I can not imagine I am the only one trying to do this.

A: Just put an if statement around the logic, probably using an index variable:
   <t:loop source="firstSource" value="firstValue">

                <t:loop source="firstValue" value="secondValue" index="firstValueIndex">
                   <t:if test="firstCondition">

${secondValue}

                   </t:if>
                </t:loop>
                <t:loop source="secondSource" value="thirdValue">
                  <t:if test="secondCondition">

${thirdValue}

                  </t:if>
                </t:loop>

    </t:loop>

In the Java page:
@Property
private int firstValueIndex;

public boolean getFirstCondition() {
  // logic to determine whether to break out
  return firstValueIndex == 0;
}

public boolean getSecondCondition() {
  // logic
}

A: My guess is that you have three sources of data and are trying to output three columns, is this right?
Sometimes you have to transform your data a little bit:  For example, you might need to do some work to convert one value from each of the three inputs into a single value:
public class Row {

  Object col1, col2, col2;

}

In your Java code, you would build up a List of Row objects.
In your template, you iterate over the Row objects, rendering the col1, col2 and col3 properties.
(In Tapestry 5.3 and above, a public field can be treated as a property.)
I've used similar techniques to output a calendar, which can be very tricky to manage using conditionals and the like inside the template.
Remember the role of the Controller in MVC: its job to mediate between the model and the view; sometimes that includes some simple transformations of the model data to fit in with the view.


text:
Q: Postgresql - Preserve relative position when using distinct I ran a query which returned a table like this.
 d |  e  | f
---+-----+----
 2 | 103 | C
 6 | 201 | AB
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 3 | 105 | E
 3 | 105 | E
 3 | 105 | E

What I want is to get distinct rows but in order. Basically I want this:
2 | 103 | C
6 | 201 | AB
1 | 102 | B
3 | 105 | E

I tried distinct and group by, but they are not always preserving the position (they preserved it for some other cases that I had). Any idea as to how can this be done easily or would one need to use other functionalities like rank?

A: Use case when:
order by case when f=C then 1 when f=AB then 2
when f=B then 3 when f=E then 5 else null end

A: SQL tables represent unordered sets.  There is no ordering, unless you have an explicit order by with a column or expression.
If you have such an ordering, you can do what you want using group by:
select d, e, f
from t
group by d, e, f
order by min(a);  -- assuming a is the column that specifies the ordering

A: You can try to order by ctid column, which describes the physical location of a row, to identify a row.

The physical location of the row version within its table. Note that although the ctid can be used to locate the row version very quickly, a row's ctid will change if it is updated or moved by VACUUM FULL. Therefore ctid is useless as a long-term row identifier. The OID, or even better a user-defined serial number, should be used to identify logical rows.

use row_number with windows function to make row number by ctid.
then get rn = 1 and order by ctid
CREATE TABLE T(
  d int,
  e int,
  f varchar(5)
);

insert into t values (2,103, 'C');
insert into t values (6,201, 'AB');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (3,105, 'E');
insert into t values (3,105, 'E');
insert into t values (3,105, 'E');

Query 1:
select d,e,f
from (
  select d,e,f,ctid,row_number() over(partition by d,e,f order by ctid) rn
  FROM T
)t1
where rn = 1
order by ctid

Results:
| d |   e |  f |
|---|-----|----|
| 2 | 103 |  C |
| 6 | 201 | AB |
| 1 | 102 |  B |
| 3 | 105 |  E |


text:
Q: htaccess for redirect to SSL For the past few hours (days) I have been having some trouble redirecting a
page to SSL.
My setup is as follows: I have the following .htaccess for an e-commerce site
on Apache 2.2.16 on Debian (all required mods enabled)
RewriteEngine On
RewriteBase /shop
RewriteCond $1 !^(index\.php|products|img|theme\.php|checkout\.php)
RewriteRule ^(.*)$ index.php?/$1 [L]

all requests are passed to index.php which acts as my controller and includes
other .php files as necessary.
I now want to use HTTPS for the checkout process which is a php script
cleverly called checkout.php
I thought it would be as easy as changing my .htaccess to:
RewriteEngine On
RewriteBase /shop
RewriteCond  %{SERVER_PORT} !^443$
RewriteCond %{SERVER_URI} checkout\.php
RewriteRule ^checkout.php?/$1 https://localhost/shop/checkout.php?/$1 [L,R]
RewriteCond $1 !^(index\.php|products|img|theme\.php|checkout\.php)
RewriteRule ^(.*)$ index.php?/$1 [L]

so that checkout.php is not processed by index.php.
Apparently it is not that simple. I could probably do it by using a hardcoded
https link to checkout but I would prefer to do it with mod_rewrite.
If anyone can share some insight into
this it would be really appreciated.
Thanks in advance

A: There are a few problems.  First, the pattern in your first RewriteRule
RewriteRule ^checkout.php?/$1   https://localhost/shop/checkout.php?/$1 [L,R]

is written incorrectly.  $1 isn't meaningful there (it's a capture result, but no capture has happened yet), and also the query string (part of the request after the ?) isn't part of what's matched, as the RewriteRule documentation says.
Second, I think you meant to use REQUEST_URI instead of SERVER_URI.
So I think you want something like this:
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/checkout\.php
RewriteRule .* https://localhost/shop/checkout.php [L,R]

RewriteCond %{REQUEST_URI} !^/(index\.php|products|img|theme\.php|checkout\.php)
RewriteRule ^(.*)$ /index.php?/$1 [L]

A few notes:

*

*You don't need to match or add back in the query string in the first RewriteRule; mod_rewrite will automatically add it back in.

*It's conventional to test RewriteCond %{HTTPS} off instead of
RewriteCond %{SERVER_PORT} !443, as @Jon Lin suggests.

*You may want to add the QSA flag in your second RewriteRule.


text:
Q: Custom header when requeing I'm using SimpleMessageListenerContainer to receive messages from RabbitMq. Is there a way to add custom metadata to a message when it is nack'ed? I would like to continue processing the message from the point it failed.
I'm assuming any exception that gets thrown from a listener will cause the message to be requeued ( provided the exception is setup for that).
Thanks,
Sudha

A: No. The amqp protocol only has a simple flag to requeue or not. You can use retry with a subclass of the RepublishMessageRecoverer to add headers, but it will requeue at the tail not the head. See the reference manual.


text:
Q: Sharing an ethernet connection My dorm room provides an ethernet connection. Since I wanted to share it and create a wireless connection, I connected the ethernet connection to the router to create a wireless connection.
The problem is that I should login through a proxy connection which my university provides, and there can be only one login per IP. The router is assigned a IP by the university. When I connect two or more devices, there are assigned local IP addresses. But there can be only one login as there is only one IP assigned to the router by the university.
What should I do the share the ethernet connection?

A: If you have a Windows  desktop around, you could try using ICS, and logging on to the proxy via the desktop when needed:

*

*Obtain a desktop computer if you don't already have one.

*Put 2 NICs in this desktop.

*Connect ethernet cable from wall to one NIC.

*Login to your proxy using the desktop.  You can also use this desktop for normal use.

*Connect an ethernet cable from the 2nd NIC in your desktop to a LAN port on a wireless router.

*Typically the default login of a wireless router is 192.168.1.1 or 192.168.1.254.  Find this information out for sure though.

*Set your second NIC to something like 192.168.1.55, subnet mask 255.255.255.0, and no default gateway or DNS.  You should then be able to log in to the wireless router's configuration interface.

*Set the wireless router's IP to 192.168.1.200.  Disable DHCP.  If you can't disable DHCP, flash it to DD-WRT or find another one that will let you.  You can also configure the SSID, wireless password and such as well.

*Enable Internet Connection Sharing on the second NIC.  You may need to remove the static IP assignment 192.168.1.55 earlier.

*Login to your school's proxy when necessary on the desktop.  Anyone connecting to the wireless router should be getting Internet via the ICS.  ICS has a built-in DHCP server and handles NAT as well.

You can use a laptop as well, if you get a USB to Ethernet adapter.  The only thing is that you might want to take the laptop with you so then  those connected could no longer use the Internet.

A: create a Virtual Wifi Access Point.
In linux , you can use hostapd to setup a virtual wifi access point given your wireless card supports master mode.check this  link to know more about creating Virtual Wifi Access Point


text:
Q: Customizing the formatting of a textual property list, with multi-line text, in Python? Consider this example, where we have an object with properties, which each contain strings - some single-line, others multi-line:
#!/usr/bin/env python3

import pprint

class SomeInfo(object):
  def __init__(self):
    self.some_param = "Some parameter value"
    self.another_param = "Another parameter value"
    self.quite_longish_param_name = """Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Fusce laoreet, odio sed finibus sollicitudin,
ipsum nibh vulputate ex, quis tempor lorem enim sed
massa. Duis commodo posuere fringilla."""

some_info = SomeInfo()

formatted_prop_list_str = pprint.pformat(vars(some_info))
print(formatted_prop_list_str)

This prints the following in terminal:
{'another_param': 'Another parameter value',
 'quite_longish_param_name': 'Lorem ipsum dolor sit amet, consectetur '
                             'adipiscing\n'
                             'elit. Fusce laoreet, odio sed finibus '
                             'sollicitudin,\n'
                             'ipsum nibh vulputate ex, quis tempor lorem enim '
                             'sed\n'
                             'massa. Duis commodo posuere fringilla.',
 'some_param': 'Some parameter value'}

... which is close to what I want, but not quite. What I'd really want is something like this:
           another_param: "Another parameter value"
quite_longish_param_name: "Lorem ipsum dolor sit amet, consectetur adipiscing
                           elit. Fusce laoreet, odio sed finibus sollicitudin,
                           ipsum nibh vulputate ex, quis tempor lorem enim sed
                           massa. Duis commodo posuere fringilla."
              some_param: "Some parameter value"

... or in other words:

*

*choice of quotation marks to double quotes

*no use of commas to separate parameters and their values

*multiline text has only one set of wrapping quotes; and its lines are aligned to each other, not to quotation marks; \n are not shown as line separators, and the multiline text is not re-wrapped

*properties' names are right-aligned, at the semicolon - and they are not wrapped in quotes.

Is there a way of persuading pprint to provide this kind of output - and if not, are there any other "easy" options (short of having to code my own text formatter)?

A: You can use eval() to convert your str to dict and then print it as per your format, like this:
import pprint

class SomeInfo(object):
  def __init__(self):
    self.some_param = "Some parameter value"
    self.another_param = "Another parameter value"
    self.quite_longish_param_name = """Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Fusce laoreet, odio sed finibus sollicitudin,
ipsum nibh vulputate ex, quis tempor lorem enim sed
massa. Duis commodo posuere fringilla."""

some_info = SomeInfo()

formatted_prop_list_str = pprint.pformat(vars(some_info))
# print(type(formatted_prop_list_str))

x=eval(formatted_prop_list_str)

for k,v in x.items():
    print(k+': '+'\"'+v+'\"')

OUTPUT:
another_param: "Another parameter value"
quite_longish_param_name: "Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Fusce laoreet, odio sed finibus sollicitudin,
ipsum nibh vulputate ex, quis tempor lorem enim sed
massa. Duis commodo posuere fringilla."
some_param: "Some parameter value"

A: Ok, here is my function that does this kind of print:
import pprint

class SomeInfo(object):
  def __init__(self):
    self.some_param = "Some parameter value"
    self.another_param = "Another parameter value"
    self.quite_longish_param_name = '''Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Fusce laoreet, odio sed finibus sollicitudin,
ipsum nibh vulputate ex, quis tempor lorem enim sed
massa. Duis commodo posuere fringilla.'''
    self.testlist = [5, 6, 7]

some_info = SomeInfo()

class propNameVal(object):
  def __init__(self, name, value):
    self.name = name
    self.value = value
def get_formatted_prop_list_str(inobj, indent=' ', spacer=' ', quotechar='"', propnamealign='>', sort=False):
  #print(type(sort))
  if type(sort)==list or type(sort)==tuple:
    #print("sort is list/tuple")
    propnamelist = sort
  elif sort:
    #print("sort is True")
    propnamelist = sorted( vars(inobj).keys() )
  else:
    #print("sort is False")
    propnamelist = vars(inobj).keys()
  #print(propnamelist)
  prop_names_vals = [ propNameVal(propname, vars(inobj)[propname]) for propname in propnamelist ]
  #print(prop_names_vals)
  prop_names_len = [ len(pnv.name) for pnv in prop_names_vals ]
  #print(prop_names_len)
  prop_names_maxlen = max(prop_names_len)
  #print(prop_names_maxlen)
  propnamefmt = '{:'+ propnamealign + str(prop_names_maxlen) + '}' #'{:>2}'
  prop_names_fmtd = [ propnamefmt.format(pnv.name) for pnv in prop_names_vals ]
  #print(prop_names_fmtd)
  out_lines = []
  for ip, pnv in enumerate(prop_names_vals):
    vallines = str(pnv.value).splitlines()
    if len(vallines) == 1:
      out_lines.append( '{}:{}{}{}{}'.format(prop_names_fmtd[ip], spacer, quotechar, vallines[0], quotechar) )
    else:
      for iln, valline in enumerate( vallines ):
        if iln==0:
          out_lines.append( '{}:{}{}{}'.format(prop_names_fmtd[ip], spacer, quotechar, valline) )
        elif iln==len(vallines)-1:
          tfmt = propnamefmt+' {}{}{}{}' # space instead of :
          out_lines.append( tfmt.format("", spacer, " ", valline, quotechar) )
        else:
          tfmt = propnamefmt+' {}{}{}' # space instead of :
          out_lines.append( tfmt.format("", spacer, " ", valline) )
  return "\n".join(out_lines)

formatted_prop_list_str = get_formatted_prop_list_str(some_info, sort=('another_param', 'quite_longish_param_name', 'some_param', 'testlist'))
print(formatted_prop_list_str)

Output:
$ python3 /tmp/test.py
           another_param: "Another parameter value"
quite_longish_param_name: "Lorem ipsum dolor sit amet, consectetur adipiscing
                           elit. Fusce laoreet, odio sed finibus sollicitudin,
                           ipsum nibh vulputate ex, quis tempor lorem enim sed
                           massa. Duis commodo posuere fringilla."
              some_param: "Some parameter value"
                testlist: "[5, 6, 7]"


text:
Q: How to allow traffic over VPN across namespaces using nftables I have a wireguard interface configured in a dedicated namespace vpn. It is configured first creating the interface in the main namespace (that has access to the physical interface routing to the Internet eno1), then moving the Wireguard interface wg0 to the vpn namespace (Reference).
Now, this is my ruleset in the main namespace:
sudo nft -a list table inet filter
table inet filter { # handle 15
        set blackhole { # handle 4
                type ipv4_addr
                elements = { 224.0.0.1, 224.0.0.251,
                             255.255.255.255 }
        }

        set in_tcp_accept { # handle 5
                type inet_service
                flags interval
                elements = { 22 }
        }

        set ip6blackhole { # handle 6
                type ipv6_addr
                elements = { ff02::16 }
        }

        set out_tcp_accept { # handle 7
                type inet_service
                flags interval
                elements = { 80, 443, 11371 }
        }

        set out_udp_accept { # handle 8
                type inet_service
                flags interval
                elements = { 53, 67, 123 }
        }

        chain global { # handle 1
                ct state established,related accept # handle 12
                ct state invalid drop # handle 13
        }

        chain input { # handle 2
                type filter hook input priority filter; policy drop;
                jump global # handle 14
                ip daddr @blackhole counter packets 0 bytes 0 drop # handle 15
                ip6 daddr @ip6blackhole counter packets 0 bytes 0 drop # handle 16
                iif "lo" accept # handle 17
                meta l4proto { icmp, ipv6-icmp } accept # handle 18
                tcp dport @in_tcp_accept ct state new accept # handle 19
                tcp dport { 80, 443 } ct state new accept # handle 20
                udp dport 51821 accept # handle 21
        }

        chain output { # handle 3
                type filter hook output priority filter; policy drop;
                jump global # handle 22
                oif "lo" accept # handle 23
                ip protocol icmp accept # handle 24
                ip6 nexthdr ipv6-icmp counter packets 3 bytes 192 accept # handle 25
                udp dport @out_udp_accept ct state new accept # handle 26
                tcp dport @out_tcp_accept ct state new accept # handle 27
                tcp sport 22 tcp flags { rst, psh | ack } counter packets 44 bytes 6052 accept # handle 28

and this blocks output traffic from wg0 in the vpn namespace.
How do I allow traffic to come from vpn namespace and go through eno1 to the Internet?

A: I will assume that WireGuard wg0 interface is configured to use main host's port 51821 since there's a rule about this port in the inet filter input chain, and the value is near the usual reference port 51820.
Just add the reverse of this input rule:

        udp dport 51821 accept # handle 21

in the inet filter output chain:
    udp sport 51821 accept

or else add this port in the out_udp_accept set.
With the several restrictions used compared to simpler setups, these are the two places allowing a new outgoing flow from UDP port 51821.
With the current rules, the same flow could be instead allowed as (new) incoming to 51821, allowing later through the global chain the whole flow in both directions as long as a peer reaches the system first, but this might never work for IPv4 in the incoming direction first if the system is hidden behind IPv4 NAT and the NAT gateway is not configured to forward UDP port 51821 to this system (or simply for example if the system is behind CG-NAT ...). If that's the case, PersistentKeepalive should be used in WireGuard's configuration.

Note: ICMPv6 in the output chain should be handled like it was in the input chain. Instead of:

ip protocol icmp accept # handle 24
ip6 nexthdr ipv6-icmp counter packets 3 bytes 192 accept # handle 25

this should be used:
meta l4proto { icmp, ipv6-icmp } counter accept

The reason, as documented, is that one should almost never use ip6 nexthdr which isn't the exact equivalent of ip protocol: it might match an intermediate header rather than the final ICMPv6 header, and thus fail to allow traffic.


text:
Q: Code forks fine on macbook laptop..but on Imac(Yosemite) I get errors in my shell script I'm still figuring out how to work within the terminal, mainly with FFmpeg at the moment. I have this code running for a while now on my macbook pro (snow leopard I think). It works fine, no glitches whatsover. I just got an Imac (yosemite) and I wanted to install the same code, but now it gives these minor stupid syntax errors - that are not at fault on my laptop! Its seems bizar to me, but maybe it's something I forgot to install .. like a certain library? I've tried to use the same steps as before but ofcourse I might have forgotten about one..
The code will make a clip of 5 seconds on every hour via the embedded webcam, (the hourly notice is being programmed within crontab). This is the shell script:

#!/bin/bash

FNAME=videocapture_`date +"%F_%H_%M"`.mpg
echo $FNAME

/usr/local/bin/ffmpeg -t 5 -f avfoundation -i "default" $FNAME

And these are the erros (I tried to change a few small syntaxes to see if it would stop but it just finds new errors)
"SyntaxError: EOL while scanning string literal
Arantxas-iMac:~ arantx$ python /Users/arantx/Documents/terminal\ stuff/camera.sh
  File "/Users/arantx/Documents/terminal stuff/camera.sh", line 3
    FNAME=videocapture_'date +"%F_%H_%M"`.mpeg
                                             ^
SyntaxError: EOL while scanning string literal
Arantxas-iMac:~ arantx$ python /Users/arantx/Documents/terminal\ stuff/camera.sh
  File "/Users/arantx/Documents/terminal stuff/camera.sh", line 3
    FNAME=videocapture_'date +"%F_%H_%M"`.mpeg
                                              ^
SyntaxError: EOL while scanning string literal
Arantxas-iMac:~ arantx$ python /Users/arantx/Documents/terminal\ stuff/camera.sh
  File "/Users/arantx/Documents/terminal stuff/camera.sh", line 3
    FNAME=videocapture_'date +"%F_%H_%M"`.mp4"

If someone can point something out that I might have missed, let me know!
Kind regards,
Arantxa


text:
Q: What is the meaning of "humbler walls"? I'm totally confused about this sentence; its grammar seems crazy. Please help me to understand it. It is from a documentary film about ancient history I've watched.

Life wasn't easy for ordinary Egyptians, but order was infinitely better than disorder. We all remember the pyramids and pharaohs, but advances which were, in the long term, just as significant were being made behind humbler walls. (0:49:41.60)
source: Andrew Marr's History of the World – Age of Survival

What are humbler walls? As I have watched the whole film, I think the meaning is:

Although pyramids and pharaohs were better developed than ordinary Egyptians, the significant advanced inventions of history were made by the ordinary Egyptians rather than by those pharaohs and pyramids.

What do you think about it?

A:
We all remember the pyramids and pharaohs, but advances which were, in the long term, just as significant were being made behind humbler walls

The grammar is not "crazy".
We can take out the parenthetical phrase "in the long term". We can remove the adjectival phrase "which were just as significant".

We all remember the pyramids and pharaohs, but advances were being made behind humbler walls.

It's a picturesque metaphorical phrase, almost poetic, likening the monumental faces of the pyramids to walls. And humble doesn't necessarily mean "deferent":

(Of a thing) of modest pretensions or dimensions:
he built the business empire from humble beginnings
[ODO]

So, in a sentence which is far more prosaic,

We may all remember the great buildings and their builders, but long-lasting and significant advances were also being made in buildings of lower status and smaller size.

A: Humbler walls
The walls in question are humble in the sense that they are lowly and unpretentious and they are low in the sense that they are not as tall as those of the grand palaces and pyramids.
I do however question the use of the comparative 'humbler'. It is not clear to me what they are supposed to be humbler than.

We all remember the pyramids and pharaohs, but advances which were, in the long term, just as significant were being made behind humbler walls.

There are problems with this sentence. Either it

*

*implies that pharoahs have (or are) walls!

or it

*implies that advances were being made behind the walls of pyramids. That is rather dubious. Pyramids were tombs -- there wasn't much going on behind their walls once said walls had been built.  [This claim is challenged, explored further, and I believe justified by me in the comments below]

A quick reading of the sentence yields its meaning. As you say, it suggests that ordinary people were making advances -- not just the great engineers who were responsible for the pharaohs' pyramids and palaces.
I don't agree that the grammar is crazy. It is quite possible to say erroneous or meaningless things and still speak in perfectly good grammar. Instead I would say that the sentence does not stand up to strict linguistic analysis from the point of view of its semantics.
EDIT 13 Oct 2015
I have amended the wording of this answer in response to some of the comments below. I still believe that the sentence in question is infelicitous and my reasons are given here and in the comments.


text:
Q: Setting Up LDAP on Odoo with Docker I'm using Docker to install Odoo version 9 on my Linux Centos server.  I need to use LDAP so I downloaded the addon, Authentication via LDAP, and saved it to my server in the directory  /mnt/extra-addons/auth_ldap.   When I started the Odoo container in Docker I pointed a Docker volume at the addon directory.  Below is the command I used.
docker run -v /path/to/addons:/mnt/extra-addons/auth_ldap -p 8069:8069 --name odoo --link db:db -t odoo

The instructions Say  "After installing this module, you need to configure the LDAP parameters in the Configuration tab of the Company details".  But I can't find the LDAP settings in the company configuration tab.
Where is the configuration tab or I'm I missing something else?

A: The addon module is included in the apps list, but the filters just stop it from appearing. The following are the instructions for install the auth_ldap addon for Odoo Version 9.

*

*Click on Administrator / About/ Activate the developer mode

*Click Ok

*Go to Apps / Update Apps List / Update

*Afterward update finished then click on the x next to Apps in the search box.

*Type 'auth' then click enter

*Click on install in Authentication via LDAP

*After install finishes click Setting/ General Settings/ Configure
your company data/ Configuration / Edit

*Then add LDAP parameters.


text:
Q: Read InputStream asynchronously I'm trying to receive packets and if no bytes are received continue with the code below. await ReadAsync blocks until a new packet is received. Is there any way to just read the current bytes received?
If I don't use await messages aren't received.
byte[] data = new byte[BufferSize];

IInputStream inputStream = socket.InputStream;
IBuffer buffer = data.AsBuffer();

socketInformation.GetStopwatchPingIdleTime().Start();

while (socketInformation.open)
{
    try
    {
        inputStream.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
        data = buffer.ToArray();
    }
    catch (Exception)
    {
        break;
    }

    while (true)
    {
        // Wait for payload size
        if (buffer.Length >= 4)
        {
            int commandType = (int)BitConverter.ToInt16(data, 0);
            int payloadSize = (int)BitConverter.ToInt16(data, 2);
            int packetSize = PacketHeaderSize + payloadSize;

            // Wait for a full message
            if (buffer.Length >= packetSize)
            {
                byte[] packet = new byte[packetSize];
                System.Buffer.BlockCopy(data, 0, packet, 0, packetSize);

                ParsePacketSequence(socket, socketInformation, packet);

                if (buffer.Length > packetSize)
                {
                    int bufferLength = (int)buffer.Length - packetSize;

                    byte[] newData = new byte[BufferSize];
                    System.Buffer.BlockCopy(data, packetSize, newData, 0, bufferLength);
                    data = newData;

                    buffer.Length = (uint)bufferLength;
                }
                else if (buffer.Length == packetSize)
                {
                    break;
                }
                else
                {
                    break;
                }
            }
            else if (buffer.Length == packetSize)
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    if (host)
    {
        // Send ping to player
        if (socketInformation.waitingPong == false &&
            socketInformation.GetStopwatchPingIdleTime().ElapsedMilliseconds > 5000)
        {
            byte[] pingPacket = CreatePacket(6, null);
            SendPacket(socket, socketInformation, pingPacket);

            socketInformation.waitingPong = true;
        }
    }

    await Task.Delay(33, tokenSource.Token);
}

inputStream.Dispose();
socket.Dispose();
tokenSource.Cancel();

A: It looks to me you are receiving a stream of messages. When a message is there you want to process it potentially at some later time or at a different place in the code.
A good approach for that is to have one Task continuously reading messages from the socket and putting them into a queue. You can then pull complete messages from the queue whenever you like.
That way you can get rid of most of the logic here. You never have to abort a read request and you never need to check for timeouts.


text:
Q: Resolver: LAN, VPN and WAN name resolution I have read the man pages on resolv.conf and resolvconf and resolvconf.conf but don't understand everything and feel I'm a tad lost on how I might (ahem) resolve this problem:
Scenario:
I have a LAN with a router that acts as DHCP and nameserver. The nameserver resolves all devices on this LAN either with no TLD or the .lan TLD. For example I can resolve with nslookup, ping, and any other tool names like "nas" and "nas.lan" that reach my NAS server (network accessible storage server). Any other names it forwards the request on to my ISP's DNSs.
My resolv.conf therefore looks like this:
# Generated by resolvconf
domain lan
nameserver 192.168.0.1

I get fine resolution of all LAN and WAN names.
I now connect to a Cisco VPN at work and resolvconf updates the resolv.conf to:
# Generated by resolvconf
domain myworkplace.com
search myworkplace.com lan
nameserver 192.168.1.10
nameserver 192.168.1.11
nameserver 192.168.0.1

And now I cannot reach "nas" or "nas.lan" on my LAN anymore but I can reach "nas" and "nas.myworkplace.com" on the VPN. WAN names are now resolved by the VPN assigned namesever 192.168.1.10, and the NAS I reach this way is on the VPN not on my LAN (a different server).
Aside: I don't actually have any such name clash, but I provide it in the apocryphal example here because a solution clearly needs to cater for it.
Now what I would like to achieve is something like this:
"nas.lan" resolves to my LAN NAS
"nas.myworkplace.com" resolves to the VPN NAS
"nas" resolves to one or the other based on config (hints of resolv.conf's ndots setting here but not sure).
My questions:

*

*Is this even doable with resolvconf?

*If not, is there some other way to do it (example using dnsmaq instead of libc as a resolver on my box?).

I appreciate any pointers here as I'm finding the man pages to be less than easy to digest and decrypt with a specific need like this in mind. I have searched on-line for a good while now and oddly enough only found others asking the same question (without answer) in other fora!
This isn't a problem unique to me, or my discovery clearly. Anyone on a LAN with devices they wants to see there, connecting to another LAN over a VPN seems likely to run into precisely this issue of being able to resolve only names on the VPN not the LAN while connected, needing to close the VPN to resolve LAN names again.

A: I guess the reason why you can't use your LAN DNS when using the VPN is that the resolver only makes two attempts by default:
From resolv.conf manual:

attempts:n
  sets the number of times the resolver will send a query to its name servers before giving up and returning an error to the calling application. The default is RES_DFLRETRY (currently 2, see ). The value for this option is silently capped to 5.

So its is trying the two DNS Servers provided by your companys VPN first and than returns an error. You could set attempts to 3 so your LAN DNS is also taken into consideration.
The downside to this is, that it slows down your DNS requests by waiting for the last server to finally answer. And you are sending all your DNS request to your company - thats an impact on performance and your privacy as well.
I would recommend to use dnsmasq.
You could add upstream DNS server by domain in a dnsmasq conf with an specified domain like this:
server=/lan/192.168.0.1

And by default dnsmasq polls upstream servers from the /etc/resolv.conf.
From the Notes section of the dnsmasq Manpage:

... By default, dnsmasq reads /etc/resolv.conf to discover the IP addresses of the upstream nameservers it should use, since the information is typically stored there. Unless --no-poll is used, dnsmasq checks the modification time of /etc/resolv.conf (or equivalent if --resolv-file is used) and re-reads it if it changes. This allows the DNS servers to be set dynamically by PPP or DHCP since both protocols provide the information. ...

So if your VPN Client change the resolv.conf you are able to use both if you could keep your dnsmasq on top of the resolv.conf.
But i guess this is not how the VPN is editing you resolv.conf so i would try to disable the DNS capabilities of the VPN and add the DNS Servers of your company manually to your dnsmasq config:
server=/myworkplace.com/192.168.1.10
server=/myworkplace.com/192.168.1.11
server=192.168.0.1

In this case all your queries for the internet and lan going to 192.168.0.1 and all queries for myworkplace.com are going to your companys DNS.

A: git clone https://github.com/timebandit1969/resolvchange.git

https://www.purebasic.com/download.php and download linux demo version of PureBasic x64, don't worry I don't think the limitations will stop you from compiling it, I checked it out. Compile (Make Executable) resolvchange.pb
    chmod +x resolvchange
start vpn if running one and immediately run resolvchange with the following:
    ./resolvchange


text:
Q: Replacing not working string Bukkit I have a string args[1] + args[2] + message but if I do
    String message = args[1] + args[2] + message;
    message.replace(args[1], "").replace(args[2], "");

A: If you look in the documentation of the replace method it says that it returns the modified String. A String is immutable and cannot be changed directly. You have to resolve the new String back to the variable:
message = message.replace(args[1], "").replace(args[2], "");


text:
Q: Error $ is not a function when open a popup? I using fancybox and tooltip from plugin of fancybox.js and tooltip.js
This is a javascript:
var yourock = {};
(function() {
    var attempts = 30;
    var old_jQuery;
    if (typeof(jQuery) != "undefined") {
        if (typeof(jQuery.noConflict) == "function") {
            old_jQuery = jQuery;
            delete jQuery;
        }
    }

    var addLibs = function() {
        var head = document.getElementsByTagName("head");
        if (head.length == 0) {
            if (attempts-- > 0) setTimeout(addLibs, 100);
            return;
        }

        var node = document.createElement("script");
        node.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
        head[0].appendChild(node);
        checkLibs();
    }

    var checkLibs = function() {
        if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
            if (attempts-- > 0) setTimeout(checkLibs, 100);
            return;
        }
        yourock.jQuery = jQuery.noConflict(true);
        if (typeof old_jQuery == "undefined")
            jQuery = old_jQuery;
    }
    addLibs();

    var jQuery;

    var tooltip = document.createElement("script");
    tooltip.setAttribute("type","text/javascript");
    tooltip.setAttribute("src",
        "http://vinawebpro.com/widget/js/jquery.tooltip.js");
    tooltip.onload = scriptLoadHandler;
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(tooltip);

    var fancybox = document.createElement("script");
    fancybox.setAttribute("type","text/javascript");
    fancybox.setAttribute("src",
        "http://vinawebpro.com/widget/jquery.fancybox.js");
    fancybox.onload = scriptLoadHandler;
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(fancybox);

    function scriptLoadHandler() {
        jQuery = window.jQuery.noConflict(true);
        main();
    }
    function main() {
        jQuery(document).ready(function($) {
            $("div#result-col-1").tooltip();
            $("a.modal").fancybox({"type" : "iframe",});
        });

    }
})();

and code html :

tooltip here

When i run tooltip is result test ok, but when open popup from fancybox is result is error is "$ is not a function", how to fix it ?


text:
Q: Ansible is not accepting customer fail module - name:                             "Waiting for URL to come up."
  uri:
    url:                            "{{ url }}/libs/granite/core/content/login.html"
    status_code:                    200
  register:                         result
  until:                            result.status == 200
  retries:                          10
  delay:                            10
  fail:
    msg: "Service was not available after 10 minutes. Files were installed except for the ones that required AEM to be available"

I'm adding the fail message so when the task fails we will have a meaningful output.
However I receive an error:
 line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name:                             \"Waiting for URL to come up.\"\n  ^ here\n"}[0

I checked at the documentation and it seems that is the right way to do. What am I missing?

A: If you look at the documentation for the uri module, you will
note that there is no fail parameter. There is, however, a separate
fail module. If you'd like to use that, you will need to
rewrite your uri task such that it does not cause Ansible fail, but
instead records the task result so that you can use it in a subsequent
fail action.
- name:                             "Waiting for URL to come up."
  uri:
    url:                            "{{ url }}/libs/granite/core/content/login.html"
    status_code:                    200
  until:                            result.status == 200
  retries:                          10
  delay:                            10
  register: uri_result
  ignore_errors: true

- name: fail with custom message
  when: uri_result is failed
  fail:
    msg: >-
      Service was not available after 10 minutes. Files
      were installed except for the ones that required AEM
      to be available.


text:
Q: NSMutableArray containsObject method not detecting object // Add the button to the NSMutableArray.
...
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[[self hBtns] addObject:btn];
...

// In another method, try to see if it exists.
- (void)didPushBtn:(id)sender
{
  UIButton *btn = (UIButton *)sender;
  if ([[self hBtns] containsObject:btn]) // Is false every time.
  ...
}

Why is it not detecting that the UIButton is in the array?

EDIT
It turns out that it won't even detect it right after it's added:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[[self hBtns] addObject:btn];
if ([[self hBtns] containsObject:btn]) // Returns false.

A: Sounds like the isEqual: comparison is failing. Can you take a look at the hash for the UIButton in both places (where it's added, and then in didPushBtn) and see if they're the same value?

A: I had forgotten to initialize the array (*doh*):
[self setHBtns:[[NSMutableArray alloc] initWithCapacity:0]];