text:
Q: mixin method is undefined in created hook of component <template>

    Top

</template>

getTemplates function is working fine if i click on link but getting error in all life hooks of Vue js component.
Thanks for help in advance !

A: You forgot this for the function. Loading mixins has the same effect as if the content in it would be in your actual component. You need to call the methods the same way as you would call a local function. Always with this.
So change it to:
created() {
    this.templates = this.getTemplates();
},


text:
Q: Streaming images to ffmpeg out of order I have an algorithm that generates a video frame by frame, which I am refactoring to stream the images to ffmpeg rather than save them all to disk first.
The algorithm currently generates and saves a bunch of QImages then executes ffmpeg (with QProcess). The new version will generate QImages then stream them out to ffmpeg's stdin via QProcess. I can do all that just fine.
The issue is, I'm not actually generating the images serially, I'm generating them on a thread pool, maybe 12-16 at a time (just using QtConcurrent). I'd like to keep this parallelism for performance reasons, since the operation (even excluding image encoding and file I/O) does take a long time.
So my question is, does ffmpeg have something like image2pipe but that can take the images slightly out of order (let's assume there's some sane maximum offset, +/- 20 or so)?
If not, my solution will be to divide the image set into small batches, then for each batch, run it on the pool, reorder it, and stream them in the correct order; sacrificing some fraction of performance depending on the batch size. I'd rather not do that just because the code right now is dirt simple, and simple is good. So I'm wondering if there's a way to get ffmpeg to accept the images out of order.
They're at a fixed frame rate, if that is useful (maybe there's some way to set PTS's or something, then I just find a codec + container that can store out-of-order frames).

redpajama_set_name: RedPajamaStackExchange


text:
Q: More efficient way to do multiple parents Is there a more efficient way to do the following?
$(this).parent().parent().parent().parent().parent().addClass('finished');

Note that I need the parent concept, because I have multiple similar items on the page.

A: If the goal is to get the Nth parent, you can mix .parents(selector) with the :eq() selector, noting that :eq(0) gets the 1st item:
$(this).parents(':eq(4)').addClass('finished');

A: If this is something you use a lot, and adding proper selectors isn't an option, you could just create your own method to get what you want as well :
$.fn.parent_num = function(num) {
    var elem = [];
    this.each(function() {
        var el = this;
        while(num>0) {
            if (el.parentNode) el = el.parentNode;
            num--;
        }
        elem.push(el);
    });
    return $(elem || this);
};

to be used like :
$(this).parent_num(5).addClass('finished');

FIDDLE

A: If you have any way to get the element with a CSS selector, you can do this:
$(this).parents('selector');

.parents()


text:
Q: Configuring Visual State Setters for a Style Universal Windows App I have a UWP app where I have created various styles for buttons and textblocks that are being used in different pages. I had assumed that I will be able to apply Visual State setters on the styles itself. However, it seems that the setters in Visual State can only be applied directly to a specific control. Is there any way to apply Visual State to an Style elements. I have 60 textblocks in my pages that have all a particular font size. Do I have to go and specify a different font size for everyone of these controls to use Visual State or is there a simpler way to do it.
thanks in advance.

A: I think you should take a difference approach: Bind the font size of 60 TextBlock to a property, and update + notify it when your condition triggered in code behind.
in XAML:
<TextBlock FontSize={"Binding MyFontSize"}/>
<!-- 60 of your textblock here ...... -->

in your ViewModel, I use MVVM Light to notify the property changed event:
private double _MyFontSize = null;

    public double MyFontSize
    {
        get
        {
            return _MyFontSize;
        }
        set
        {
            Set(ref _MyFontSize, value);
        }
    }

In your code behind:
in contructor:
this.SizeChanged += LoginPanel_SizeChanged;

private void LoginPanel_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        if(e.NewSize.Width >= 600)
        {
            (this.DataContext as MyViewModel).MyFontSize = 20;
        }
        else
        {
            (this.DataContext as MyViewModel).MyFontSize = 16;
        }
    }


text:
Q: Pointers on solving this Image Processing challenge? The 2nd problem in IOI 2013 states:

You have an Art History exam approaching, but you have been paying
more attention to informatics at school than to your art classes! You
will need to write a program to take the exam for you.
The exam will consist of several paintings. Each painting is an example of one of
four distinctive styles, numbered 1, 2, 3 and 4. Style 1 contains
neoplastic modern art. Style 2 contains impressionist landscapes.
Style 3 contains expressionist action paintings. Style 4 contains
colour field paintings.
Your task is, given a digital image of a painting, to determine which style the painting belongs to.
The image will be given as an H×W grid of pixels. The rows of
the image are numbered 0, …, (H  1) from top to bottom, and the
columns are numbered 0, …, W  1 from left to right. The pixels are
described using twodimensional arrays R , G and B , which give the
amount of red, green and blue respectively in each pixel of the image.
These amounts range from 0 (no red, green or blue) to 255 (the maximum
amount of red, green or blue).
Implementation
You should submit a file
that implements the function style(), as follows:
int style(int H, int W, int R[500][500], int G[500][500], int B[500][500]);

This function should determine the style of the image. Parameters are:

*

*H: The number of rows of pixels in the image.

*W: The number of columns of pixels in the image.

*R: A twodimensional array of size H×W , giving the amount of red in each pixel of the image.

*G: A twodimensional array of size H×W , giving the amount of green in each pixel of the image.

*B: A twodimensional array of size H×W , giving the amount of blue in each pixel of the image.

Example pictures are in the problem PDF
I do not want a readymade program. A hint or two to get me started would be nice, as I am clueless about this might be solved.

A: Since you are provided the image data in RGB format, first prepare a copy of the same image data in YUV. This is essential as some of the image features are easily identified patterns in the Luma(Y) and Chroma(U,V) maps.
Based on the samples provided, here are some of the salient features of each "style" of art :

Style1 - Neoplastic modern art

*

*Zero graininess - Check for large areas with uniform Luma(Y)

*Black pixels at edges of the areas(transition between different chroma).

Style2 - Impressionist landscapes

*

*High graininess - Check for high entropy (salt-n-pepper-noise like) patterns in Luma(Y).

*Pre-dominantly green - High values in green channel.
Greenavg >> Redavg
Greenavg >> Blueavg

Style3 - Expressionist action paintings

*

*High graininess -  Check for high entropy (salt-n-pepper-noise like) patterns in Luma(Y).

*NOT green.

Style4 - Color field paintings

*

*Zero graininess - Check for large areas with uniform Luma(Y)

*NO black(or near black) pixels at the transition between different chroma.

As long as the input image belongs to one of these classes you should have no trouble in classification by running the image data through functions that are implemented to identify the above features.
Basically it boils down to the following code-flow :

*

*Image has uniform luma?

*

*(If Yes) Image has black pixels at chroma transitions?

*

*(If Yes) Style1

*(If No) Style4

*(If No) Image is green-ish?

*

*(If Yes) Style2

*(If No) Style3

A: Maybe you can do a first approach using colors and shapes... In neo plastic modern it is likely that there will be only a few number of colors, occupying geometrical areas as in the  colour field paintings.
This might gives you a way to differenciate styles 1 and 4 from styles 2 and 3.
In styles 1 and 4 you have large areas with the same color, but in style 4 the color is rarely a solid color but brush strokes of shades of the color.
Anyway you should look into the specialities of each styles, which are the usual colors and methods and then try to make your function "see" it.


text:
Q: How could I return value with Vue.js I has worked with Vue for several days, and meet some problem.
I use jQuery AJAX load data (text content) in template, title and description need to be ellipsis, I wrote the methods ↓
methods:{
               titleELLIPSIS:function(){
                    var title = self.articleList.title;//AJAX data
                    var titleLength = title.length;
                    var maxWidth = 15;
                    var newTitle = title.split("",maxWidth);
                    return title(function(ELLIPSIS){
                        if(titleLength>maxWidth){
                            for(var j=newTitle.length-1;j>0;j--){
                                delete newTitle[j];
                                var ELLIPSIS = self.innerHTML = newTitle.join('')+'...';
                                if(newTitle.length<=maxWidth){ break;}
                                return ELLIPSIS;
                            }
                        }
                    })

                }
}

And my template is:

{{titleELLIPSIS}}

How could I return the ellipsis title in h2?
Please give me some idea.
By the way, the AJAX is success, because other data show correctly.

A: Computed property is what you're looking for. Move titleEllipsis to computed section:
computed: {
   titleELLIPSIS:function(){
        var title = self.articleList.title;//AJAX data
        var titleLength = title.length;
        var maxWidth = 15;
        var newTitle = title.split("",maxWidth);
        return title(function(ELLIPSIS){
            if(titleLength>maxWidth){
                for(var j=newTitle.length-1;j>0;j--){
                    delete newTitle[j];
                    var ELLIPSIS = self.innerHTML = newTitle.join('')+'...';
                    if(newTitle.length<=maxWidth){ break;}
                    return ELLIPSIS;
                }
            }
        })

    }
}

A: titleELLIPSIS is defined as a method, therefore you need to actually call it.

{{ titleELLIPSIS() }}

The way you are using it is like it's defined as a data or computed property.


text:
Q: How can I fix/improve the typings of my Decorator containing a Proxy? I've written this decorator which uses a Proxy to read value from the local storage for a list of specified properties.
function StoredValues<T>(storageKey: string, storedProperties: Array<keyof T>) {
  function keyForProperty(property: string | symbol) {
    return `${storageKey}.${property.toString()}`;
  }

  function shouldUseStorage(property: string | symbol): boolean {
    return storedProperties.includes(property as keyof T); // Is it possible without type assertion ?
  }

  function actualDecorator(target: Function) {
    // better return type ?
    const f: any = function (...args: any[]) {
      return new Proxy(Reflect.construct(target, args), {
        get(target, property) {
          if (shouldUseStorage(property)) {
            const fromStorage = localStorage.getItem(keyForProperty(property));
            if (fromStorage) {
              console.log('From storage', fromStorage);
              // Warning !!! this will return a string (was number before)
              return fromStorage;
            }
          }
          console.log('Pass through', property);
          return target[property];
        },
        set(target: any, property: string | symbol, value: any): boolean {
          target[property] = value;
          if (shouldUseStorage(property)) {
            localStorage.setItem(keyForProperty(property), value);
          }
          console.log('Set', property, 'to', value);
          return true;
        },
      });
    };
    return f;
  }
  return actualDecorator;
}

