Deserialize jackson with abstract Type

I'm a beginner in java so i'm not really sure if the title is right but i've been trying to unmarshal a json string of which i won't know the type in advance.

  public interface Dummy<T>  {
      T unmarShall(String item);
  }

  abstract class  DummyAbstract implements Dummy<T> {

      protected T unmarShall(String item){
          ObjectMapper mapper = new ObjectMapper();

          try {
              T objectx = mapper.readValue(item, T);
              return objectx;
          }
      }

      }

  }

As this method is expecting a Class as the second parameter

              T objectx = mapper.readValue(item, T);
              return objectx;

I've been reading about how to do this but can't really find a proper way to do this.

I would only call this method from an subclass like :

   public class DummyImpl extends DummyAbstract<MyClass>{
   }

I've been doing it with the class hardcoded into the implementation for now but that not DRY at all..

could that be done ?


How to create reusable WPF grid layout

I have a window with tab control and number of pages - tab items. Each tab item has same grid layout - 6 rows and 4 columns. Now, each tab item contains grid with row and column definitions, so almost half of XAML is definition of grids.

How can I define this grid in one place and reuse that definition in my application? Template? User control?

Besides 6x4, I have only two more grid dimensions that repeat: 8x4 and 6x6.

Edit:

Forgot to mention: controls in grid are different for each tab. I just want to have grid defined once in some resource so that I can reuse them on different tab pages. Now XAML looks like this:

    <TabControl>
        <TabItem Header="Property">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <!-- some controls here -->
            </Grid>
        </TabItem>
        <TabItem Header="Style">
            <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <!-- some controls here -->
            </Grid>
        </TabItem>

       ... and this repeats for several more tab items

    </TabControl>

This grid definition repeats for each tab item on the form. It annoys me that half of XAML is grid definition.

Is there a way to define this grid at one place and then reuse that definition?


Redirect a form submit with ajax

I want to send form responses to a Google sheet and then redirect the user to a thank you page. The Google script redirects the user directly to a report page. I want to drop the google redirect and place mine.

Form:

<form method="post" id="formID" action="gscript">
...
</form>

Script:

<script>
   $(document).on('submit', '.formID', function(e) {
     $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(html) {
        alert('ok');
        window.location("Thanks page link");
        }
    });
    e.preventDefault();

});
</script>


Sampling on Yahoo! Answers

I wonder what is the best way to sample,say, 1000 questions,completely randomly from Yahoo! Answer.
I want to achieve this complete randomness in which I will totally ignore the categories or date of posting etc.
Doing this manually may result in bias,so could anyone give some suggestions here,like using Yahoo! Answer API or sth.
Thanks a lot.


How does Unity3D set its icon on linux

When I start a Unity3D program on Linux (not via desktop launcher), the program has an icon. As far as I was told, a program entry would only get an icon, when launched via desktop launcher.
Seems like Unity3D found a way to do it differently. Does anyone know how it works?


Set Calendar to next Thursday

I'm developing an app in Android which have a service that must be executed every Thursday and Sunday at 22:00

What I do need, is to set a Calendar to that day and time. However, I'm not sure about how to do it.

Calendar calendar = Calendar.getInstance();

This is giving me a calendar with the current date and time.

I know I can add days, minutes, hours, etc. But, is there any way to directly setNext("thursday")?

I don't want to do many maths there. I mean I'm looking for an answer which doesn't need to calculate how many minutes/hours/days are left till next thursday.

Thank you!!


How do I create a checkbox in iOS Titanium?

How would I create a checkbox with Titanium for iOS?


Jquery windows.open

Hello StackOverflow community,

I'm completely new to jQuery, so I'm learning as I go. I'm having some difficulty getting the "window.open" to display any information when clicked.
Currently, it will open a new tab, but only shows "Blank" in the URL.  Within the database, there is an HTML tag:

<a id="1" href="javascript://"class="dsDetail">Test</a>

that calls dsDetail:

jQuery("body").on('click', '.dsDetail', function () {
        //  alert('works');
        searchText = jQuery(this).attr("id");
        //  alert(searchText);
        window.open(displayDetails(searchText));
    });

If I remove the "window.open()" and just leave "displayDetails(searchText)" it will show the correct data, but only on the current page. How can I get the dsDetail function to display its content in a new tab?

Additionally, the 'displayDetails' function is this:

function displayDetails(searchText) {
        var jqxhr = jQuery.ajax("index.php?option=com_ppsearchusd&view=ppsearchusd&task=displayDetail&format=json&searchText=" + searchText)
        .success(function (result) {
            //      var obj = jQuery.parseJSON(result);
            //  alert(result.data.HTML);
            jQuery('#searchResult-detail').html(result.data.HTML);
            jQuery('#searchResult-detail').css('display', 'block');
            jQuery('#alphaDiv').css('display', 'none');
            jQuery('#searchResults').css('display', 'none');
        })
        .fail(function (jqxhr) {
            alert('status:' + jqxhr.status);

        });
}


datagridview example for sale entry form

i want to make simple sale entry form,
first i want to ask invoice number and customer name, then
next details of sale entry i want add using datagridview, like:

sr.no---Product Name------Price---qty---total

1       Item 1            150.00  2     300.00
2       Item 2            80.00   3     240.00

above details i want to add using datagridview in editable rows, but with proper validation.

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
   dataGridView1.CurrentRow.Cells["l_sr"].Value = "1";
}

can you help for this


How do I create a keybinding (Ctrl + O) in Kivy?

I'm wanting to create a keybinding in Kivy (Ctrl + O) that I can attach an event to. I see that the Kivy Inspector module is doing something similar but I'm not sure how to replicate the functionality.

I'd like to have the keybinding work on all of the Kivy application so I guess that it must bind to the window/root widget.

Has anyone done this before? Thanks!


Classes.dex file size increased after ionic framework updated

I have created an app using Ionic framework and for the first time the apk file size was 2.5mb and to add the google analytics plugin I have update the ionic framework and after that the file size increased to 3.7mb I'm sure that nothing is changed or added other than GA plugin. I have extracted the apk and identified that the classes.dex file size is 3.4mb before it was 900kb.

Does anyone have any clue on why the file size is increased?


I am trying to run simple app engine guestbook app modified for Spring
I am running od InteliJ IDEA

Since it is AppEngine, I need to run on JAVA 7
When I am compiling with Java 8 compiler, I have no problem. However when compiling with Java 7, I get this:

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.test.context.web.WebDelegatingSmartContextLoader]: Constructor threw exception; nested exception is java.lang.UnsupportedClassVersionError: javax/servlet/ServletContext : Unsupported major.minor version 52.0
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:125)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.resolveContextLoader(AbstractTestContextBootstrapper.java:474)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:359)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:305)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:250)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.UnsupportedClassVersionError: javax/servlet/ServletContext : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.springframework.test.context.web.WebDelegatingSmartContextLoader.<init>(WebDelegatingSmartContextLoader.java:63)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
    ... 32 more

Here is my Pom

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>0.1-SNAPSHOT</version>

<groupId>XXXXX</groupId>
<artifactId>XXXXX</artifactId>

<properties>
    <app.id>XXXXX</app.id>
    <app.version>1</app.version>
    <appengine.version>1.9.46</appengine.version>
    <gcloud.plugin.version>2.0.9.74.v20150814</gcloud.plugin.version>

    <objectify.version>5.1.13</objectify.version>
    <guava.version>20.0</guava.version>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
    <spring.framework.version> 4.3.4.RELEASE</spring.framework.version>
    <jackson.version>2.8.5</jackson.version>
    <javax.servlet.api.version>4.0.0-b01</javax.servlet.api.version>

    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
</properties>

<prerequisites>
    <maven>3.1.0</maven>
</prerequisites>