I'm not quite satisfied with the typing I've used, particularly the any as return type. I've tried multiple things but I can't get quite the right typing.
For example if I use new Proxy<T>(), the compiler returns Decorator function return type '(...args: any[]) => Bar' is not assignable to type 'void | typeof Bar'
Playground


text:
Q: OpenCL, manage device buffer pointer from host? I'm trying to implement a code previously written in CUDA using OpenCL to run on Altera FPGA. I'm having problem reading back data that are supposed to be in the buffer. I use the same structure as CUDA version, only thing different is cudaMalloc can allocate memory for all types of pointer while for clCreateBuffer I have to use cl_mem. My code looks like this:
cl_mem d_buffer=clCreateBuffer(...);
 //CUDA version:
 //float* d_buffer;
 //cudaMalloc((void **)&d_buffer, MemSz);

clEnqueueWriteBuffer(queue, d_buffer, ..., h_data, );
 //cudaMemcpy(d_buffer, h_Data, MemSz, cudaMemcpyHostToDevice);

#define d_buffer(index1, index2, index3) &d_buffer + index1/index2*index3
 //#define d_buffer(index1, index2, index3) d_buffer + index1/index2*index3

cl_mem* d_data=d_buffer(1,2,3);

clEnqueueReadBuffer(queue, *d_data,...)// Error reading d_data

I tried clEnqueueMapBuffer or CL_MEM_ALLOC_HOST_PTR for the clCreateBuffer, it doesn't work either.

A: cl_mem is an opaque object. You should not perform pointer arithmetic on it; attempting to do so will result in very nasty bugs.
I'm not familiar with how CUDA handles buffer allocation, but the implication of your commented out code is that CUDA buffers are always Host-Visible. This is very strictly not the case in OpenCL. OpenCL allows you to "Map" a buffer to host-visible memory, but it won't be implicitly visible to the host. If you intend to read an arbitrary index of the buffer, you need to either map it first or copy it to host data.
float * h_data = new float[1000];
cl_mem d_buffer=clCreateBuffer(...);

clEnqueueWriteBuffer(queue, d_buffer, true, 0, 1000 * sizeof(float), h_data, 0, nullptr, nullptr);
//======OR======
//float * d_data = static_cast<float*>(clEnqueueMapBuffer(queue, d_buffer, true, CL_MAP_WRITE, 0, 1000 * sizeof(float), 0, nullptr, nullptr, nullptr));
//std::copy(h_data, h_data + 1000, d_data);
//clEnqueueUnmapMemObject(queue, d_buffer, d_data, 0, nullptr, nullptr);
//clEnqueueBarrier(queue);

//Do work with buffer, probably in OpenCL Kernel...

float result;
size_t index = 1 / 2 * 3; //This is what you wrote in the original post
clEnqueueReadBuffer(queue, d_buffer, true, index * sizeof(float), 1 * sizeof(float), &result, 0, nullptr, nullptr);
//======OR======
//float * result_ptr = static_cast<float*>(clEnqueueMapBuffer(queue, d_buffer, true, CL_MAP_READ, index * sizeof(float), 1 * sizeof(float), 0, nullptr, nullptr, nullptr));
//result = *result_ptr;
//clEnqueueUnmapMemObject(queue, d_buffer, result_ptr, 0, nullptr, nullptr);
//clEnqueueBarrier(queue);

std::cout << "Result was " << result << std::endl;


text:
Q: Importing a test suite into another project in soapUI I am working on a evaluation automation scenario in which i will create a test suite on one project-1 in soapUI and import into other projects (project2,project3) where the same test cases are applicable.
I exported the test suite and imported it in new project.But problem is,after importing into project2 and updating the test suite with new request, still the process request in the test case of test suite is having the end point URL of the project-1.How can this be rectified and also please point me source or documentation of how to import and export test suites.
Exporting test suite contains:
1.TestCase under which are:
1.Property File
2.Property Transfer
3.Process(of project-1)

SoapUI version-5.2.1
Thanks in Advance.


text:
Q: Error while running this project in tomcat6 When i am runig my project in myeclipse using tomcat6 then it will throw an error like so what should i do  this error regarding spring class but i will load all spring library from myeclipse
Jan 12, 2011 5:24:09 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.6.0\bin;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.easie.tomcat.myeclipse_8.6.0.me201007231647\tomcat\bin
Jan 12, 2011 5:24:10 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jan 12, 2011 5:24:10 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2559 ms
Jan 12, 2011 5:24:10 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jan 12, 2011 5:24:10 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.13
Jan 12, 2011 5:24:19 PM org.apache.catalina.loader.WebappLoader start
SEVERE: LifecycleException
java.lang.ClassNotFoundException: org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at org.apache.catalina.loader.WebappLoader.createClassLoader(WebappLoader.java:770)
    at org.apache.catalina.loader.WebappLoader.start(WebappLoader.java:639)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4196)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Jan 12, 2011 5:24:19 PM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start:
LifecycleException:  start: :  java.lang.ClassNotFoundException: org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader
    at org.apache.catalina.loader.WebappLoader.start(WebappLoader.java:676)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4196)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Jan 12, 2011 5:24:19 PM org.apache.catalina.startup.HostConfig deployDirectory
SEVERE: Error deploying web application directory servlet
java.lang.IllegalStateException: ContainerBase.addChild: start: LifecycleException:  start: :  java.lang.ClassNotFoundException: org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:795)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Jan 12, 2011 5:24:19 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jan 12, 2011 5:24:20 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jan 12, 2011 5:24:20 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/219  config=null
Jan 12, 2011 5:24:20 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 9998 ms

A: http://forum.springsource.org/archive/index.php/t-28028.html

A: Your Tomcat has been configured to use Spring's classloader instrumentation framework, but Spring is missing from your classpath.
You wither need to remove that instrumentation config, or add Spring to the classpath.

A: Seems like one of the Spring jars is not on your classpath.