<dependencies>
    <!-- Compile/runtime dependencies -->
    <dependency>
        <groupId>com.google.appengine</groupId>
        <artifactId>appengine-api-1.0-sdk</artifactId>
        <version>${appengine.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet.api.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- [START Spring Dependencies] -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>
    <!-- [END Spring Dependencies] -->

    <!-- [START Objectify_Dependencies] -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>${guava.version}</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.objectify</groupId>
        <artifactId>objectify</artifactId>
        <version>${objectify.version}</version>
    </dependency>
    <!-- [END Objectify_Dependencies] -->

    <!-- Test Dependencies -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>2.0.2-beta</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.appengine</groupId>
        <artifactId>appengine-testing</artifactId>
        <version>${appengine.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.appengine</groupId>
        <artifactId>appengine-api-stubs</artifactId>
        <version>${appengine.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.framework.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <!-- for hot reload of the web application-->
    <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>versions-maven-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>display-dependency-updates</goal>
                        <goal>display-plugin-updates</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <version>3.6</version>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <compilerVersion>1.7</compilerVersion>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <archiveClasses>true</archiveClasses>
                <webResources>
                    <!-- in order to interpolate version from pom into appengine-web.xml -->
                    <resource>
                        <directory>${basedir}/src/main/webapp/WEB-INF</directory>
                        <filtering>true</filtering>
                        <targetPath>WEB-INF</targetPath>
                    </resource>
                </webResources>
            </configuration>
        </plugin>

        <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>${appengine.version}</version>
            <configuration>
                <enableJarClasses>false</enableJarClasses>
                <version>${app.version}</version>
                <!-- Comment in the below snippet to bind to all IPs instead of just localhost -->
                <!-- address>0.0.0.0</address>
                <port>8080</port -->
                <!-- Comment in the below snippet to enable local debugging with a remote debugger
                     like those included with Eclipse or IntelliJ -->
                <!-- jvmFlags>
                  <jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
                </jvmFlags -->
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>gcloud-maven-plugin</artifactId>
            <version>${gcloud.plugin.version}</version>
            <configuration>
                <set_default>true</set_default>
            </configuration>
        </plugin>
    </plugins>

    <testResources>
        <testResource>
            <directory>${basedir}/src/main/webapp</directory>
        </testResource>
    </testResources>
</build>

My JAVA_HOME is iset to Java7, inside project structure Project SDK is defined for Java7.
JDK for maven importer is Java77, JRE for maven runner is set to Project JDK

Can you please tell me how it is possible that I get this error, even if I have everything set to Java 7? And also how to fix it :)

Thanks


Can Short2 be used on WP7 for vertex positions?

I'm having trouble using Short2 for the (x,y) positions in my vertex data.  This is my vertex structure:

struct VertexPositionShort : IVertexType
{
    private static VertexElement[]
        vertexElements = new VertexElement[]
        {
            new VertexElement(0, VertexElementFormat.Short2, VertexElementUsage.Position, 0),
        };
    private static VertexDeclaration
        vertexDeclaration = new VertexDeclaration(vertexElements);

    public Short2
        Position;

    public static VertexDeclaration Declaration
    {
        get { return new VertexDeclaration(vertexElements); }
    }

    VertexDeclaration IVertexType.VertexDeclaration
    {
        get { return new VertexDeclaration(vertexElements); }
    }
}

Using the WP7 emulator, nothing is drawn if I use this structure - no artifacts, nothing!  However, if I use an identical structure where the Short2 structs are replaced by Vector2 then it all works perfectly.

I've found a reference to this being an emulator-specific issue: "In the Windows Phone Emulator, the SkinnedEffect bone index channel must be specified as one of the integer vertex element formats - either Byte4, Short2, or Short4. This same set of integer data formats cannot be used for other shader input channels such as colors, positions, and texture coordinates on the emulator."  (http://www.softpedia.com/progChangelog/Windows-Phone-Developer-Tools-Changelog-154611.html)  However this is from July 2010 and I'd have assumed this limitation has been fixed by now...?  Unfortunately I don't have a device to test on.

Can anyone confirm that this is still an issue in the emulator or point me at another reason why this is not working?


Windows Phone App 7.5 - 8.0 migration: Resuming... screen is infinitive

After migrating windows phone application from 7.5 to 8.0, it starts showing "Resuming" screen infinitely after hitting windows button first and after that back button on one of the page.
Can anybody help please how to troubleshoot this problem?


Get direct url of youtube video

I wonder how to get the direct url of youtube video. For example, when i analyzed the video code of https://www.youtube.com/watch?v=OrTyD7rjBpw

i found some URLs inside the js code of the player, like <a href="https://r6---sn-w511uxa-cjoe.googlevideo.com/videoplayback?mt=1440164084&mv=m&ms=au&mm=31&mn=sn-w511uxa-cjoe&upn=ELDhWOVFRzM&id=o-AM6zxCNJwi5l5gjbq_262NpEnieXQ2iQTkGLLDieVKs4&ip=188.77.186.165&sparams=dur%2Cgcr%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&fexp=3300113%2C3300134%2C3300137%2C3300164%2C3310699%2C3312381%2C3312531%2C9407535%2C9408710%2C9409069%2C9412877%2C9413010%2C9414935%2C9415365%2C9415417%2C9415485%2C9416023%2C9416105%2C9416126%2C9416522%2C9417353%2C9417707%2C9418060%2C9418153%2C9418203%2C9418449%2C9419675&dur=0.000&initcwndbps=1298750&pl=20&ratebypass=yes&source=youtube&gcr=es&pcm2cms=yes&requiressl=yes&expire=1440185744&mime=video%2Fwebm&key=yt5&ipbits=0&lmt=1365511426344921&sver=3&itag=43" rel="nofollow">https://r6---sn-w511uxa-cjoe.googlevideo.com/videoplayback?mt=1440164084&mv=m&ms=au&mm=31&mn=sn-w511uxa-cjoe&upn=ELDhWOVFRzM&id=o-AM6zxCNJwi5l5gjbq_262NpEnieXQ2iQTkGLLDieVKs4&ip=188.77.186.165&sparams=dur%2Cgcr%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&fexp=3300113%2C3300134%2C3300137%2C3300164%2C3310699%2C3312381%2C3312531%2C9407535%2C9408710%2C9409069%2C9412877%2C9413010%2C9414935%2C9415365%2C9415417%2C9415485%2C9416023%2C9416105%2C9416126%2C9416522%2C9417353%2C9417707%2C9418060%2C9418153%2C9418203%2C9418449%2C9419675&dur=0.000&initcwndbps=1298750&pl=20&ratebypass=yes&source=youtube&gcr=es&pcm2cms=yes&requiressl=yes&expire=1440185744&mime=video%2Fwebm&key=yt5&ipbits=0&lmt=1365511426344921&sver=3&itag=43

But it doesn't redirect to the youtube video, so i'm thinking that code is more obfuscated


Android app encoding problem - not display ÅÄÖ properly

When user enters a value 'Nedskräpning' in a EditTextbox, it is saved as 'NedskrÃ¤pning' in the database. So I am assuming this error is generated from the Android part of the application. UPDATE: <-- probably false assumption?

 <EditText android:id="@+id/commentTextBox"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent"
                android:layout_weight="1"/>

The java code:

commentTextBox = (EditText) findViewById(R.id.commentTextBox);
crapport.setComment(commentTextBox.getText().toString());

Then this crapport is saved in the database.

Any tips on how to solve this?

UPDATE: This is my Apache CXF webservice:

  @Path("/crapportService/")
public class CrapportServiceImpl implements CrapportService {

    @Autowired
    private CrapportController crapportController;

    @Override
    @Path("image")
    @POST
    @Produces(MediaType.TEXT_HTML)
    public String addReport(MultipartBody multipartBody) {

        List<Attachment> attachmentList = new ArrayList<Attachment>();
        attachmentList = multipartBody.getAllAttachments();

        if (attachmentList.size() == 0){
            return "No attachments";
        }

        try {
            crapportController.processReportFromClient(attachmentList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "Error: FileNotFoundException";
        } catch (NullPointerException e) {
            return "Error: NullPointerException";
        } catch (IOException e) {
            return "Error: IOException";
        }

        return "Success";
    }

}


DataContractSerializer - serialize string as value and not reference

I use DataContract serializer to serialize my data. I use PreserveObjectReferences = true because I need it.
I have two objects for example:

[Datacontract]
class A
{
  [DataMember] string _name;
  ...
  public A(string name)
  {
    _name = name;
  }
}

and

[Datacontract]
class B
{
  [DataMember] string _name;
  ...
  public B(string name)
  {
    _name = name;
  }
}

Both have _name field.
Then I create instance of A and B where I use as a name of the second object the same name from object A:

var obj1 = new A("John");
var obj2 = new B(obj1.Name);

Then I serialize it, and XML contains:

...
<d11p1:_name z:Id="505">John</d11p1:_name>
..
<d11p1:_name z:Ref="505" i:nil="true" />

So the field _name of the second object is serialized as reference and not Value.

Then I don't need object A so I delete it. But I want to be abble to open an old saved file which contains data from class A, but in the new version of my program I don't need class A anymore.

The problem is that DataContractSerializer cannot deserialize instance of B because its _name is a reference to _name of A which is not deserialized (class is deleted).

Is there any way to force DataContractSerializer to serialize a string as Value type instead of reference?

I know that one solution is not to delete class A but it contains a lot of data which isn't important in the new version of my program.


Why is GPUImage slower than CPU calculation when calculating average color of image?

In my project I am trying to get the average color of a series of UIImage objects. So I implemented a category UIImage(AverageColor) to calculate the average color.

Here's how I do it with the GPUImage library:

- (void)averageColor:(void (^)(UIColor *))handler {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:self];
        GPUImageAverageColor *averageColorFilter = [GPUImageAverageColor new];
        [averageColorFilter setColorAverageProcessingFinishedBlock:^(CGFloat r, CGFloat g, CGFloat b, CGFloat a, CMTime frameTime) {
            UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a];
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(color);
            });
        }];

        [picture addTarget:averageColorFilter];
        [picture useNextFrameForImageCapture];
        [picture processImage];
    });
}

I've also tried the approach (pure CPU one I think?) in this answer. Then I test these two methods with the same UIImage and log out the time used in each methods. And here's the result:

cpu time: 0.102402

gpu time: 0.414044

I am surprised that the CPU one runs much faster. So what's the problem here? Am I using GPUImage in a wrong way?

Edit:

The above result was got from iOS simulator. When testing on real device (iPhone6s) the difference is even greater:

cpu time: 0.019034

gpu time: 0.137635


what value will have property of my object?

Hi in my opinion property of my object shouold be 2, but after this code, is still 1, why?

internal class Program
{
    private static void Main(string[] args)
    {
        MyClass value = new MyClass() { Property = 1 };

        value.Property = value.Property++;
        Console.WriteLine(value.Property);
        Console.ReadKey();
    }
}

internal class MyClass
{
    public int Property;
}

in my opinion this should value.Property = value.Property++; first put to value what is in value and the increment property of this object, why id doesn't work?


Not able to login while using Opera Mobile created using Jquery

While using Opera mobile browser my login page i can enter data in username and passwd fields but not able to fire any event so that i can direct the application to another page.

Same app is working fine with Android browser. A 'Go' key appears on it while entering the data, on pressing that key it fires ENTER event(i checked the key code : 13).

Thanks in advance.


Celery Pickiling error with dynamic models

I'm using celery with a function which writes data into a database table.

This table doesn't have a related model inside models.py because I create it dynamically using django-mutant.

When I run my task, it correctly writes on my dynamic table, but at the very end of the task I get the following error:

[2013-07-10 09:10:45,707: CRITICAL/MainProcess] Task topology_py.Functions.Functions.objectAggregate[aff70510-1e93-4610-b08c-c3675c92afe9] INTERNAL ERROR: PicklingError("Can't pickle <class 'mutant.apps.tss.models.1_tmp'>: import of module mutant.apps.tss.models failed",)
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/celery/task/trace.py", line 261, in trace_task
for callback in task_request.callbacks or []]
  File "/usr/lib/python2.7/site-packages/celery/canvas.py", line 197, in apply_async
return self._apply_async(args, kwargs, **options)
  File "/usr/lib/python2.7/site-packages/celery/app/task.py", line 472, in apply_async
**options)
  File "/usr/lib/python2.7/site-packages/celery/app/amqp.py", line 249, in publish_task
**kwargs
 File "/usr/lib/python2.7/site-packages/kombu/messaging.py", line 157, in publish
compression, headers)
  File "/usr/lib/python2.7/site-packages/kombu/messaging.py", line 233, in _prepare
body) = encode(body, serializer=serializer)
  File "/usr/lib/python2.7/site-packages/kombu/serialization.py", line 170, in encode
payload = encoder(data)
  File "/usr/lib/python2.7/site-packages/kombu/serialization.py", line 356, in dumps
return dumper(obj, protocol=pickle_protocol)
PicklingError: Can't pickle <class 'mutant.apps.tss.models.1_tmp'>: import of module mutant.apps.tss.models failed

The model that celery is searching for, 1_tmp is not stored in my app, named tss, but inside mutant app tables.

My problem is that if I chain this function as a subtask to another subtask, celery terminates with this error at the end of the first one!

Is there a way to tell celery where to find this model or anyway to skip this error and go further to next subtasks?

Thanks in advance.

EDIT: at the moment I can run even 5 functions in a chain using 5 immutable subtasks. They work correctly and fill correctly the dynamic table, but the first one, and only the first one, continue producing the error described...Can you give me and idea of why only the first one give me the error since that they access the dynamic model in the same identical way?


How to check for nulls using LINQ

I have this code. How can I check for null values with the SingleOrDefault method?

public static List<ETY.Rol> GetRolesByApplicationAndCompany(this UsuarioContext usuario, int company, int app)
        {
            List<ETY.Company> lCompanies= usuario.Companies;

            var roles = lCompanies.
                SingleOrDefault(e => (e.Id == company)).Applications.
                SingleOrDefault(a => a.Id == app).Roles;
            return roles;

        }


Should I use MongoDb module or morphia module or Casbah in play framework for MongoDb?

I am working on a play framework project with scala in which I want to have Scala domain classes (or even Java domain classes) using MongoDb as data store.

I want maximum performance while serving hundreds of thousands  if not millions of requests per day.

Since both scala language and Play framework is adding new features by the month, what is the best answer in terms of latest production version of the modules mentioned in the question
and play framework 1.2.2, scala 0.9.1+  and scala language 2.8+?


String format using UWP and x:Bind

Does anyone know how to format a date when using x:Bind in a UWP Windows 10 app?

I have a TextBlock that is bound (x:Bind) to a DateTime property on my ViewModel which is read from SQL. I want to format the output to "dd/MM/yyy HH:mm (ddd)". Is there a simple way of doing this?

The default format is "dd/MM/yyy HH:mm:ss" which I presume is coming from a default. Could this be replaced maybe?

Thanks.


User auth problem when trying to access to the SQL Server Reporting service's webservice

I've a SSRS(2008 standard, not R2), so I'm using ReportExecution2005.asmx and ReportService2005.asmx to run them.

We developed an application which can connect to the SSRS through a webservice. It worked well on our test server, but now I'm trying to configure a new server on a virtual machine, and no way, everytimes the application tries to connect to the SSRS webservice, I get a 401 unautorized.

it's very strange, because if I only put the .asmx url in firefox on the client workstation, it prompts me for username-password, I enter it and I get the wsdl definition, so I think that the access is correct.