A: This question is hard to answer without asking for more details... I had this (or similar) error in different situations, one of which is just solved.
If you're running the app using Eclipse's  "Run As/Run on Server" command/menu, then you could try either manually adding a spring-instrument-tomcat-.jar to the Tomcat's installation home/lib/ directory, and try again; or (if you do not actually need LTW nor  instrumentation) - check whether you have loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader" in your project ..webapp/META-INF/context.xml and remove it..
If you're actually using Maven and running as "Run As/Maven..." from eclipse (then - tomcat6:run command; also can do from console), then it's a different story.  The following POM configuration works both for deploying on a stand-alone tomcat (if you've added the spring JAR as I described above) and embedded one:
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <webResources>
                    <resource>
                        <targetPath>META-INF</targetPath>
                        <directory>src/main/config</directory>
                        <includes>
                            <include>context.xml</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat6-maven-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <port>8080</port>
                <path>/</path>
                <update>true</update>
                <classLoaderClass>org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader</classLoaderClass>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-instrument-tomcat</artifactId>
                    <version>${spring.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Note: the TomcatInstrumentableClassLoader and META-INF/context.xml file conflicts with the tomcat6-maven-plugin (which works when the context.xml file is not in src/main/webapp/META-INF/context.xml), so I had to move it to src/main/config and then let maven-war-plugin take care of it.
Cheers,
IR.


text:
Q: How to find the first index of the words? I use the following code
 String fulltext = "I would like to create some text and i dont know what creater34r3, ";
    String subtext = "create";

    int ind = -1;
            do {
                ind = fulltext.indexOf(subtext, ind + subtext.length());

            } while (ind != -1);

As a result, I find the first index of the words:
create creater34r3
But I need to find the first index only of the words create
How to do it? help

A: If I understand your requirement to find whole words in a string, if they're present, then how about this:
    String fulltext = "I would like to create some text and i dont know what creater34r3, ";
    String subtext = "create";
    Pattern pattern = Pattern.compile("\\b(" + subtext + ")\\b");
    Matcher matcher = pattern.matcher(fulltext);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

The output would be create
But it occurs to me that you need the actual index - if so you can add this to the while block:
      int start = matcher.start();
      int end = matcher.end();


text:
Q: How can the ICC(1,1) reliability of group A possibly be higher than group B? I have calculated the ICC(1,1) reliability of my groups A and B over 2 trials using SPSS (syntax below), and found (with 95% CI's):
ICC(1,1) Group A = .832 [.766, .881]
ICC(1,1) Group B = .801 [.725, .858]

RELIABILITY
  /VARIABLES=trial1 trial2
  /SCALE('ALL VARIABLES') ALL
  /MODEL=ALPHA
  /ICC=MODEL(ONEWAY) CIN=95 TESTVAL=0.

I am struggling to understand how the reliability from trial 1 to 2 could possibly be higher for Group A than for Group B of my dataset. It seems counter-intuitive since (1) Group A scores are on average 0.5 higher on trial 2 than trial 1 (a bulk shift that ICC model 1 should pick up since we treat raters, that is, trials, as random - and are checking for absolute agreement not just consistency), while on average Group B scores remain the same, and (2) the degree of change in scores from trial 1 to 2 seems lesser in general (as well as being more central) for Group B than for Group A (see histograms of trial-1-to-2 difference scores below).
After inspecting the data, the idea that the ICC(1,1) reliability as I've calculated it is higher for group A than B makes me wonder if I'm doing it wrong... and if not, where is the hidden variance in group B scores?

A: I may be closer to finding my own answer... ICC measures the proportion of variance attributable to error – hence if the total observed variance increases sufficiently, it is possible for ICC reliability to improve, without a reduction in error variance (or even with a small increase in error variance). This has happened between trial 1 and 2 for my dataset for group A – total variance is pretty large (5.079) compared with that of group B (2.756) at trial 2.
Ideally, to compare like with like, I need to keep the denominator of total variance the same for both groups. I think, since I am expecting zero true changes between trial 1 and 2, I should use the whole-sample between-subjects variance from trial 1. This will require me to calculate ICC from a formula but that is ok.


text:
Q: Adding JPanel to JFrame? I'm trying to add a JLabel to a JPanel to a JFrame. I set the border for the JPanel, but all I see on the JFrame is a small black square in the center of my frame. Whatever I do I can't change the size or location of it. Please help.
    Start main = new Start();
    Random random = new Random();

    JFrame mainFrame = new JFrame("MainFrame");
    JPanel mainPanel = new JPanel();
    JLabel welcomeLabel = new JLabel();

    mainFrame.add(main);
    mainFrame.setLayout(new GridBagLayout());
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setTitle(names[random.nextInt(names.length)]);
    mainFrame.pack();
    mainFrame.setVisible(true);
    mainFrame.setSize(mainFrameX, mainFrameY);
    mainFrame.setResizable(false);
    mainFrame.setLocationRelativeTo(null);
    mainFrame.add(mainPanel);

    mainPanel.add(welcomeLabel);
    mainPanel.setBorder(new LineBorder(Color.BLACK));
    mainPanel.setSize(new Dimension(200, 200));

    welcomeLabel.setFont(new Font("Verdana", 1, 20));
    welcomeLabel.setLocation(100, 100);

    main.start();

A: Suggestions:

*

*You will want to read the tutorial, Laying out Components, as it will explain how to code with the Swing layout managers, and this information is essential to solve your current problem.

*One caveat: I urge you to avoid the temptation to use the null layout as use of it will lead to creation of code that is very hard to maintain or upgrade.

*Your JLabel, welcomeLabel, will of course need some text to be visible.

*Don't set it's location via setLocation(...) but again use the layout managers to do the dirty work of placing and sizing your components.

*You will also want to call pack() and setVisible(true) on your JFrame after adding all initial components.

A: Hovercraft is right (+1), make sure you understand how the layout managers are working.
The order in which you do things are important, especially when dealing with the top level containers...
Start main = new Start();
Random random = new Random();

JFrame mainFrame = new JFrame("MainFrame");
JPanel mainPanel = new JPanel();
JLabel welcomeLabel = new JLabel();

welcomeLabel.setFont(new Font("Verdana", 1, 20));

mainPanel.add(welcomeLabel);
mainPanel.setBorder(new LineBorder(Color.BLACK));

// Do this first
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle(names[random.nextInt(names.length)]);

// Add your components
mainFrame.add(main);
mainFrame.add(mainPanel);

// Prepare the window for showing, now you have some content.
mainFrame.setResizable(false);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);

main.start();

This will still only produce a small black square in the window, because the JLabel has no content and therefore it's preferred size is going to be (something like) 2x2 (because of the border).
Try adding some text to...
welcomeLabel.setText("Welcome");

And then see the difference


text:
Q: 'System.ArgumentOutOfRangeException'"Tried the other solution but never gotten to the point of resolving" i've tried the other solution(like changing item that should be shown on data) but i think i've never gotten the point to resolving. Thank you in advance whoever can answer my problem...

Private Sub dgEmp_Click(sender As Object, e As EventArgs) Handles dgEmp.Click
    LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)

End Sub

Private Sub LoadEmployee(Optional q As String = "")
    list.Query = "Select id,lastname,firstname,middlename,sss,philh,pag,rate,cola,mStatus,free_insurance,mp,mpvalue from tblemployee where (lastname like'%" & q & "%'  or firstname like'%" & q & "%' or middlename  like'%" & q & "%') and deactive='No' order by lastname,firstname,middlename"

    list.datagrid = dgEmp
    list.LoadRecords()
    If list.RecordCount = Nothing Then Exit Sub

    LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)
End Sub
Public Sub LoadEmployeeInfo(index As Integer)
    With dgEmp.Rows(index)
        id = .Cells(0).Value
        lblName.Text = .Cells(1).Value & ", " & .Cells(2).Value & " " & .Cells(3).Value
        rpd = .Cells(7).Value
        lblRate.Text = Format(rpd, "#,##0.000000000")
        cola = .Cells(8).Value
        lblAllo.Text = Format(cola, "#,##0.000000000")
        otrate = (rpd / 8) * 1.25
        lblOTRate.Text = Format(otrate, "#,##0.000000000")
        IsSSS = ConvertToBoolean(.Cells(4).Value)
        IsPH = ConvertToBoolean(.Cells(5).Value) 'add
        IsPAG = ConvertToBoolean(.Cells(6).Value) 'pos
        IsMP = ConvertToBoolean(.Cells(11).Value)
        IsFI = ConvertToBoolean(.Cells(10).Value)
        CStatus = .Cells(9).Value
        MPV = .Cells(12).Value
    End With

    ThisPayroll.Query = "Select * from tblpayroll where payrollperiod=? and empid=?"
    ThisPayroll.AddParam("@payrollperiod", GetPeriod)
    ThisPayroll.AddParam("@empid", id)
    ThisPayroll.ExecQuery()

    If ThisPayroll.RecordCount = Nothing Then
        isUpdate = False
        txtReg_Days.Text = 0
        txtReg_OT.Text = 0
        txtSP_Days.Text = 0
        txtSP_OT.Text = 0
        txtHoliday.Text = 0
        txtHolidayOT.Text = 0
        txtLate.Text = 0
        txtAdjustment.Text = 0
        txtSSSL.Text = 0
        txtHDMFL.Text = 0
        txtCA.Text = 0
        txtDMA.Text = 0
        txtRice.Text = 0
        txtCloth.Text = 0
        txtEmpMed.Text = 0
        txtLaundry.Text = 0
        txtMeal.Text = 0
    Else
        With ThisPayroll.DataSource
            isUpdate = True
            txtReg_Days.Text = .Rows(0)("regday")
            txtReg_OT.Text = .Rows(0)("ot")
            txtSP_Days.Text = .Rows(0)("spday")
            txtSP_OT.Text = .Rows(0)("spdayot")
            txtHoliday.Text = .Rows(0)("lholiday")
            txtHolidayOT.Text = .Rows(0)("lhot")
            txtLate.Text = .Rows(0)("hlate")
            txtAdjustment.Text = .Rows(0)("salary_adj")
            txtSSSL.Text = .Rows(0)("sss_loan")
            txtHDMFL.Text = .Rows(0)("pag_loan")
            txtCA.Text = .Rows(0)("cash_advance")
            txtDMA.Text = .Rows(0)("depmed")
            txtRice.Text = .Rows(0)("ricesub")
            txtCloth.Text = .Rows(0)("clothing")
            txtEmpMed.Text = .Rows(0)("empmed")
            txtLaundry.Text = .Rows(0)("laundry")
            txtMeal.Text = .Rows(0)("meal")

        End With
    End If
    Compute()
End Sub

A: If you cannot make sure that something is selected elsewhere, you can last-minute check it like this:
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
    If dgEmp.SelectedRows.Count > 0 Then
        LoadEmployeeInfo(dgEmp.SelectedRows.Item(0).Index)
    End If
End Sub

It works only because you're using index zero, or else you would have to be careful for your index, too. Of course, this is assuming that dgEmp is not Nothing...
Also, notice that I attached this to the SelectionChanged event, as I don't think that the Click event will give you what you want, but I'll let that part for you to deal with. Have fun!


text:
Q: apt-get does not find suggested package (perf tool) I am using performance counters (https://perf.wiki.kernel.org/index.php/Main_Page) on Ubuntu 13.10 x86_64. If I type perf I get:
perf not found for kernel 3.11.0-031100
You may need to install linux-tools-3.11.0-031100-generic

But apt-get install ... does not find it
E: Unable to locate package linux-tools-3.11.0-031100-generic

uname -r returns 3.11.0-031100-generic, i.e., a slightly different kernel name (Ubuntu default is 3.11.0-13-generic)
How can I by default install the correct binaries matching the kernel (and/or what repositories do I have to add for this)?
(I know I can work around this by compiling it from the kernel sources in /tools/perf/; this works, but ideally I want to have it done automatically via apt.)

A: You need to have both linux-tools and the kernel in the same version or it won't work:
sudo apt-get install linux-tools linux-generic
sudo reboot

If you are using mainline kernels you must compile perf against the mainline sources, otherwise it will not work.

A: I was having the same problem.
Whenever I fire perf command I got :
$ perf
perf_2.6.38-1208 not found
You may need to install linux-tools-2.6.38-1208

But actually perf was installed by installing linux-tools package but it was with different name perf_2.6.38-16.
So, I am able to use perf with perf_2.6.38-16 command instead of perf.
You can create alias for perf_2.6.38-16 with name perf.
Hope someone with same problem may find it useful.

A: Open your terminal and type as
sudo apt-get install linux-lowlatency-tools-3.11.0-11

Then check again.
If it fails to get you , then install these packages also and then try again
sudo apt-get install linux-tools-common linux-base

Then check again.

A: For me, the problem was a wrong kernel version after upgrading my system from 13.10 to 14.04.
Fixed the kernel issue by reinstalling the generic kernel package (Wrong kernel after upgrade --- old kernel still installed?). After that, perf worked perfectly.


text:
Q: How to convert float value to another float value with some specified precession using python? How to convert float value to another float value with some specified precision using python?
>>> a = 0.1

but actually value of a is
0.10000000000000001

But I need to convert a to 0.1 in float type.

A: It is not possible to have 0.1 exactly when using the float type, due to how numbers are stored internally.  This offsite resources will hopefully explain the internals more easily.
Note that when you use the Python console it may look like you have 0.1 exactly but this is not true, as the code below shows
In [35]: a = 0.1

In [36]: print(a)
0.1 # Looks fine! But wait, let's print with 30 decimal places...

In [37]: print('{:.30f}'.format(a))
0.100000000000000005551115123126 # Uh oh.

This occurs because when printing in the console, only a certain number of decimal places are printed, and for 0.1 this number is such that where it starts to deviate from 0 is outside the range.
Python does have a Decimal package which can provide support for decimal numbers, as below
import decimal

a = decimal.Decimal('0.1')

print(a)
# 0.1

print('{:.30f}'.format(a))
# 0.100000000000000000000000000000

Note that I've constructed the Decimal object using the string '0.1' as opposed to the float 0.1. This is because if I had used the float then the Decimal object would have contained the same "errors" that the float has.

A: How about the round function: Round

A: You can use formate function with float and round function also
>>> a = float(format(0.10000000000000001, '.1f'))
>>> a
0.1
>>> round(0.10000000000000001,2)
0.1


text:
Q: Casting to a shared_ptr* from a void* I have a shared pointer that, due to interactions with a C library, spends part of its life as a void*
class Base { };

class Derived : public Base { };

int main() {
  // Construct the object.
  std::shared_ptr<Derived> derived = std::make_shared<Derived>();

  // Make a void* that I can pass into the C library.
  std::shared_ptr<Derived>* derived_ptr = new std::shared_ptr<Derived>(derived);
  void* my_void = derived_ptr;

  // Cast back into a shared_ptr when I get the void* from the C library
  std::shared_ptr<Base> base = *static_cast<std::shared_ptr<Base>* >(my_void);
}

My worry is that I could cause undefined behavior, because I am casting to std::shared_ptr<Base>* when I receive the void* back from the C library, rather than casting to std::shared_ptr<Derived>*.  I think that this would be safe if I were storing only a C-style pointer, but I don't know how inheritance and casting work with shared pointers.
Unfortunately, with the way my program is currently structured, when I am reading the void* out of the C library, I have no knowledge of the derived class, and so I can't just cast to std::shared_ptr<Derived>*, which I know would be safe.
Is it safe to use the casts as they are currently shown, for any possible combination of Base and Derived classes, or are there circumstances in which the result is not defined?


text:
Q: Input Text is not changing in the bean variable When i enter the data in the browser, it should suppose to set the variable parameter in the bean. But it is not setting for some reason. At one point it did work and again not anymore.
XHMTL

                <ice:form>
                    <ice:inputRichText id="editor_prevsummary"
                        value="#{statusReport.prevSummaryStr}" width="1200" height="200"
                        rendered="#{statusReport.renderPrevSummTextIn}"
                        onchange="this.form.submit()"  />

                    <ice:outputText value="#{statusReport.prevSummaryStr}"
                        rendered="#{!statusReport.renderPrevSummTextIn}" escape="false"></ice:outputText>

                    <ice:commandButton action="#{statusReport.editPrevSummary()}"
                        value="Edit" partialSubmit="true" />
                    <ice:commandButton action="#{statusReport.updatePrevSumm()}"
                        partialSubmit="true" value="Update"  />
                </ice:form>

Bean Values
  public String getExecSummaryStr() {

        return execSummaryStr;
    }

    public void setExecSummaryStr(String execSummary) {

        this.execSummaryStr = execSummary;
    }

I getting the same thing, even i change to inputText or anything. Not sure why it is happening and where i should start diagnosing the issue.

A: Your problem is because you're using the same variable for the <ice:inputRichText> and the <ice:outputText> inside the same form. When the form is submitted, the framework will set the value from both components into #{statusReport.prevSummaryStr}, leading to odd behavior in your site.
EDIT:
A possible solution could be moving the <ice:outputText> out of the form and rendering from your commandButton. Another solution could be using javascript to update its value. You can do something like:
<ice:inputRichText id="editor_prevsummary"
    value="#{statusReport.prevSummaryStr}" width="1200" height="200"
    rendered="#{statusReport.renderPrevSummTextIn}"
    onchange="document.getElementById('divText').innerHTML = this.value"  />


text:
Q: Python MVC just for wx gui -- if not it, then what? I have been spending time reorganizing a project gui.  Originally, I had a file with functions like "makeConfigWindow" and "makeMainWindow" and they did everything to make the windows.  The problem was that it was very tightly coupled and very specific, reusable code was nowhere for similar tasks.  I decided to try MVC with just the gui portion so I made a model class, view class, and controller class in one interface file.  One instance of each per wx.App (except view, that's a new one every new Frame).
The problem I'm running into now is that I seem to be reinventing the wheel.  My model simply grabs info from the config file and spits it out when requested, but this functionality was already there by directly referencing the config file.  The view, which is a subclass of wx.Frame, ended up having a bunch of functions like "changeBgColor(panel, color)" which was called by the controller -- the problem is that the controller could simply call those functions from wx instead of the View middleman.  And now, the controller has ended up looking just as specific as my original "makeMainWindow" functions.
It looks like the MVC framework was already there for this -- the config was the model, wxPython itself was the view, and the enormous command-after-command script was the controller.  Correct?
My question is this: if not this way, then how should I go about structuring my gui?  My biggest issue is that the gui ends up holding everything, objects, references, everything, because Mainloop is the only thing running in the end, minus a few threads doing system checks and the like, and then they throw events to the gui.

A: Most of the time, I use the wxPython code as my view. If the event handler needs to load a config or access a database, then it uses the controller to do that. The model for me has typically been database-related (or for ObjectListView). The wxPython code should only do wxPython related things.
What that means is if you have anything that does anything outside of wx, then it will probably go in either the model or the controller. Examples for the controller:

*

*parse a csv file

*start a thread

*run a database query

The following article(s) might help you:

*

*http://wiki.wxpython.org/ModelViewController

*http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/

*http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/

*http://pyvideo.org/video/288/pycon-2010--wxpython-ii--introduction-to-gui-prog


text:
Q: SQL query not selecting property I have query like this

SELECT   *
FROM     `GSheets`
WHERE    `sheetcat` = 'Unsubscribed'
AND      `sheetcat` IS NOT NULL
AND      `user` LIKE '%,r00t,%'
OR       `user` LIKE 'r00t,%'
OR       '%,r00t'
OR       `user` = 'r00t'

I specify sheetcat to be Unsubscribed, but query response is NULL (or blank)?
Why?

A: AND takes precedence over OR.  You need to group your OR conditions:
SELECT   *
FROM     `GSheets`
WHERE    `sheetcat` = 'Unsubscribed'
AND
(        `user` LIKE '%,r00t,%'
OR       `user` LIKE 'r00t,%'
OR       `user` LIKE '%,r00t'
OR       `user` = 'r00t'
)

The second sheetcat condition is also redundant, you can remove the NULL check.

A: This is a problem when you store lists of things in delimited strings.  Bad, bad, bad data design.  The first and primary advice is to create a new table with one row per sheet and one row per user.
Now, sometimes we are stuck with other people's really bad, bad, bad design decisions.  MySQL offers find_in_set() which does what you want:
SELECT g.*
FROM `GSheets` g
WHERE `sheetcat` = 'Unsubscribed' AND
      FIND_IN_SET('r00t', `user`) > 0;

Note that sheetcat IS NOT NULL is redundant.  A NULL value would fail the first condition.  Unless you possibly intend:
SELECT g.*
FROM `GSheets` g
WHERE `sheetcat` = 'Unsubscribed' OR
      (sheetcat IS NOT NULL AND FIND_IN_SET('r00t', `user`) > 0);

But that would not be my first guess as to your intention.
Your query would also work if you put parentheses around the OR conditions.  But even that is too complicated.  A simpler version using LIKE would be:
WHERE `sheetcat` = 'Unsubscribed' AND
       CONCAT(',', `user`, ',') LIKE '%,r00t,%'


text:
Q: Connect to nearest agent in collection So I have several different agent types: Person, Factory, Hospital, Home, Doctor.
Now, all of these agents except Person are connected through a network, while the initial population size of Person = 0.
Now, when the model runs, Person agents will be generated with a given rate. What I want to accomplish is that each instance of Person determines which instance of Factory, Hospital or Home is the nearest, and then makes a connection to that particular agent.
How would I accomplish this?
I have so far been able to let instances of Person connect to the nearest Hospital, the nearest Factory, or the nearest Home. I wrote the following code in the entry action box in a Person's statechart:
Hospital nearestHospital = this.getNearestAgent(main.Hospital); this.connectTo(nearestHospital);

But I have been unable to let the instances of Person determine the nearest instance of Hospital, Factory, Home concurrently.

A: In your Person agent you have to create 3 link to agents as you can see in the following figure: You will find them in the Agent palette.

After that, you have to create connections independently for hospital, home and factory. (since they are different agents)
Hospital nearestHospital = this.getNearestAgent(main.hospitals);
Home nearestHome = this.getNearestAgent(main.homes);
Factory nearestFactory = this.getNearestAgent(main.factories);
double distanceToHospital=distanceTo(nearestHospital);
double distanceToHome=distanceTo(nearestHome);
double distanceToFactory=distanceTo(nearestFactory);

hospitalLink.disconnectFromAll();
homeLink.disconnectFromAll();
factoryLink.disconnectFromAll();

if(distanceToHospital<distanceToHome && distanceToHospital<distanceToFactory)
   hospitalLink.connectTo(neareastHospital);
else if(distanceToHome < distanceToFactory)
   homeLink.connectTo(neareastHome);
else
   factoryLink.connectTo(nearestFactory);

That's the way it must be done... what you do later with it... I don't know


text:
Q: Is there a simple way to achieve the effect of `--no-parent` and also grab files from a specific top level directory, with wget? Using wget version 1.20.3 or higher...
I am currently using a command like so, to keep a static "backup" of my blog, but only pages under "/blog":
wget --mirror --convert-links --adjust-extension --page-requisites --wait=1 https://example.com/blog
However, some of my blog pages reference static downloadable files (usually a PDF; so extensions are known and predictable) that are stored in a top-level "static" directory, e.g.,
https://example.com/static-files/file1.pdf or https://example.com/static-files/file2.png
I would like the behavior of --no-parent, where only pages under /blog are downloaded, but I would also specifically like to archive all files that are linked to, that exist in the static-files directory.
Is there a simple way to do that with a single wget command?
If not, is there a reasonable compromise?

A: I think this will do what I need (it definitely downloaded the static files). Tho it seemed to download slightly different sets of files, so I'm not 100% sure what might be different:
wget --mirror --convert-links --adjust-extension --page-requisites --wait=1  --include-directories="/s,/blog" https://example.com/blog/

The output directories I have now are blog and static-files. blog contains more than it did... but I haven't looked at why.
The main difference here is that instead of excluding parent directories, we're  only including the directories we want content from.
I welcome anyone to expound on the differences, and explain why this may or may not be the correct answer.


text: Q: How can I add an option with a checkbox to add an additional fee to a product? I have a bit of a specific need to fill here. My client sales tennis lessons. He wants to be able to have an option on the form that I have created (Gravity Forms) that allows a customer to select a box that allows an additional student for the class. Not only does it allow the additional student, but it needs to charge an extra $10.00 for said student and have the availability to increment the number of students. Currently I have it set up like this (look towards the bottom) I would like to simplify it to have just the one check box and the increment number box as I already have on the site. Can anyone help me?


text:
Q: Weird behaviour of fill method in different kinds of UIBezierPath I have been experimenting with two shapes. First one is a type of frame and its code is below:
( (x,y) is origin of my UIView and (w,h) is its size)
[bpath moveToPoint:CGPointMake(x, y)];
[bpath addLineToPoint:CGPointMake(x + w, y)];
[bpath addLineToPoint:CGPointMake(x + w, y + h)];
[bpath addLineToPoint:CGPointMake(x, y + h)];
[bpath closePath];

[bpath moveToPoint:CGPointMake(x + 100, y + 100)];
[bpath addLineToPoint:CGPointMake(x + 100, y + 50)];
[bpath addLineToPoint:CGPointMake(x + 50, y + 50)];
[bpath addLineToPoint:CGPointMake(x + 50, y + 100)];
[bpath closePath];

This gives me following output:

And second one is a circle inside a circle. Its code is below:
[bpath moveToPoint:CGPointMake(x + w, y + h * 0.5)];
[bpath addArcWithCenter:CGPointMake(x + w * 0.5, y + h * 0.5) radius:midx startAngle:0 endAngle:2 * M_PI clockwise:YES];

[bpath moveToPoint:CGPointMake(x + w * 0.75, y + h * 0.5)];
[bpath addArcWithCenter:CGPointMake(x + w * 0.5, y + h * 0.5) radius:0.25 * w startAngle:0 endAngle:2 * M_PI clockwise:YES];

And for this I got something like below:

I applied [bpath fill] to both paths. So why there is a difference in fill pattern. (I tried adding closePath in 2nd case, but it didn't make any difference).
Also, is there a way to get similar fill pattern as of 1st shape for the 2nd one?
(I know it can be done by adding a second path for inner circle but I want to do it in one path)
Update: I noticed that if I use containsPoint on 2nd path, it returns FALSE when touch point is inside inner circle and returns TRUE only when touch point is in between two circles. Similar behaviour is shown by 1st shape also.

A: To have the second example make a hole, you need to set usesEvenOddFillRule.
bpath.usesEvenOddFillRule = YES;
[bpath fill];

Here's my working code:
UIBezierPath *bpath = [UIBezierPath bezierPath];
CGFloat x = rect.origin.x;
CGFloat y = rect.origin.y;
CGFloat w = rect.size.width;
CGFloat h = rect.size.height;
CGFloat midx = (x + w) / 2;

[bpath moveToPoint:CGPointMake(x + w, y + h * 0.5)];
[bpath addArcWithCenter:CGPointMake(x + w * 0.5, y + h * 0.5) radius:midx startAngle:0 endAngle:2 * M_PI clockwise:YES];

[bpath moveToPoint:CGPointMake(x + w * 0.75, y + h * 0.5)];
[bpath addArcWithCenter:CGPointMake(x + w * 0.5, y + h * 0.5) radius:0.25 * w startAngle:0 endAngle:2 * M_PI clockwise:YES];

[[UIColor blueColor] set];
bpath.usesEvenOddFillRule = YES;
[bpath fill];

Result:

Update:
After playing around with the code a little, I found out why your first example produces a hole and your second didn't: it's about the direction of the paths!
In the first path, the outer square is drawn clockwise while the inner square is drawn counter-clockwise. This seems to make the zero-rule for filling consider the inner rectangle to be "outside".
But the circles are both drawn in the same direction. If you reverse the direction of the inner circle it'll make a hole even without setting usesEvenOddFillRule:
[bpath addArcWithCenter:CGPointMake(x + w * 0.5, y + h * 0.5) radius:0.25 * w startAngle:2*M_PI endAngle:0 clockwise:NO];

(Notice that start and end angle are reversed and clockwise:NO).

A: The second example also needs the [bpath closePath]. The first example contains two closed subpaths, but currently the second example contains just one unclosed path.


text:
Q: Is allowing exceptions in static class constructors to escape a proper design pattern? I find myself choosing between the two following design patterns a lot:
static {
    try {
        foo();
    }
    catch(Exception exc) {
        throw new RuntimeException(exc.getMessage());
    }
}

and
TheConstructor() throws SomeException {
    if(alreadyInited) {
        return;
    }
    alreadyInited = true;
    foo();
}

The problem is I really do want to initialize stuff once per class - so statically, I think - such as setting up a logger, loading some map from a file, etc. - and I really do want the program to halt if this operation fails.  Both of these design patterns seem kludgey (the first one more obviously so), so I'm wondering if there's a better way to do this.

A:
Is allowing exceptions in static class constructors to escape a proper design pattern?

I would say No.
First, wrappering a checked exception in that context means that if something goes wrong you will get a class initialization failure.

*

*An exception that propagates out of the class initalizer cannot be caught and handled directly.

*An uncaught exception during class initialization is not recoverable.  Even if you could catch and handle the exception, the class and (I think) all others that depend on it / they will be left in a state where they cannot be initialized, and hence cannot be used.  That's effectively "game over" for (at least) the classloader, and possibly the entire JVM.
The bigger picture is that this probably represents an inappropriate use of statics.  There are better ways to handle this problem; e.g.

*

*Do the initialization using an explicit call (in a place where you can catch and handle the exception), rather than relying on class initialization.

*Get rid of the static (and potentially the singleton class that wraps it) and use dependency injection.

A: The factory pattern can help you here.  You can still throw RunTime exceptions, although I would throw an exception called "CouldNotCreate" along with some cool info on what went wrong.

A: Your first example looks fine to me. If your class absolutely needs to do foo() to be usable, then if it can't do foo(), it's not usable. If it's not usable, then it must not be used. Throwing an exception from the static initializer is a straightforward and effective way of making sure that the class isn't used.
It's unfortunate that Java doesn't allow checked exceptions to be thrown from static initializers. I don't see why that should be the case.

A: In this case I choose the singleton pattern FOR the "configuration".
But the logic inside the constructor is very strange, the static block is more clean IMHO, but I think it is not easy to test. Be careful.

A: You could make the second a little less kludgey like this:
static boolean isStaticInit = false;
static void staticInit() throws InitException {
    if (isStaticInit) return;

    // [init loggers, map, etc...throw InitException as appropriate]

    isStaticInit = true;
}

MyClass() throws InitException {
    staticInit();

    // ...
}

Note there is a subtle difference between your first and second options.  In the first option, the static{} block is called when the class is first loaded, while for the second option, the init code isn't called until the first class instance is constructed.  This could make a difference if you have code that calls, say, MyClass.myStaticMethod().  With option 1, the call would trigger class initialization; with option 2, it won't.


text:
Q: Many to many relation table name for tables with similar name I have two tables named business and business_category that have many-to-many relation. What name should I use for a third table that bind them together? I don't like business_business_category name at all.

A: You could name it - BusinessCategoryLink or BusinessesPerCategory

A: I would like to suggest you. Can make three table. Business, categories, businesses_x_categories. All business are will be in business table , all categories will be categories table and both table link will be business_x_categories.
Multible. Business have same categories. So we can link with same category and different business.


text:
Q: Open edebug window with predefined height in Emacs How can I open the edebug window in a given height? I know there is a window-resize function. But I am not sure if there is a hook that can be run after edebug has been activated.
Suppose I open Emacs with a file "t.txt" and then switch to *scratch* buffer and enter
(defun test ()
  (message "Hello"))

Then I instrument this function using C-u C-M-x (it calls edebug-defun), then switch to the t.txt buffer and type M-: (test) I then get following screen shot:

So by default, the edebug window splits the current window into two, one above the other, and activates in the lower window.
I would like to set a predefined height to this window..

A: Here's a piece of advice:
(defadvice edebug-pop-to-buffer (after edebug-advice activate)
  "Resize window."
  (set-window-text-height (get-buffer-window buffer) 5))


text:
Q: Why do we have $\operatorname{Supp}(\mathcal{O}_Y/\mathscr{K}_f)=\overline{f(X)}$? This comes up in the proof of Prop. 10.30 in Görtz-Wedhorn: if $f:X\rightarrow Y$ is a quasi-compact morphism of schemes, why do we have $\operatorname{Supp}(\mathcal{O}_Y/\mathscr{K}_f)=\overline{f(X)},$ where $\mathscr{K}_f$ denotes the kernel of $f^{\flat}:\mathcal{O}_Y\rightarrow f_*\mathcal{O}_X$?
So far, I only think that I can embed $\mathcal{O}_Y/\mathscr{K}_f$ into $f_*\mathcal{O}_X$ and then get an inlcusion $\operatorname{Supp}(\mathcal{O}_Y/\mathscr{K}_f)\subseteq\overline{f(X)}.$ But I don't see at the moment why we have an equality.


text:
Q: What is different with the writing in FileStream? When I searched the method about decompress the file by using SharpZipLib, I found lot of methods like this:
public static void TarWriteCharacters(string tarfile, string targetDir)
{
    using (TarInputStream s = new TarInputStream(File.OpenRead(tarfile)))
    {
        //some codes here

        using (FileStream fileWrite = File.Create(targetDir + directoryName + fileName))
        {
            int size = 2048;
            byte[] data = new byte[2048];
            while (true)
            {
                size = s.Read(data, 0, data.Length);
                if (size > 0)
                {
                    fileWrite.Write(data, 0, size);
                }
                else
                {
                    break;
                }
            }
            fileWrite.Close();
        }
    }
}

The format FileStream.Write is:

FileStream.Write(byte[] array, int offset, int count)

Now I try to separate part of read and write because I want to use thread to speed up the decompress rate in write function, and I use dynamic array byte[] and int[] to deposit the file's data and size like below
Read:
public static void TarWriteCharacters(string tarfile, string targetDir)
{
    using (TarInputStream s = new TarInputStream(File.OpenRead(tarfile)))
    {
        //some codes here

        using (FileStream fileWrite= File.Create(targetDir + directoryName + fileName))
        {
            int size = 2048;

            List<int> SizeList = new List<int>();
            List<byte[]> mydatalist = new List<byte[]>();

            while (true)
            {
                byte[] data = new byte[2048];
                size = s.Read(data, 0, data.Length);

                if (size > 0)
                {
                    mydatalist.Add(data);
                    SizeList.Add(size);
                }
                else
                {
                    break;
                }
            }
            test = new Thread(() =>
                FileWriteFun(pathToTar, args, SizeList, mydatalist)
            );
            test.Start();
            streamWriter.Close();
        }
    }
}

Write:
public static void FileWriteFun(string pathToTar , string[] args, List<int> SizeList, List<byte[]> mydataList)
{
    //some codes here

    using (FileStream fileWrite= File.Create(targetDir + directoryName + fileName))
    {
        for (int i = 0; i < mydataList.Count; i++)
        {
            fileWrite.Write(mydataList[i], 0, SizeList[i]);
        }
        fileWrite.Close();
    }
}

Edit

(1)byte[] data = new byte[2048] into while loop to assign data to new array.
(2)change int[] SizeList = new int[2048] to List<int> SizeList = new List<int>() because of int range

A: As read on a stream is only guarantied to return one byte (typically it will be more, but you can't rely on the full requested length each time), your solution can theoretically fail after 2048 bytes as your SizeList can only hold 2048 entries.
You could use a List to hold the sizes.
Or use a MemoryStream instead of inventing your own.
But the two main problems are:
1) You keep reading into the same byte array, overwriting previously read data. When you add your data byte array to mydatalist, you must assign data to a new byte array.
2) you close your stream before the second thread is done writing.
In general threading is difficult and should only be used where you know it will improve performance. Simply reading and writing data is typically IO bound in performance, not cpu bound, so introducing a second thread will just give a small performance penalty and no gain in speed. You could use multithreading to ensure concurrent read/write operations, but most likely the disk cache will do this for you if you stick to the first solution - amd if not, using async is easier than multithreaded to achieve this.


text:
Q: Adicionar parametro no final do link com jQuery Galera, estou tentando pegar algumas URL's especificas em uma página, e adicionar um parâmetro no fim do link, mas não estou obtendo sucesso, pois é retornado o objeto ao invés da string do link + o parâmetro.
Fiz um exemplo bem simples do código:
var links = jQuery('a[href*="google.com.br"]');
links.attr('href', links + 'parametros_adicionais');

A execução dessa código me retorna a URL com esse parâmetro no fim [object%20Object]test
Será que vocês podem me ajudar?

A: Links é um objeto que contem todos os elementos, deves percorrer os a[href*="google.com.br"] e mudar um de cada vez.

var param = 'SoUmParametro';
var src;
var links = jQuery('a[href*="google.com.br"]');
links.each(function() {
   src = $(this).prop('href');
   $(this).prop('href', src+param);
});

link1
link2

A: O correto seria assim:
var links = jQuery('a[href*="google.com.br"]');
links.attr('href', links.attr('href') + 'parametros_adicionais');

Lembrando que o código com Jquery deve estar sempre dentro de um "ready":
    $(document).ready(function(){
       var links = jQuery('a[href*="google.com.br"]');
       links.attr('href', links.attr('href') + 'parametros_adicionais');
    })


text:
Q: Is the use of the tense correct? I am not sure about the tenses in the following sentences. Is it the right choice?
1) I am originally from XYZ, studied XYZ in XYZ and will stay in XYZ until the end of March 2020.
( maybe 'have studied' or 'having studied' ? )
2) The last year I have been working in a XYZ company being responsible for XYZ in the northeasterly part of Poland.
(I am not working there anymore, so probably it has to be: 'I worked' ?)