Here is my code:

    public ReportGateway()
    {
        _rs = new ReportingService2005 { Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ReportGatewayUser"], ConfigurationManager.AppSettings["ReportGatewayPassword"])  };
        _rs.Url = "http://MyMachine:80/ReportServer/ReportService2005.asmx";//?? I saw when I was debugging that it wasn't reading the value in the app.config, but keeping the url of the reference when I created it, so for my test of the moment, I hard-setted it
        _rsExec = new ReportExecution2005.ReportExecutionService { Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ReportGatewayUser"], ConfigurationManager.AppSettings["ReportGatewayPassword"]) };
        _rsExec.Url = "http://MyMachine:80/ReportServer/ReportExecution2005.asmx";//Same
        GenerateReportList();
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    private void GenerateReportList()
    {
        try
        {
            Dictionary<String, SRSSReport> reports = new Dictionary<String, SRSSReport>();
            foreach (var children in _rs.ListChildren("/", true))
            {
                if (children.Type == ItemTypeEnum.Report)
                {
                    SRSSReport report = new SRSSReport {Name = children.Name, Path = children.Path};
                    ReportParameter[] parameters = _rs.GetReportParameters(children.Path, null, false, null, null);
                    foreach (ReportParameter parameter in parameters)
                        report.Parameters.Add(new SRSSReportParameter {Name = parameter.Name, Type = _typeConverstion[parameter.Type]});
                    reports.Add(report.Path, report);
                }
            }
            lock (_lockObject)
            {
                _reports = reports;
            }
        }catch(Exception ex)
        {
            _reports = new Dictionary<string, SRSSReport>();
            Logger.Instance.Error("Error when contacting the reporting server", ex);
        }
    }

I'm completly desperate for now, I've looked for a solution during days, and I don't know what I can have done wrong.

Do you have an idea/solution/... to help me?

Thank you very much, any help would be really appreciated.


What does "cdecl" stand for?

Yes,  I know that "cdecl" is the name of a prominent calling convention, so please don't explain calling conventions to me. What I'm asking is what the abbreviation (?) "cdecl" actually stands for. I think it's a poor naming choice, because at first sight it reminds one of "C declarator" (a rather unique syntactic aspect of C). In fact, there is a program called cdecl whose sole purpose is to decipher C declarators. But the C declarator syntax has absolutely nothing to do with calling conventions as far as I can tell.

Simplified version: "stdcall" stands for "standard calling convention". What does "cdecl" stand for?


Making data accessible to fragments

I am having an app which is retrieving data in the main activity and sending an event to all fragments as soon as it is available. So for the first start it looks like this:

App starts (fragments are initialising in the background) -> feed download -> notification sent to fragments -> fragments initialise UI

Everything's fine so far. BUT, what if I am resuming the app. The data will be still cached, so i will send the event immediately on app resume, and therefore it can happen that my fragments are not even ready for receiving the event -> no fragment UI update!
Or the event is triggered and received in the fragment, but the fragment is not ready for the UI update, cause it still hasn't inflated the layout -> NullpointerException
Or the fragment receives the event, but is not attached to the activity anymore -> another Exception.
There are ways to deal with single issues, but overall it is complicating the architecture a lot.

Somehow I tried a lot of things (playing around with Otto bus) but somehow I can't find any architecture which is working for making a central datasource available to all activities and fragments in the app.

How do you supply your fragments with data if you don't want to use bundles?


C++ char arithmetic overflow

#include <stdio.h>

int main()
{
    char a = 30;
    char b = 40;
    char c = 10;
    printf ("%d ", char(a*b));
    char d = (a * b) / c;
    printf ("%d ", d);
    return 0;
}

The above code yields normal int value if 127 > x > -127
and a overflow value if other. I can't understand how the overflow value is calculated. As -80 in this case.
Thanks


Finding points of a scrabble word

So i recently started c language with no prior knowledge of coding or computer science. Wrote this piece of code to find value of a word using scrabble points as below:
1:AEILNORSTU   2:DG   3:BCMP   4:FHVWY   5:K   8:JX   10:QZ.

# include <stdio.h>
# include <ctype.h>
# include <conio.h>
int main (void)
{
  int n=0;
  char ch;
  clrscr();
  printf("Enter the SCRABBLE word\n");
  ch = getchar();
  while(ch!='\n')
  {
    toupper(ch);
    if(ch =='A'||'E'||'I'||'L'||'N'||'O'||'R'||'S'||'T'||'U')
      n=n+1;
    else if (ch =='D'||'G')
      n=n+2;
    else if (ch =='B'||'C'||'M'||'P')
      n=n+3;
    else if (ch =='F'||'H'||'V'||'W'||'Y')
      n=n+4;
    else if (ch =='K')
      n=n+5;
    else if (ch =='J'||'X')
      n=n+8;
    else if (ch =='Q'||'Z')
      n=n+10;

    ch = getchar();
  }
  printf("The value is %d",n);
  return 0;
}

So what happens when i run this code is that :
    Enter the SCRABBLE word
  eg: barrier
    The value is 7
though it should be 9 as b carries 3 points as noted above the code,a carries 1,r carriers 1,again r 1 point,i carries 1 point and the last two alphabet are one point each so thats 3+1+1+1+1+1+1=9


Using matrix column or rows to reference elements of a vector

I have a vector. I select groups of n=4 consecutive values using the matrix produced by mapply(seq,starts,ends).  I use the matrix columns to reference elements in my vector y. Then I run the min function on the sub vectors to identify the minimum value in each group of elements.

set.seed(30)
y <- sample(100)
  # [1]  10  49  36  41  29  15  85  21  89  13   6  98  48  77  20  79  22  69
 # [19]  50  35  91  47   3  26  86  23  92  19  59  34  43  17  71  97  76  44
 # [37]  90  87  78  83  27  37  45  28  11  38  70  95  99   9   7  51  53  66
 # [55]   4  40   5  46  25  81   2  54  57  93  55  84  61  82  73  31  96  58
 # [73]  68  74  32 100  24  72   1  30  39  42  16  14  64  75  67  60  56  33
 # [91]  94  88  65   8  52  12  80  63  62  18
x <- c(3,6,9,14,17,21,23)
ends <- x*4
starts <- ends - 3
m <- mapply(seq,starts,ends)
     # [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    9   21   33   53   65   81   89
# [2,]   10   22   34   54   66   82   90
# [3,]   11   23   35   55   67   83   91
# [4,]   12   24   36   56   68   84   92

For example, the first column in m is 9,10,11,12.  The goal is to reference the 9th through the 12th element of y and find out which of the 4 referenced element is the minimum. Then do the same thing with the rest of m's columns, grouping y's elements based on m columns.  I attempted to use the following code, but it didn't produce the expected results. Instead it produced all ones, and it was very slow.

oneU <- as.integer(sapply(m,function(i) which(y[i]==min(y[i]))))

The desired output is:

# [1] 3 3 4 3 1 4 2

Note for the first group the minimum should be the 3rd element of the group, which is the 11th element of y.

Is there an efficient way of employing matrix columns or rows to reference elements of a vector into groups, and then run a function on the resulting groups?


in-app billing for subscriptions

I am planning to sell an android application on Google play with the subscription model as follows

1.99/month (includes a 30 day free trial. The first billing date is set to today+30)
-19.99/year (includes a 60 day free trial. the first billing date is set to today+60)

I have implemented the logic for this pricing and the application is working fine.

Now, I would like to offer an additional 30 days of free service to those customers that report an issue with using the application. In order to do this, I like to just update the next billing date. The question does google play allow such an update using google play server-side api? If yes, I may just develop a console app for and admin to add the 30 days to next billing date for the specific customer reporting the issue.

Can someone help me, if this approach works and point me with a link to server-side API and a sample showing how to consume? Alternatively, can someone suggest an alternative approach to meet this requirement

Srinivas


jqGrid: Subgrid row displaying columns obtained in maingrid json

Can I have a subgrid that shows some of the columns from main grid without actually going and getting data again using URL?
Example:Main Grid is getting data from server (10 columns) using jsonReader out of which I want to show 7 columns in the parent row and 3 columns in the subgrid row . Can I do this?
(Or some other way to achieve this expand concept?)

(I tried the below with "subGridRowExpanded" function but it doesn't seem to be working...)

Error: jQuery("#grid").getRowData is not a function

-------------------------------------
var myGrid =  jQuery("#grid").jqGrid({

...
subGrid: true,

subGridRowExpanded: function (subgridDivId, rowId) {
            var subgridTableId = subgridDivId + "_t";
            var rowData = $("#grid").getRowData(rowId);
            var requestorFullName = rowData['requestorFullName'];
             var html ="<table id='" + subgridTableId + "'> <tr><td>'" +requestorFullName+"'</td></tr> </table>";
             $("#" + subgridDivId).append(html);

}

});

-------------------------------------


C++ syntax to alias non-class overloaded function inside class

I know I can do namespace FILE { using boost::filesystem::rename }; which I will do if there's no other solution, but wondering if I can get it inside the class so I can be DRY. I want to create a class called FILE and have no need for namespace FILE.

// class-qualified name is required
using boost::filesystem::rename

// definition not found
void(*rename)(const path&, const path&) = boost::filesystem::rename;

// cannot determine which overloaded instance
function rename = std::mem_fn<void(const path&, const path&)>(boost::filesystem::rename);

// not an alias, creates a new function
function<void(const path&, const path&)> rename = [](const path& old_p, const path& new_p) { boost::filesystem::rename(old_p, new_p); };

// all sorts of errors
auto rename = std::mem_fn(static_cast<void()(const path&, const path&)>(&boost::filesystem::rename));

// nope!
void constexpr rename = boost::filesystem::rename

I am trying to do this:

class FILE {
public:
    // Would like to alias boost::filesystem::rename as rename here
};

What is the correct syntax?


Select all data different second between two date times

I have a mysql table with data connected to date and time. Each row has data and a date, like this:

datetime               name
2009-06-25 10:00:00    jhon
2009-06-25 10:00:05    jack
2009-06-25 10:00:11    json
2009-06-25 10:00:15    jack

My problem is I need to get the rows different second date1 and date2 like this :

datetime               name     second
2009-06-25 10:00:00    jhon     0
2009-06-25 10:00:05    jack     5
2009-06-25 10:00:11    json     6
2009-06-25 10:00:15    jack     4

Thank you


CakePhp: Dont load some related tables

I've one model, which has several(6) linked tables.

Most of times, I use this model to display one data and I need all those data, but once, to provide data for an auto-complete field, I only need to have 2 tables linked to make my search. This request needs to be very fast because of the autocomplete and the very frequent usage of this request,

I know that I can disable the load of all items(with recursive =0), but not only disable(or enable) some relations.

So how can I do this with cakePhp?

Thank you!


.NET Core on Mac for developing REST web service

I have a simple question:
Is it possible to develop a REST web service on a Mac laptop, using the latest Core.NET and the new Mac Visual Studio tooling? The service is to be deployed in Window server/iis eventually, but I need productive environment.

Also, as I will be interfacing with SharePoint 2013 server, will I be able to use the above environment for OAuth, claims, etc during Mac development cycles (e.g are the libraries/assemblies/whatever included in .NET Core for Mac)?

Thank you.


Rearranging div tags within one another

I want to rearrange the div tags (shown below) between one another. How can I do that?

<div class="wrap">
    <div class="box">
        This has less height
    </div>
    <div class="box">
        This has more height
    </div>
    <div class="box">
        This has less height.
    </div>
</div>


How to integrate 3rd party merchant payment gateway in ubercart

I've been looking for 2 days on how to integrate my merchant payment gateway into ubercart with no lack. So I decided to ask it here.

I have the following code as an example from my merchant:

<form name="payFormCcard" method="post" action=" https://test.MyMerchantGateway.com/ECN/eng/payment/payForm.jsp">
<input type="hidden" name="merchantId" value="1">
<input type="hidden" name="amount" value="3000.0" >
<input type="hidden" name="orderRef" value="000000000014">
<input type="hidden" name="currCode" value="608" >
<input type="hidden" name="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" name="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" name="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<input type="hidden" name="payType" value="N">
<input type="hidden" name="lang" value="E">
<input type="submit" name="submit">
</form>

Please note that I change the actual domain above for security reason.

What I want after checkout is redirect it to https://test.MyMerchantGateway.com/ECN/eng/payment/payForm.jsp


Aggregate initialization of std::array of subobjects with nested initializer lists

What is the correct way to initialize an aggregate type (such as std::array) and its subobjects with nested braced initializer lists? I don't want to call the constructors of the sub-type(s) directly.

This is a recurring issue and I'm always surprised that the code below doesn't work, since the type of the elements is specified, so the proper constructor can be deduced by the compiler.

Note that the example type A is not necessary to be an aggregate (but of course it must support braced initializer-lists).

#include <array>

struct A
{
    int values[4];
};

int main()
{
    std::array<A, 2> arr{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }};

    // Works only if A is an aggregate, also looks confusing, I don't want to do this
    //std::array<A, 2> arr{ 0, 1, 2, 3, 4, 5, 6, 7 };

    // I don't want to do this neither
    //std::array<A, 2> arr{A{ 0, 1, 2, 3 }, A{ 4, 5, 6, 7 }};

    return 0;
}

But all I get is the error

error: too many initializers for 'std::array<A, 2ul>'


How to implement a bidirectional "mailbox service" over tcp?

The idea is to allow to peer processes to exchange messages (packets) over tcp as much asynchronously as possible.

The way I'd like it to work is each process to have an outbox and an inbox. The send operation is just a push on the outbox. The receive operation is just a pop on the inbox. Underlying protocol would take care of the communication details.

Is there a way to implement such mechanism using a single TCP connection?

How would that be implemented using BSD sockets and modern OO Socket APIs (like Java or C# socket API)?


javascript css3 change background color every 2 seconds

How can I change the HTML background color automatically every 2 seconds? HTML5 with CSS3 fade in or fadeout?

I tried to use transition with timer and CSS target without any success

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

label {
     display: block;
     background: #08C;
     padding: 5px;
     border: 1px solid rgba(0,0,0,.1);
     border-radius: 2px;
     color: white;
     font-weight: bold;
}

input[type=checkbox]:checked ~ .to-be-changed {
    color: red;
}


Under what circumstances would [[NSScreen mainScreen] visibleFrame] return null?

I want to get the dimensions of the main screen, so I use this snippet:

NSLog(@"mainScreen frame = %@", [[NSScreen mainScreen] visibleFrame]);

It's printing

mainScreen frame = (null)

Earlier it was printing the expected dimensions of my main monitor.

What are some possible causes of this?


how to create json from associate array

I am new to PHP. So bear with me. I have to fetch songs from db. I don't know how to initialize associate array in a for loop using keyValuePair. and also add status attribute to it.

What i want is

{
       "status" : "true" ,// It tells whether day available or not
       "data": [
          {
             "name": "Joe Bloggs",
             "id": "203403465"
          },
          {
             "name": "Fred Bloggs",
             "id": "254706567"
          },
          {
             "name": "Barny Rubble",
             "id": "453363843"
          },
          {
             "name": "Homer Simpson",
             "id": "263508546"
          }
       ]
    }

My Code

$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');

$output = array();// how to initialze it in for loop with keyValue pair

// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
    if (0 === strpos($e->href, '/watch?v'))
    {
        $output[] = $e->href . '<br>';

        echo $e->href . '<br>';
    }
}
echo json_encode($output);

Thanks in Advance.


How to display html, body and head tags in Sweet Alert?

I'm trying to do live preview of html code. It will be small code just for creating custom tickets template.
I thought setting html: true will do the trick, but it removes <html><head><body> tags. If a have <style> in head Sweet Alert leave it there, which breaks my original css. I tried to wrap the code into iframe like this:

$('<iframe>').append($('textarea').val()).html()

But even iframe was removed.

So again. I have a textarea -> user types in the code which could look like this:

<html>
<head>
    <style>
        h1 {color: white}
        ...
    </style>
</head>
<body>
    <h1>TICKET'S NAME</h1>
    ...
</body>
</html>

And after click on some button sweet alert appers with code preview.

How to force SA display html, head and body tags?


c# run an async task in background when parent returns

I am writing a MVC5 app that has a controller with a function say Method1

I have a third party function that is async Task, let's call it DoMethodAsync (it essentially makes a POST call).

I want to call it right before returning from Method1 but I don't really care about the result of the async task, if it fails, it fails. How can I fire and forget and have it execute in the background so that it does not block the controller from responding to other requests?

How can I ensure that DoMethodAsync is only executed after Method1 has returned?


Placing buttons under the combo box

How do i make the buttons appear under the combo box here? In other words have button 1 and button 2 right underneath the combo box?

public class GUI extends JFrame implements ListSelectionListener, ActionListener {

    private JPanel myPanelA;
    private JSplitPane itemPane;

    public static void startWindowsGui ( ) {

        SwingUtilities.invokeLater ( new Runnable ( ) {
            public void run ( ) {

                GUI gui = new GUI ( );

                gui.setVisible ( true );
            }
        } );
    }

    public GUI() {

        // Set the layout to a grid
        setLayout ( new BorderLayout ( 5, 5 ) );

        setTitle ( "UI " );
        setSize ( 800, 600 );
        setDefaultCloseOperation ( EXIT_ON_CLOSE );
        setBackground ( new Color ( 15, 255, 10 ) );

        addComponents ( );
    }

    private void addComponents ( ) {

        JSplitPane mainPane = new JSplitPane ( JSplitPane.HORIZONTAL_SPLIT );
        itemPane = new JSplitPane ( JSplitPane.VERTICAL_SPLIT );

        mainPane.add ( PanelA ( ), JSplitPane.LEFT );
        mainPane.add ( itemPane, JSplitPane.RIGHT );
        mainPane.setOneTouchExpandable ( true );

        itemPane.setOpaque(true);
        itemPane.setBackground(new Color(0xffffffc0));
        BufferedImage myPicture = null;
        try {
            myPicture = ImageIO.read(new File("C:/Users/Desktop/image.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        //add(picLabel);
        itemPane.add(picLabel);

        add ( mainPane, BorderLayout.CENTER );
    }

    private JPanel PanelA ( ) {

        myPanelA = new JPanel ( );

        myPanelA.setLayout ( new BorderLayout ( 0, 0 ) );

        myPanelA.add ( buttonPanel ( ), BorderLayout.NORTH );

        myPanelA.setBorder ( new EmptyBorder ( 0, 0, 0, 0 ) );
        myPanelA.setBackground(new Color(0,0,0));

        return myPanelA;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }

    @Override
    public void valueChanged(ListSelectionEvent arg0) {

    }

    private JPanel buttonPanel ( ) {
        // Create the panel
        JPanel addButton = new JPanel ( );

        JPanel cards; //a panel that uses CardLayout
         String BUTTONPANEL = "Card with JButtons";
         String TEXTPANEL = "Card with JTextField";

        JPanel comboBoxPane = new JPanel(); //use FlowLayout
        String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
        JComboBox cb = new JComboBox(comboBoxItems);
        cb.setEditable(false);
            //cb.addItemListener(this);
            comboBoxPane.add(cb);

            //Create the "cards".
            JPanel card1 = new JPanel();
            card1.add(new JButton("Button 1"));
            card1.add(new JButton("Button 2"));

            JPanel card2 = new JPanel();
            card2.add(new JTextField("TextField", 10));

            //Create the panel that contains the "cards".
            cards = new JPanel(new CardLayout());
            cards.add(card1, BUTTONPANEL);
            cards.add(card2, TEXTPANEL);

            addButton.add(comboBoxPane, BorderLayout.PAGE_START);
            addButton.add(cards, BorderLayout.CENTER);

        return addButton;
    }
}


Loop in SWI-PROLOG

I have to create a program, to simulate energy exchange between particles,
let me explaine: i have to create a list of 1000 particles each particle
begining with energy = 5 quanta, then I have to randomly select 2 particle
(P1 and P2) to exchange one quanta of energy (E1-1 and E2+1) this would be 1
exchange, i have to do n exchange until reach the boltzmann distribuction.

keeping in mind that a particle cannot exchange energy with itself, and a
particle cannot have energy < 1 quanta.

%Create a list (Particle/energ) [1/5,2/5,3/5...1000/5].

from_to2(P1, P1000, List) :-
bagof(N/5, between(P1,P1000,N), List),!.
from_to2(_,_,[]).

%Exchange 1 quanta of energy between to particle: E1+1 , E2-1

energexchange(L1,L2):-
choose(L1,Px/Ex),
delete(Px/Ex,L1,Listsem1),
choose(Listsem1,Py/Ey),
delete(Py/Ey,Listsem1,Listsem2),
Ex > 1, Ex2 is Ex - 1, add(Px/Ex2,Listsem2,Listcom1),
Ey2 is Ey + 1, add(Py/Ey2,Listcom1,L2).

example:
?-from_to2(1,1000,L), energexchange(L,L2).
gives L2= [3/4,1/6,2/5,4/5,5/5...1000/5]

L2 is the first exchange now I need to use L2 in the next exchange, energexchange(L2,L3). to do the second exchange and so on...

What should I do to repeat energexchange 1000 times without counting the fails (when Ex=1)?


How do i link my "add to cart" button to a specific on page tab and scroll to it when clicked?

Previously I was trying to create and alternate "add to cart" button on the single-product-page of a Woocommerce website.  Now, I would like that button to link to a tab on the same page, have the page scroll down and switch to that tab when the button is clicked.

This is exactly what I need to happen but I do no know how to implement it in the wordpress setting.

So I settled for creating a js script by suggestion of this place

<script type="text/javascript">
    if ( location.href.match(/#tab-reviews/g) !== null ) {
        jQuery( '#tab-reviews' ).show();
        jQuery( 'li.reviews_tab a' ).trigger('click');
    }
</script>

Then I called it into word press through the funtion.php file with this, but its not working.

function tab_scroll() {
wp_enqueue_script('custom-script',
    get_stylesheet_directory_uri() . '/tab_scroll.js',
    array( 'jquery' ));
}
add_action( 'wp_enqueue_scripts', 'tab_scroll' );

I dont know if its the way i called the script or just that the script is not written to suit my needs or even written properly

What I would like is some help/suggestions on making the first script work for me. And help on bringing into wordpress.


Android: How to make merge multiple bitmap images to a large jpeg image

I am going to merge multiple bitmap images to a jpeg image.

I can make large .bmp file from multiple bitmap images(tiled).
And I can convert it to jpeg file with jpeg library.

But the speed of this process is very slow.
I tested this on my SamSung phone.

It takes about 15 secs to make a large bitmap with tiled bmp images.
Is there any way to solve this?

Thanks.


Convert URL to correct filename (Linux/Windows)

I have a script that works with different sites. As a result this script returns 1 csv file for 1 site with a unique filename, based on site URL. Site URL may be different, like

http://test1.com
http://test2.com/testurl
http://test3.com/test/path/

I want to convert URLs to filenames - to remove all characters that can cause conflict in Linux/Windows, to replace them with '_', for example

http://test1.com will be test1com.csv
http://test2.com/testurl will be test2comtesturl.csv
http://test3.com/test/path/ will be test3comtestpath.csv

I can try to use parse_url and concat host and path with replacing '/' and '.' to '_', but I'm not sure that this is the best solution, because URLs can be different and with different characters that can not be used as filename.


How to reverse a array of chars and then store the reversed array of char to another array?

I have been working on this very simple question. I am trying to reverse a array of chars and then store this reversed array of chars into another array using c language. Here is my code, I can not figure out what is the problem of my code. I really do not understand why when I try to print out my stcp which is the array with the reversed string, there is nothing show up on the screen. Please advice, any help would be really appreciate.

#include<stdio.h>

int main() {
    char st[100];
    scanf("%s", st);
    int count = 0;
    while(st[count] != '\0'){
        count++;
    }

    //printf("%s", st);
    char stcp[100];
    int i, j = 0;
    for(i = count-1; i >= 0; i--){
        st[i] = stcp[j];
        j++;
    }

    puts(stcp);
    return 0;
}


Column locking in innodb?

I know this sounds weird, but apparently one of my columns is locked.

select * from table where type_id = 1 and updated_at < '2010-03-14' limit 1;

select * from table where type_id = 3 and updated_at < '2010-03-14' limit 10;

the first one would not finish running even in a few hours, while the second one completes smoothly. the only difference is the type_id between the 2 queries.

a bit of background, the first statement screwed up before which i had to kill manually.

Thanks in advance for your help - i have an urgent data job to finish, and this problem is driving me crazy


Setting a delay with clearTimeout for a drop down menu

I'm very new to Javascript, and I'm trying to set a delay on some drop down menus. I have jQuery loaded and am currently using the delay method. However, I did some looking around and it seems like there's no way to cancel the timer with delay, which means that I end up with a bunch of uncollapsed dropdowns.

How do I set this up so that I can set a delay and have it cancel on mouseout?

Here's my code (note that the $$'s are for jQuery noconflict):

$$(function(){
    $$('#custommenu>div.menu').mouseover(function(){
    $$('#custommenu>div.menu').removeClass('active');
    $$('#popup'+$$(this).attr('id').replace('menu','')).delay(500).slideDown(100);
    });

    $$('#custommenu>div.menu').mouseout(function(){
    $$('#custommenu .wp-custom-menu-popup').hide();

    });

    $$('#custommenu .wp-custom-menu-popup').mouseout(function(){
    $$('#custommenu>div.menu').removeClass('active');
    $$('#custommenu .wp-custom-menu-popup').hide();
    });

    $$('#custommenu .wp-custom-menu-popup').mouseover(function(){
    $$('#menu'+$$(this).attr('id').replace('popup','')).addClass('active');
    $$(this).show();
    });
});


Implement "Catch Block" like behavior in Spring using AOP

I'm working on Spring application and I want to implement exception handling in following way:
Implement an Aspect class for specific exception type where that exception is diverted
Have such aspect classes based on exception types hierarchy and implement catch block like behavior
for example,
there're two aspect classes: ExceptionHandler for Exception and SQLExceptionHandler for SQLException
Both of them are exactly same pointcut expression.
Now, if SQLException is raised from any method which is covered in point expression, SQLExceptionHandler's method should be executed.
If FileNotFoundException or any other type of exception occurs then ExceptionHandler's method should be executed.
Any help would be much appreciated.


ffmpeg - convert image sequence to video with reversed order

Looking at the docs, it is not apparent to me whether ffmpeg would allow me to convert an image sequence to a video in reverse order, for example using this sequence:

frame-1000.jpg
frame-999.jpg
frame-998.jpg
...
frame-1.jpg

Is it possible to give a "step direction" for the frame indices?


edit each row in html using javascript

Help! I can't edit the other rows on my table

here is my script.. and it's working. but only on the first row.

<script>
function showInput(e)
{
document.getElementById(e.id).type = "text";
document.getElementById(e.id).focus();
}
</script>

and here is my table. coming from my database.

<table class="table table-bordered">
<tr class="green">
    <th>Job Title</th>
    <th>Job Description</th>
    <th colspan="2">actions</th>
 </tr>
<?php foreach ($fill_data as $row): ?>enter code here

<tr>
    <td>
        <?php echo $row['title'];?>
        <div style="position:absolute; margin-top:-20px; margin-left:4px;">
            <input type="hidden" id="<?php echo $row['title'];?>" name="<?php echo $row['title'];?>" value="<?php echo $row['title'];?>">
        </div>
    </td>
    <td><?php echo $row['description'];?></td>
    <td width="40px"><img src="<?php echo base_url(); ?>images/edit1.png" width="30" height="30" title="Edit" onclick="showInput(<?php echo $row['title'];?>)" style="cursor: pointer"></td>
    <td><img data-toggle="modal" data-id="<?php echo $row['id']?>" class="delete-data" href="#delete" style="margin-top: 5px; cursor:pointer" height="15" width="15" src="<?php echo base_url(); ?>images/remove.gif"></td>
</tr>
<?php endforeach?>
</table>

the $rows comes from my database.


How to show recorded value in Edit Ruby on Rails

I have a master detail working, but when I go to the edit form the select field isn't shown as recorded in the database, it's showing the first option_for_select:

<div class='fields'>
  <div class='span-24 last'>
    <div class='span-11'>
      <%= f.select :ordem, options_for_select([["0", 0], ["1", 1], ["2", 2], ["3", 3], ["4", 4], ["5", 5]]) %>
    </div>
    <div class='span-8'><%= f.text_field :opcao %></div>

    <div class='last'>
      <%= f.hidden_field :_destroy %>
      <%= link_to_function '(X)', "remove_fields(this)" %>
    </div>
  </div>
</div>

So what do I have to do to show the recorded content for this select?


How do I use the command "heroku pg:transfer"?

I am very new to heroku/ruby on rails and git.  I just went through Michael Hartl's Ruby on Rails tutorial and want to push my local database to heroku but am having trouble.

After doing some research I found this article:

pg transfer is the new taps

It seems like it should work, but I do not understand how to set my env var DATABASE_URL:

$ env DATABASE_URL=postgres://localhost/someapp-dev heroku pg:transfer

Specifically I have no idea what I am supposed to directly copy and what to change.  I believe I need to enter my own local host and my own database name.

Is this correct?  If so how do I find my localhost and how do I find my database name?

My database.yml file looks like this:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000


CakePHP - Html->link - why use controller=> and action=> instead of just controller/action

Why this:

echo $this->Html->link('Add a User', array('controller'=>'users', 'action'=>'add'));

Instead of just this:

echo $this->Html->link('Add a User', 'users/add');


Google cloud compute engine high latency

I just started using google cloud, and I've been having issues with my instance. The connection is really unstable and has really high ping. Used speedtest to test it, and has over 150 ms. Is this normal? It shouldnt be. I'd appreciate anyones help.


rotation along x and y axis

I'm using GLKit along with PowerVR library for my opengl-es 2.0 3D app.  The 3D scene loads with several meshes, which simulate a garage environment.  I have a car in the center of the garage.  I am trying to add touch handling to the app, where the user can rotate the room around (e.g., to see all 4 walls surrounding the car).  I also want to allow a rotation on the x axis, though limited to a small range.  Basically they can see from a little bit of the top of the car to just above the floor level.

I am able to rotate on the Y OR on the X, but not both. As soon as I rotate on both axis, the car is thrown off-axis.  The car isn't level with the camera anymore. I wish I could explain this better, but hopefully you guys will understand.

Here is my touches implementation:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];
    CGPoint lastLoc = [touch previousLocationInView:self.view];
    CGPoint diff = CGPointMake(lastLoc.x - location.x, lastLoc.y - location.y);

    float rotX = -1 * GLKMathDegreesToRadians(diff.x / 4.0);
    float rotY = GLKMathDegreesToRadians(diff.y / 5.0);

    PVRTVec3 xAxis = PVRTVec3(1, 0, 0);
    PVRTVec3 yAxis = PVRTVec3(0,1,0);

    PVRTMat4 yRotMatrix, xRotMatrix;

    // create rotation matrices with angle
    PVRTMatrixRotationXF(yRotMatrix, rotY);
    PVRTMatrixRotationYF(xRotMatrix, -rotX);

    _rotationY = _rotationY * yRotMatrix;
    _rotationX = _rotationX * xRotMatrix;
}

Here's my update method:

- (void)update {

    // Use the loaded effect
    m_pEffect->Activate();

    PVRTVec3    vFrom, vTo, vUp;
    VERTTYPE    fFOV;
    vUp.x = 0.0f;
    vUp.y = 1.0f;
    vUp.z = 0.0f;

    // We can get the camera position, target and field of view (fov) with GetCameraPos()
    fFOV = m_Scene.GetCameraPos(vFrom, vTo, 0);

    /*
     We can build the world view matrix from the camera position, target and an up vector.
     For this we use PVRTMat4LookAtRH().
     */
    m_mView = PVRTMat4::LookAtRH(vFrom, vTo, vUp);

    // rotate the camera based on the users swipe in the X direction (THIS WORKS)
    m_mView = m_mView * _rotationX;

    // Calculates the projection matrix
    bool bRotate = false;
    m_mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)1024.0/768.0, CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate);
}

I've tried multiplying the new X rotation matrix to the current scene rotation first, and then multiplying the new Y rotation matrix second.  I've tried the reverse of that, thinking the order of multiplication was my problem.  That didn't help.  Then I tried adding the new X and Y rotation matrices together before multiplying to the current rotation, but that didn't work either.  I feel that I'm close, but at this point I'm just out of ideas.

Can you guys help?  Thanks. -Valerie

Update: In an effort to solve this, I'm trying to simplify it a little.  I've updated the above code, removing any limit in the range of the Y rotation.  Basically I calculate the X and Y rotation based on the user swipe on the screen.

If I understand this correctly, I think I want to rotate the View matrix (camera/eye) with the calculation for the _rotationX.

I think I need to use the World matrix (origin 0,0,0) for the _rotationY calculation.  I'll try and get some images of exactly what I'm talking about.


How to make Google map fill available height between dynamic header and footer

I have a header and footer, each with dynamic content. This is actually an aspx page with a master page which contains header/footer content which may vary in size.  I can not enforce a px height for header or footer as they may have images or just text, etc.  I want to make the Google map fill the available page height (and width) between them.  I'll give the map canvas a minimum height of say 200px, just in case, but otherwise it should force the footer to bottom of the page without scrolling (unless the screen is short enough for the 200px minimum to require scrolling).

<body>
<div id="wrapper">
    <div id="header">Title<br />of<br />variable<br/>height</div>
    <div id="body">
        <div id="map-canvas"></div>
    </div>
    <div id="footer">
        Footer<br />of<br />variable<br />height
    </div>
</div>

Here is a Fiddle showing it very close using flex approach... It seems to work in Chrome/FireFox but this does not work in IE11.
https://jsfiddle.net/randbrown/7dc8u6ja/4/

Is the flex-based approach best for this and if so what am I missing to get it working in IE?  Or is there a better way to achieve this?


How can I read single-channel 32-bit integer images with python?

I want to read single-channel 32-bit integer image saved as ssv file.
I have tried so far(see the following code) but without much success.

Here is the code

Please let me know if you have any idea of what is missing?


Update cannot proceed due to validation errors.

below is my code

CREATE TABLE [dbo].[tbl_company] (
    [Id]            INT           IDENTITY (1, 1) NOT NULL,
    [company_Id]    INT           NOT NULL,
    [typeOfCompany] VARCHAR (250) NULL,
    [ownership_Id]  INT           NULL,
    CONSTRAINT [PK_tbl_company] PRIMARY KEY ([Id])
);

i am getting below error:
The referenced table '[dbo].[tbl_company]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.


how to add bootstrap responsive features to my navigation without changing my styling

I'm working on a navigation and I want to add bootstrap responsive feature to it, but without changing my original styling, like color, height and etc. appreciate if any one can help me on this.

below is the navigation mark up.

    <header id="pageHeader">
        <div class="container">
            <div id="logo">
            </div>
            <div id="navMain">
                <ul id="navContainer">
                    <li><a class="selected" href="index.html">HOME</a></li>
                    <li><a href="about.html">ABOUT</a></li>
                    <li><a href="services.html">SERVICES</a></li>
                    <li><a href="portfolio.html">PORTFOLIO</a></li>
                    <li><a href="contact.html">CONTACT</a></li>
                </ul>
            </div>
        </div>
    </header>

and this is the styling I have used.

#pageHeader{
  background-color: rgb(250,210,0);
  width: 100%;
}
/* 3.2. Logo Styling */
#logoTop{
  float:left;
}
/* 3.3. Main Navigation Styling */
#navMain{
  float: right;
  position: relative;
  margin: 84px 10px 21px 10px;
}
ul#navContainer{
  display: block;
  position: inherit;
}
#navMain ul li{
  float: left;
  display: block;
  margin: 0px auto;
  font-weight: bold;
  list-style-image: none;
}
#navMain ul li a{
  color: rgb(99,99,99);
  font-size: 18px;
  padding: 10px 3px 10px 12px;
  font-family: "nexa_500", Tahoma, Geneva, sans-serif;
  font-size: 16px;
  text-transform: uppercase;
  text-decoration: none;
  -webkit-transition: color ease 0.7s;
  -moz-transition: color ease 0.7s;
  -o-transition: color ease 0.7s;
  transition: color ease 0.7s;
}
#navMain li a:hover,
#navMain li a:active {
  text-decoration: none;
  color: rgb(33,33,33);
  -webkit-transition: color ease 0.7s;
  -moz-transition: color ease 0.7s;
  -o-transition: color ease 0.7s;
  transition: color ease 0.7s;
}
#navMain ul li a.selected{
  color: rgb(33,33,33);
}