A:
1) I am..., (I) studied…, (I) will stay...

The sentence is long, but all the tenses are correct.

2) I have been working in a XYZ company being
  responsible for XYZ in the northeasterly part of Poland.
(I am not working there anymore, so probably it has to be: 'I worked'
  ?)

Your instinct seems correct. It depends on how long ago, and whether you have since worked at another job.

A: In your second sentence, "have been working" is in the following tense:

Present Perfect Progressive: Present perfect progressive tense
  describes an action that began in the past, continues in the present,
  and may continue into the future. This tense is formed by using
  has/have been and the present participle of the verb (the verb form
  ending in -ing).

Since the action no longer "continues in the present"--it "was started and finished in the past"--the past tense "worked" (as you suggested) would be a correct alternative to the incorrect present perfect progressive tense ("have been working"). For more on verb tenses, click on the link below to view the reference cited.
https://leo.stcloudstate.edu/grammar/tenses.html
In your 1st sentence, either "studied" (past tense) or "have studied" (present perfect tense--"describes an action that happened at an indefinite time in the past or that began in the past and continues in the present") would be a correct choice (if the action--study--happened as indicated above).
OTOH, "having studied" is a perfect participle (having + past participle), so it is incorrect to use it as part of the compound predicate in your sentence. For more on that and its proper use, click on the following link:
https://learnenglish.britishcouncil.org/es/intermediate-grammar/participle-clauses
Also, see the comment section for other suggested edits to your sentence(s) that are unrelated to your specific questions regarding verb tense.
Have a good day.