-Wsign-compare warning in g++

I have a code which uses comparison of 64-bit integers. It looks similar to the following:

#include <cstdio>

long long getResult()
{
    return 123456LL;
}

int main()
{
    long long result = getResult();

    if (result > 0x000FFFFFFFFFFFFFLL
        || result < 0xFFF0000000000000LL)
    {
        printf("Something is wrong.\n");

        if (result > 0x000FFFFFFFFFFFFFLL
            || result < -4503599627370496LL)
        {
            printf("Additional check failed too.\n");
        }
        else
        {
            printf("Additional check went fine.\n");
        }
    }
    else
    {
        printf("Everything is fine.\n");
    }

    return 0;
}

When this code is compiled in g++ (tried different versions on Ubuntu 12.04 x64: 4.6.3, 4.6.4, 4.7.3, 4.8.0) with flags -Wall -pedantic -std=c++0x test.cpp -o test I get -Wsign-compare warning for second line of the first if statement (output from g++-4.8):

test.cpp:13:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 || result < 0xFFF0000000000000LL)
             ^

And when the test program is run I get two lines of text:

Something is wrong.
Additional check went fine.

When compiling same code on Windows using MS Visual Studio 11 Express Update 2 with default project options for either x86 or x64 architecture I don't get neither the warning nor this output, instead the output is:

Everything is fine.

Is it a problem in the code? If yes, could you point it? Or is it a problem with the compiler used?

Adding additional type cast for the second constant in the first if statement removes the warning in g++.


Setting "On start" fragment

I want to set a specific fragment to start when opening my app.
There's a built-in layout called "content_home" which I don't know how to delete and I think it's the one which opened at start.

Now when I open the app, I see a blank screen, then I open the drawer and click on "Home" which I want to be opened as default, without calling it.

HomeActivity.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private NavigationView navigationView;
    private DrawerLayout drawer;
    private TextView tvFullName, tvEmail;
    private Fragment fragment = null;
    FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        // Drawer Toggle:
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_search) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        switch (item.getItemId()) {
            case R.id.nav_home:
                fragment = new HomeFragment();
                break;
            case R.id.nav_settings:
                fragment = new SettingsFragment();
                setNavUserDetails();
                break;
        }
        fragmentManager = getFragmentManager();
        if (fragment != null)
            fragmentManager.beginTransaction().replace(R.id.content_home, fragment).commit();
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/logged_out_drawer_menu" />
</android.support.v4.widget.DrawerLayout>

app_bar_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.amit.java5776_7546_8412.HomeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>
    <include layout="@layout/content_home" />            // <!-- THIS ONE -->

</android.support.design.widget.CoordinatorLayout>