text:
Q: Defining machine-independent datatypes in C++ Is there a way to do this?
#if sizeof(int) == 4
typedef unsigned int Integer32;
#else
typedef unsigned long Integer32;
#endif

or do you have to just #define integer size and compile different headers in?

A: If you need exact sizes you can use the intXX_t and uintXX_t variants, where XX is 8, 16, 32, or 64.
If you need types that are at least some size, use int_leastXX_t and uint_leastXX_t;
if you need fast, use int_fastXX_t and uint_fastXX_t.
You get these from <stdint.h>, which came in with C99. If you don't have C99 it's a little harder. You can't use sizeof(int) because the preprocessor doesn't know about types. So use INT_MAX (from <limits.h>, etc. to figure out whether a particular type is large enough for what you need.


text:
Q: Automator questions - Copying files to new location So I have some questions about the Automator.
I'm doing a fairly simple task with it and that's why it boggles my mind that it doesn't work. Always brings me the same info

*

*"The action "Filter Finder Items" was not supplied with the required data"

So what I'm doing is.

*

*I receive video files from a client.

*Download it to SERVER-1.

*If the video is pretty big, I compress it to make it smaller and choose a folder on SERVER-2.

*After the conversion has happened, I need to move the newly converted file to SERVER-3

I want Automator to understand that as soon as the file has been converted and placed on the desired folder on SERVER 2, to copy the file and place it on the corresponding folder on SERVER 3.

This is the action that I've made. The first one "Find Finder Items" seems pointless to me cause I'm already looking at that same folder with "Folder Action" but I tried it regardless if that could give the other two actions more data to perform their tasks correctly.
Also tried to use the "any content - Contains ***" for multiple things but nothing seems to be working.
Note, I have no background in coding or anything like that so it's a bit out of my wheelhouse to start writing codes but I guess that's the way to go since the actions from the action list are not doing what I need.
Could someone chime in and help me figure this out, receiving an insane amount of data and doing it all my hand is doing my head in.
Thanks in advance to anyone that can help me out here!


text:
Q: What is the language support across Windows 8 metro platforms? I am excited about the upcoming Microsoft Surface Tablet but I am confused by the differences between the tablet, phone and PC Windows 8/RT platforms.
I found the following API for developers:
http://msdn.microsoft.com/en-us/library/windows/apps/br211369.aspx
But is is not clear to me if all of these Javascript/C#/C++ are supported on the phone, tablet and PC.
If I want to use the provided Microsoft API to write an application that is compatible with a Windows 8 Tablet, phone and desktop computer do I just have to use the API for a Metro style app? Or are there further restrictions on languages and API features depending on the device?

A: I believe there will be differences in the API based on the device. I don't think it makes sense to have all APIs on all devices - for example all the mouse related events on a phone.
I think they seem to be creating different API profiles with a common subset and very similar looking programming model on each device - so that porting code across should be very easy - especially if it is designed with portability in mind.
For example, on the C# side, the .NET Portable libraries help in creating assemblies which are binary compatible across different versions of Windows on devices.

A: The Surface tablets are just really awesome Windows 8 PCs.  They won't require a specialized API set Though maybe there will be extra APIs available to get input from the fancy touch cover... I don't know they haven't said yet.  Likewise, they haven't given any useful details of how much Windows Phone 8 will have in common with Windows 8.  What we do know is that Windows Phone 7 is very much not compatible with Windows 8 - while many of the basics are the same between platforms, there are wide deviations in what APIs are available and how things work.
So on the desktop or Surface (which are the exact same platform), you can use Win8 APIs for Metro-style apps using JS, VB, C#, or C++.  On WP7, it's C# or VB only.  On WP8, it has been announced that we'll get the added option of C++ but not JS.


text:
Q: Android - "Method Call Expected" error when trying to build a singleton SQLiteOpenHelper New programmer here trying to self-learn, apologies for any stupid questions.
I'm trying to build a SQLite database with a singleton pattern in Android, so I can access the same DB through many different activities. I have the code below, but in the dbInstance = DatabaseHelper(context.getApplicationContext()); line, they have flagged an error "Method call expected".
I've searched google and this site, but it seems like this error can be triggered for a variety of reasons, and I wasn't able to figure out what's wrong in my case.
private static class DatabaseHelper extends SQLiteOpenHelper{

    private static DatabaseHelper dbInstance = null;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static DatabaseHelper getInstance(Context context) {
        synchronized(DatabaseHelper.class) {
            if(dbInstance == null) {
                dbInstance = DatabaseHelper(context.getApplicationContext());
            }
        }

        return dbInstance;
    }

Appreciate all of your help in advance!

A: Should be
dbInstance = new DatabaseHelper(context.getApplicationContext());


text:
Q: How to make tooltipsy staying so a link in it can be clicked I have the jQuery plugin Tooltipsy to generate a tooltip for a link. In this tooltip I have other links to related objects. I would like it to pop up just above the initial link and stay if I move the mouse to it to click a link. Is this possible? Does anyone know how to do it?

A: I didn't manage to get it to stay open and couldn't wait any longer so I changed to another tooltip plugin called simpletip that provided the functionality that I needed.
Simpletip could not get the title attribute from the links by itself so this is the code I used to achieve that. EDIT: I changed the code to take data-title (HTML5 compliant) instead for title so that I didn't have to block all titles from default showing:
$(".order_tooltip").simpletip({
    fixed: true,
    position: 'top',
    onBeforeShow: function(){
        this.update(this.getParent().data('title'));
    }
});

A: You can put a close button in the tooltip and make the tooltip hide on click of the close button.
The hide function on the tooltip can be invoked as explained at http://tooltipsy.com/methods.html#method-hide

A: To directly answer your original question, this worked for me:
var hoverHand = false;

    $('.hastip').tooltipsy({
            show: function (e, $el) {
                $el.hover( function() {
                    hoverHand = true;
                }, function() {
                    hoverHand = false;
                });
                $el.fadeIn(100);
            },
            hide: function (e, $el) {
                var tooltipCloserInterval = setInterval(function(){
                    if (hoverHand == false) {
                        $el.fadeOut(100);
                        $el.off( "mouseenter mouseleave" );
                        clearInterval(tooltipCloserInterval);
                    }
                }, 500);
            }
        });

Essentially, you are giving the user 500ms to move their mouse onto the tooltip using setInterval. After 500ms it is checking if the mouse is still over the tooltip, and if it is not, the tooltip is closed.


text:
Q: "the following August" vs. "in the following August"?

*

*She completed writing her first novel the following August.

Is grammatically known, months name are preceded by the preposition "in"
Why , in this sentence, the preposition "in" is not included?
To be formed like:
She completed writing her first novel in the following August.

A: Because these relative prepositions take the place of "in." For example:

She finished writing her novel in August.

(Which August? Depends on the context.)

She finished writing her novel last August.
She will finish writing her novel next August.

When the month is followed by a prepositional phrase, however, "in" remains:

She finished writing her novel in August of 2016.

This is also generally true for days of the week and the preposition "on."


text:
Q: Getting a Login Timeout Expired: A network related or instance specific... While trying to export data from one server to another I am trying to export data from a table in a server to another server that has the same table. The table contains about 500 Million records, Generating a script requires memory that our server doesnt seem to have since it gives us an error midway. I was trying to use the export data wizard tool. I chose native client 11.0 as the source and specified the server. But when i specify the the destination server it gives me an error.
Login timeout expired: A network related or instance specific error has occured while establishing a connection to the server. Server is not found or accessible...
I am also worried I might have to deal with duplicate data if I use this tool.
Is there a way I can copy/backup/restore a specific table in SQL server and simply restore it on the other server?
I am looking for the most efficient solution to this.
Thank you for your help.


text:
Q: Is there a way to find out the gateway of a mobile network connection? Hi I want to read details on mobile network connection, like ip adress, dns servers etc. and the GATEWAY which the network normally uses to send data to the internet. Since this is a TCP/IP connection there has to be one. So I tried to find solutions or examples to find out the Gateway of a mobile network connection (Not Wifi!!!!).
Under API Level 21 there exists LinkProperties, but my Library will not be used by tablets and smartphones having this min SDK.
So under LOLLIPOP I do have this solution
if (Utils.hasLollipop()) {
                LinkProperties linkProperties = connectivityManager.getLinkProperties(mobileNetwork);

                if (linkProperties != null) {
                    List<InetAddress> dnsServers = linkProperties.getDnsServers();

                    for (InetAddress dns : dnsServers) {
                        if (!status.getmDNS().contains(dns.getHostAddress())) {
                            status.getmDNS().add(dns.getHostAddress());
                        }
                    }

                    List<RouteInfo> routeInfos = linkProperties.getRoutes();

                    if (routeInfos != null && routeInfos.size() > 0) {
                        for (RouteInfo i : routeInfos) {
                            if (i.getGateway() != null) {
                                status.setmGateway(i.getGateway().getHostAddress());
                                break;
                            }
                        }
                    }
                }
            } else {
              ... Solution for devices API Level < 21
            }

Do anybody has an Idea what i can do?!
Thanks ;D
EDIT:
According to the comments of the answer from "Lance Preston", I did write an example code. If there is any other way, or if you have any bugfixes just let us know.
private static final String ipv4Pattern = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
private static final String interfacePattern = "\\s*dev\\s*";
private static final String defaultGatewayPattern = "default\\s*via\\s*";
private static final String noCapturingPattern = "(?:%s)";

public static List<String> getGateways(String interfaceName) {
    try {
        List<String> gateways = new ArrayList<>();
        Pattern defaultpattern = Pattern.compile(String.format(noCapturingPattern, defaultGatewayPattern) + "(" + ipv4Pattern + ")" + String.format(noCapturingPattern, (interfacePattern + interfaceName)));
        Pattern ipAddressPattern = Pattern.compile(String.format(noCapturingPattern, ipv4Pattern + "\\s*via\\s*") + "(" + ipv4Pattern + ")" + String.format(noCapturingPattern, (interfacePattern + interfaceName)));
        Process result = Runtime.getRuntime().exec("ip route show");
        BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
        String line = output.readLine();

        while (line != null) {
            if (!line.isEmpty()) {
                Matcher defaultMatcher = defaultpattern.matcher(line);
                if (defaultMatcher.find() && defaultMatcher.groupCount() == 1) {
                    String gatewayAddress = defaultMatcher.group(1);
                    if (gatewayAddress != null && !gatewayAddress.isEmpty() && !gateways.contains(gatewayAddress)) {
                        gateways.add(gatewayAddress);
                    }
                }

                Matcher ipAddressMatcher = ipAddressPattern.matcher(line);
                if (ipAddressMatcher.find() && ipAddressMatcher.groupCount() == 1) {
                    String gatewayAddress = ipAddressMatcher.group(1);
                    if (gatewayAddress != null && !gatewayAddress.isEmpty() && !gateways.contains(gatewayAddress)) {
                        gateways.add(gatewayAddress);
                    }
                }
            }
            line = output.readLine();
        }

        return gateways;

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

    return null;
}

A: This linux command can lend some Gateway info - netstat -r -n or ip route show
You can then parse the output of ip route show along the lines of default via xxx.xxx.xxx.xxx
This will help you out.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

TextView tv;
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.out);
    et = (EditText) findViewById(R.id.txt);

    String [] res = executeInShell("ip route show").split("\n");
    String gatewayInfo [] = res[0].split(" ");

    et.setText("ip route show");
    et.setSelection(et.getText().length());

    tv.setText(gatewayInfo[2].toString());

    Log.d("Response", executeInShell("ip route show"));

}

public static String executeInShell(String command) {

        StringBuffer output = new StringBuffer();

        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        String response = output.toString();
        return response;

   }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20sp"
    android:gravity="center"
    android:textAlignment="center"
    android:text="Get My Gateway" />
<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/txt" />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/out"
    android:gravity="center_horizontal" />

Response from LogCat

Screenshot from device


text:
Q: How can I navigate from custom class to UIViewController in Swift 4 I have a ViewController which have a button, it calls some method in MyClass.swift. I'm trying to navigate from MyClass.swift to UIViewController MainViewController when I press that button. I implemented this method and I get "navigating..." in the log but nothing happen.
class Myclass {
// some code ...
func someFunc() {

    // some code ...
    navigateToMainViewController()

}

func navigateToMainViewController() {
    let storyboard: UIStoryboard? = UIApplication.shared.keyWindow?.rootViewController?.storyboard
    if let myMVC = storyboard?.instantiateViewController(withIdentifier: "MainViewController") {
        print("navigating....")
        let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
        navController?.pushViewController(myMVC, animated: true)
    }else {
        print("Something wrong..")
    }
}

// some code ...
}

Thank your for your help.

A: Change your navigation Function and add a parameter of viewController to it, and take a variable in myClass of type UIViewController:
var viewController: UIViewController!

func someFunc(_ viewController: UIViewController) {
    self.viewController = viewController
    self.navigateToMainViewController()
}

func navigateToMainViewController() {
  let storyboard: UIStoryboard? = UIApplication.shared.keyWindow?.rootViewController?.storyboard
  if let myMVC = storyboard?.instantiateViewController(withIdentifier: "MainViewController") {
      print("navigating....")

      self.viewController.navigationController?.pushViewController(myMVC, animated: true)
  }else {
      print("Something wrong..")
  }
}

Then From viewController, Call someFunc() with instance of ViewController:
class ViewController: UIViewController {
    @IBAction func buttonPressed(_ sender: UIButton) {
          myClassObject.someFunc(self)
    }
}


text:
Q: What is the optimal way to use setInterval in jquery ajax calls? I am using JQWidgets to create a pie chart. And while that is all fine and dandy and working like a charm. What I'd like to do however is update the data every x number of seconds. Using jQuery, here is the code that I have so far:
function loadChart(id,name){
   //chart loads here
   var speed = 5000,
       t = setInterval(reloadData,speed);
   function reloadData() {
        source.url = 'data.php?id='+id;
        var dataAdapter = new $.jqx.dataAdapter(source);
        $('#pie').jqxChart({ source: dataAdapter });
        console.log('reloading pie...'+globalPieId);
        speed = 5000;
        clearInterval(t);
        t = setInterval(reloadData, speed);
    }
}

My issue is, that if the loadChart function is called, another instance of setInterval is created, and after three or four times, the chart is in a constant state of refresh. How do optimize my setInterval call so that only one instance is called?
Thanks in advance.

A: Instead of using setInterval which calls the function over and over again you would be better off using the setTimeout function which will call the callback you specify just once. Once that callback is called you can once again call setTimeout and you'll stop having the problems you're having right now. Also you'll wait until the last call is done before you start doing another one which is also good. The code might look something like this with the change:
function loadChart(id,name){
   //chart loads here
   var speed = 5000,
       t = setTimeout(reloadData,speed);
   function reloadData() {
        source.url = 'data.php?id='+id;
        var dataAdapter = new $.jqx.dataAdapter(source);
        $('#pie').jqxChart({ source: dataAdapter });
        console.log('reloading pie...'+globalPieId);
        speed = 5000;
        t = setTimeout(reloadData, speed);
    }
}

For a working poc you could see http://jsfiddle.net/9QFS2/

A: You need to clear existing interval before you set up a new one. Try the following trick.
function loadChart(id, name) {
    // We use a trick to make our 'interval' var kinda static inside the function.
    // Its value will not change between calls to loadChart().
    var interval = null;

    // This is the core of a trick: replace outer function with inner helper
    // that remembers 'interval' in its scope.
    loadChart = realLoadChart;
    return realLoadChart(id, name);

    function realLoadChart(id, name) {
        var speed = 5000;

        // Remove old interval if it exists, then set up a new one
        interval && clearInterval(interval);
        interval = setInterval(reloadData, speed);

        function reloadData() {
            // ... your code, but no do nothing with interval here ...
        }
    }
}


text:
Q: Fetching data from an API works locally but not live First time building a site with Nuxt.js and I'm requesting data from an API that works great locally but when I access the site through Netlify, none of the code seems to run. I'm assuming this has something to do with my misunderstanding of how static sites work.
What I'm trying to do is check if there is a browser cookie, if not create one and fetch the API to get the user's general location and check their city against an array of cities in NY.  If there is a match then close the v-banner.  If there is already a browser cookie then close the v-banner.
Abridged index.vue:
<template>
    <v-app v-bind:class="{ alertOpen: alertOpen }">
        <v-main>
            <v-banner
                class="state-alert"
                transition="slide-y-transition"
                v-bind:class="{ alertOpen: alertOpen }"
            >
                By our calculations, it looks like you might be visiting our website from outside of New York. Unfortunately at this time, we can't sell our Granola outside of New York. If you are buying a gift for someone with a New York address then please proceed.
                <template>
                    <v-btn
                        icon
                        color="alert"
                        v-on:click="alertOpen = false"
                    >
                        <v-icon>mdi-close</v-icon>
                    </v-btn>
                </template>
            </v-banner>
        </v-main>
    </v-app>
</template>

<script>
    let nyList = ['Albany', 'Amsterdam', 'Auburn', 'Batavia', 'Beacon', 'Binghamton', 'Buffalo', 'Canandaigua', 'Cohoes', 'Corning', 'Cortland', 'Dunkirk', 'Elmira', 'Fulton', 'Geneva', 'Glen Cove', 'Glens Falls', 'Gloversville', 'Hornell', 'Hudson', 'Ithaca', 'Jamestown', 'Johnstown', 'Kingston', 'Lackawanna', 'Little Falls', 'Lockport', 'Long Beach', 'Mechanicville', 'Middletown', 'Mount Vernon', 'New Rochelle', 'New York', 'Newburgh', 'Niagara Falls', 'North Tonawanda', 'Norwich', 'Ogdensburg', 'Olean', 'Oneida', 'Oneonta', 'Oswego', 'Peekskill', 'Plattsburgh', 'Port Jervis', 'Poughkeepsie', 'Rensselaer', 'Rochester', 'Rome', 'Rye', 'Salamanca', 'Saratoga Springs', 'Schenectady', 'Sherrill', 'Syracuse', 'Tonawanda', 'Troy', 'Utica', 'Watertown', 'Watervliet', 'White Plains', 'Yonkers'];

    export default ({
        head() {
            return {
                script: [{
                    body: true
                }]
            }
        },
        data() {
            return {
                geoData: [],
                alertOpen: true
            }
        },
        async fetch() {
            const locationCookie = this.$cookies.get('location-cookie');

            if(!locationCookie) {
                console.log('no cookie');
                this.$cookies.set('location-cookie', 'true', {
                    path: '/',
                    maxAge: 31556952
                });
                this.geoData = await fetch(
                    'https://ipgeolocation.abstractapi.com/v1/?api_key=1eef312cdda9428cac26815c9d3bdd26'
                ).then(res => res.json());

                var vm = this;
                compareCity(this.geoData.city);

                function compareCity(city) {
                    var i;
                    for(i = 0; i < nyList.length; i++) {
                        if(nyList[i].toLowerCase().replace(/\s/g, '') == city.toLowerCase().replace(/\s/g, '')) {
                            console.log(city);
                            vm.alertOpen = false;
                        }
                    }
                }
            } else {
                console.log('yes cookie');
                this.alertOpen = false;
            }
        }
    });
</script>

Not sure if ya'll also need to see the nuxt.config.js:
export default {
    mode: "universal",

    // Global page headers (https://go.nuxtjs.dev/config-head)
    head: {
        title: 'homemade-crunch',
        meta: [
            { charset: 'utf-8' },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' },
            { hid: 'description', name: 'description', content: '' }
        ],
        link: [
            { rel: "preconnect", href: "https://app.snipcart.com" },
            { rel: "preconnect", href: "https://cdn.snipcart.com" },
            { rel: 'stylesheet', href: 'https://cdn.snipcart.com/themes/v3.0.23/default/snipcart.css', defer: true },
            { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Anton&family=Open+Sans&display=swap' }
        ],
        script: [
            { src: "https://cdn.snipcart.com/themes/v3.0/default/snipcart.js", defer: true }
        ]
    },

    // Global CSS (https://go.nuxtjs.dev/config-css)
    css: [
    ],

    // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
    plugins: [
        '@plugins/vuetify'
    ],

    // Auto import components (https://go.nuxtjs.dev/config-components)
    components: true,

    // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
    buildModules: [],

    // Modules (https://go.nuxtjs.dev/config-modules)
    modules: [
        'vue-scrollto/nuxt',
        'cookie-universal-nuxt'
    ],

    // Build Configuration (https://go.nuxtjs.dev/config-build)
    build: {
    },

    server: {
        port: 3333,
        host: '0.0.0.0'
    }
}

The git repo: https://github.com/mat148/Homemade-crunch
and live site: https://www.homemadecrunch.com/
Let me know if I've forgotten something or done something silly.
Any help would be greatly appreciated.
Thank you!

A: I decided to move my logic from the index.vue to a javascript file


text:
Q: Using tf.shape causes an error I have the following simple code in TensorFlow:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)
t1, t2 = size

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    res = sess.run(size, feed_dict = {a: np.random.randn(3, 4)})

t1

but it does not work. I want to have the shape of the tensor, a.shape works fine but the point is that it gets None for the second dimension. I searched and got that for knowing its value I have to use tf.shape(a), but now the problem is that I searched and figured out that python does have any idea what is in the tensor object. I just want to retrieve the values in two variables. The point is that I have to use this code in a more complicated code and these sizes are the marginal part of a larger computation. Is there anyway to get those numbers as integers without running the session for them separately?
I have to say that I know the following variant of my code wroks:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = a.shape.as_list()
print(type(size))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    res = sess.run(c, feed_dict = {a: np.random.randn(3, 4)})
    print(res)
    print(size)

but It gets None as the second element of shape. Consequently I have to use tf.shape. Those folks who insist that my question is duplicate, I ran the suggestion here and get the following result which still consists of None:

(3, ?)

A: Does this help? It's not very general but since I don't know what exactly you're trying to achieve, it might be enough.
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)
t1 = size[0]
t2 = size[1]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    res = sess.run([t1, t2], feed_dict = {a: np.random.randn(3, 4)})
    print(res)

Alternative:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    t1, t2 = sess.run(size, feed_dict = {a: np.random.randn(3, 4)})
print(t1, t2)