content_home.xml it's almost an empty RelativeLayout... I didn't see a reason to paste it too...


Strange result of sort on Linux

I have got strange result of sort on Linux

$ uname -a
Linux ... 2.6.32-279.5.2.el6.x86_64 #1 SMP Tue Aug 14 11:36:39 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux

$ sort --version
sort (GNU coreutils) 8.4

Here is file zzz2.

   pe/CCC
   pe_ext/CCC
   pe/MMM

$ sort zzz2

   pe/CCC
   pe_ext/CCC
   pe/MMM

Exppected output:
   pe/CCC
   pe/MMM
   pe_ext/CCC

Appendix.

$ od -c zzz2
0000000   p   e   /   C   C   C  \r  \n   p   e   _   e   x   t   /   C
0000020   C   C  \r  \n   p   e   /   M   M   M
0000032


Symfony 3.3 can't find Doctrine annotations

I use Symfony 3.3 it works great in local but online it shows me this error

Warning: class_exists() expects parameter 1 to be a valid callback, function 'ORM\Entity' not found or invalid function name in /htdocs/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php on line 145

Warning: class_exists() expects parameter 1 to be a valid callback, function 'ORM\Table' not found or invalid function name in /htdocs/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php on line 145

Warning: class_exists() expects parameter 1 to be a valid callback, function 'Doctrine\ORM\Mapping\Entity' not found or invalid function name in /htdocs/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php on line 145

Nothing special with my code but it seem that there is a problem with annotations
My entity City start like that

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * City
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CityRepository")
 * @ORM\Table(name="city")
 */
class City
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

}

Also in dev mod, it can't show me the profiler and the issue it's also always linked to the annotations.
Please Help


Bootstrap / Dropdown Button

Hi Im trying to create a dropdown button using bootstrap. But it just doesnt seem to come out correctly ?

<div class="btn-group">
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
        Action
        <span class="caret"></span>
    </a>
    <ul class="dropdown-menu">
        <li><a href="#">Foo</a></li>
        <li><a href="#">Bar</a></li>
    </ul>
</div>

A jsfiddle is here http://jsfiddle.net/UrgP8/

Any ideas ?

Thanks,


Cascading drop down list with ajax in php

I have a cascading dropdown list which is fetched from the database through ajax.
The list loads but its not posting to the database nor is the code seen behind.

function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {
            try{
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }

function getCity(stateid)
{
    //alert(stateid);
  var strURL="findCity.php?state="+stateid;
  var req = getXMLHTTP();
  if (req)
  {
    req.onreadystatechange = function()
    {
      if (req.readyState == 4) // only if "OK"
      {
        if (req.status == 200)
        {
          document.getElementById('citydiv').innerHTML=req.responseText;
        } else {
          alert("There was a problem while using XMLHTTP:\n" + req.statusText);
        }
      }
    }
    req.open("GET", strURL, true);
    req.send(null);
  }
}

and the php file

<? $state=$_GET['state'];
    $link = mysql_connect('localhost', '', ''); //change the configuration if required
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('a'); //change this if required
    $query="select FOR_CODE,FOR_DESC from maruti_city where FOR_STAT_CODE='{$state}' order by FOR_DESC";
    $result=mysql_query($query);?>
    <select name="city" onchange="getDealer(this.value)" class="sel" >
        <option value="0">Select City</option>
        <? while($row=mysql_fetch_array($result)) {  ?>
        <option value><?=$row['FOR_DESC']?></option>
        <?} ?>
    </select>

The DDL's Load but these values are not getting posted to the database.
form

<div class="container">
<table width="528" border="0" cellpadding=1 class="formTable" style="width: 515px;font-family:arial;font-size:12px;" >
<form action="form_submit.php" method="POST" name="alto800" id="alto800" onsubmit="return validate();">
    <tbody>
        <tr>
            <td width="52%">Name</td>
            <td width="48%" >Mobile/Phone No.</td>
        </tr>
        <tr>
            <td>
                <select name="title" id="mr" class="sel">
                <option value="mr">Mr.</option>
                <option value="mrs">Mrs.</option>
                </select>
                <input type="text" name="name" id="name" class="formName" />
            </td>
            <td>
                <input type="text" name="mobile" id="mobile"/>
            </td>
        </tr>
        <tr>
            <td >State</td>
            <td >City</td>
        </tr>
        <tr>
            <td>
                <select name="state" id="state" class="sel"  onchange="getCity(this.value)">
                <option value="0">Select state</option>
                <option value="AN">ANDAMAN</option>
<option value="AP">ANDHRA PRADESH</option>
<option value="AR">ARUNANCHAL PRADESH</option>
<option value="AS">ASSAM</option>
<option value="BH">BIHAR</option>
<option value="CG">CHATTISGARH</option>
<option value="CH">CHANDIGARH</option>
<option value="DL">DELHI</option>
<option value="DM">DAMAN</option>
<option value="DN">DADRA & NAGAR HAVELI</option>
<option value="GJ">GUJRAT</option>
<option value="GO">GOA</option>
<option value="HN">HARYANA</option>
<option value="HP">HIMACHAL PRADESH</option>
<option value="JH">JHARKHAND</option>
<option value="JK">JAMMU & KASHMIR</option>
<option value="KL">KERALA</option>
<option value="KT">KARNATAKA</option>
<option value="MH">MAHARASHTRA</option>
<option value="ML">MEGHALAYA</option>
<option value="MN">MANIPUR</option>
<option value="MP">MADHYA PRADESH</option>
<option value="MZ">MIZORAM</option>
<option value="NG">NAGALAND</option>
<option value="OS">ORISSA</option>
<option value="PJ">PUNJAB</option>
<option value="PY">PONDICHERRY</option>
<option value="RJ">RAJASTHAN</option>
<option value="SK">SIKKIM</option>
<option value="TN">TAMIL NADU</option>
<option value="TR">TRIPURA</option>
<option value="UP">UTTAR PRADESH</option>
<option value="UT">UTTARANCHAL</option>
<option value="WB">WEST BENGAL</option>

                </select>
            </td>
            <td><div id="citydiv">
                <select name="city" id="city" class="sel" onChange="getDealer(this.value)" >
                <option value="0">Select state first</option>
                </select>
                </div>

            </td>
        </tr>
        <tr>
            <td >Preffered Dealer</td>
            <td >&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2"><div id="dealerdiv"><select name="dealer"  style="width:500px;height:25px;" >
              <option value="0">Select city first</option>
            </select>                   </div>  </td>
        </tr>
        <tr>
          <td>Email Address</td>
          <td>&nbsp;</td>
      </tr>
        <tr>
          <td><input type="text" name="email" id="email" /></td>
          <td>&nbsp;</td>
      </tr>
        <tr>
            <td >Your Query</td>
            <td rowspan="2" ><br />
              <br />            </td>
        </tr>
        <tr>
            <td>
             <textarea name="query" id="query"></textarea>

            </td>
        </tr>
        <tr>
            <td >
                <div style="height:10px"></div>
                <input type="image" name="submit" value="submit" src="images/submit.png" />
            </td>
            <td ></td>
        </tr>

    </tbody>
    </form>
</table>


Post javascript module array as List object with ajax in asp .net mvc project

I want to send JavaScript object array as list object to server, the server side method(GetData) accepts list object with 3 elements, but all elements have null value. Any advice? Thanks in advance.

At Client:

User.js

define(function () {
    function User(name) {
        this.Name = name
    }
    return User;
});

main.js

var users = [new User('Barney'),
                 new User('Cartman'),
                 new User('Sheldon')];
    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: {users: users},
        success: function (data) {
            //alert(data.Result);
        },
        dataType: "json"
    });

At Server:

GetData action

public void GetData(List<User> users){
}

User Model

public class User {
        public string Name { get; set; }
}


return hits from one bucket when doing a geodistance search in elasticsearch .net

I want to do a geosearch where it should first search for all locations within a distance of 50 meters, if more than 5 hits are found, then return those. If less than 5 hits are found I want to expand and search all locations within a distance of 400 meters. Again, if less than 5 hits are found I want to expand to 1000 meters but if less than 5 hits are found there I want to return those and not expand further. I don't want to return the 5 closest results, I want to return all the hits from up to the distance used.

I'm aggregating like this:

aggregations.GeoDistance("nearby_locations", g => g
    .Field(f => f.GeoLocations)
    .DistanceType(GeoDistanceType.Arc)
    .Unit(DistanceUnit.Meters)
    .Origin((double)position.X, (double)position.Y)
    .Ranges(
        r => r.To(50),
        r => r.To(400),
        r => r.To(1000)));

But I don't know how to return the hits for the first bucket that has over 5 hits. At the moment I'm checking which bucket that had more than 5 hits and then do another search on that distance.

var maxDistance = 1000;
response = Search(query, skip, size, position, maxDistance);
var distanceBucket = response.Aggs.GeoDistance("nearby_locations").Buckets
    .FirstOrDefault(x => x.DocCount > 5);

if(distanceBucket != null) {
    distanceUsed = (int)distanceBucket.To.Value;
    response = Search(query, skip, size, position, distanceUsed);
}

This works, but I was wondering if there is a better way to achieve this?


How can I make a symbol point at the mouse?

I want to make a symbol rotate to point at the mouse. I'm using this function, but it doesn't work below the symbol's pivot. The inverse tan function has a range of 180 degrees right? So how can i get 360 degrees of movement?

Would I need to add an if statement to check the mouse position or is there a more elegant solution?

function panelTrack(){
    angle = -180/Math.PI * Math.atan((mouseX - panel.x)/(mouseY - panel.y));
    panel.rotation = angle;
    trace(panel.rotation);
}


smarty php anchor link not working

Hi I was wondering if you could help me with an issue where with my smarty php code won't work.  The problem is the anchor tag containing all of the code in this section won't actually surround it when it is outputted to the web page.

<a href="mylink"> //the link that does not actually work/surround the code below when outputed
    <div class="row" {if $smarty.section.pm_loop.last}style="border:none;"{/if}>
        <div class="f-right" style="padding-right: 35px">
            <a href='UserMessagesNew.php?pm_id={$pms[pm_loop].pm_id}'>{$Application659}</a><br/>
            <a href='UserMessagesView.php?pm_id={$pms[pm_loop].pm_id}&task=delete'>{$Application660}</a><br/>
            <input type='checkbox' name='message_{$pms[pm_loop].pm_id}' value='1' style="margin:0; height:15px; width:15px;"/>
        </div>
        <a class="f-left" href="UserMessagesView.php?pm_id={$pms[pm_loop].pm_id}"><img src="{$pms[pm_loop].pm_user->user_photo('./images/nophoto.gif')}" class='img' width="92px" alt="{$pms[pm_loop].pm_user->user_info.user_username} {$Application500}"></a>
        <a href="#" class="msg-info-c">
            <div class="msg-user-re"><b><a href="UserMessagesView.php?pm_id={$pms[pm_loop].pm_id}">{$pms[pm_loop].pm_user->user_info.user_username}</a></b></div>
            <a href="UserMessagesView.php?pm_id={$pms[pm_loop].pm_id}"><div class="msg-datet">{$datetime->cdate("`$setting.setting_timeformat` `$setting.setting_dateformat`", $datetime->timezone($pms[pm_loop].pm_date, $global_timezone))}</div></a>
            <a href="UserMessagesView.php?pm_id={$pms[pm_loop].pm_id}"><div class="user-msg-c">{$pms[pm_loop].pm_body|truncate:100|choptext:75:"<br>"}</div></a>
        </a>
    </div>
</a>

The output looks like this:

<a href="mylink"></a>
<div class="row">

     rest of content inside here

</div>


Route inbound calls to different SIP Trunks in Asterisk Python

I recently started a project to route inbound calls to different softphones.

What I Did

I'm using Raspberry Pi to do this. So in raspberry pi I've installed asterisk and python and pyst package to connect asterisk and python. However I want to route incoming call to different softphones in the network based on caller ID. So though to use Zoiper application in several mobiles which have connected to the same Wi-Fi network.

What I want

I want to know how can I use python and pyst functions or AGI functions to route incoming call to specific softphone. I know I've to make an asterisk SIP server and add SIP client info to the softphone. But I can't get a proper idea how to do that when it comes to several softphones.

Also I'm running asterisk on freePBX and I'm using Python IDLE IDE. So I wish I could only use codes to accomplish this than setting up by freePBX web GUI. Please help.