text:
Q: Yandex Maps API: add multiple placemarks I understand how to create a single placemark and if I need to create more than one I do it like that:
ymaps.ready(init);

function init() {

  var map = new ymaps.Map('map', {
    center: [55.76, 37.64], // lat, long
    zoom: 5,
    controls: ['zoomControl', 'fullscreenControl']
  });

  var data = [
    {
      name: 'Moskow',
      coordinates: [55.684758, 37.738521]
    },
    {
      name: 'Saint Petersburg',
      coordinates: [59.939095, 30.315868]
    },
  ];

  for (var i = 0; i < data.length; i++) {
    map.geoObjects.add(new ymaps.Placemark([data[i]['coordinates'][0], data[i]['coordinates'][1]], {
        balloonContent: data[i]['name']
    }));
  }

}

But is there a better way to add bunch of data to the map without a cycle?

A: Yes, use Object Manager and organize your data into objects collection. Yandex Maps API provides convenient way for that case.
Here is the simple example according to your data:
ymaps.ready(init);

function init() {

  var map = new ymaps.Map('map', {
    center: [55.76, 37.64], // lat, long
    zoom: 5,
    controls: ['zoomControl', 'fullscreenControl']
  });

  // Objects collection
  var collection = {
    type: "FeatureCollection",
    features: [
      {
        type: "Feature",
        id: 0,
        geometry: {
          type: "Point",
          coordinates: [55.684758, 37.738521]
        },
        properties: {
          balloonContent: "Moskow"
        }
      },
      {
        type: "Feature",
        id: 1,
        geometry: {
          type: "Point",
          coordinates: [59.939095, 30.315868]
        },
        properties: {
          balloonContent: "Saint Petersburg"
        }
      }
    ]
  };

  // Object Manager
  objectManager = new ymaps.ObjectManager({ clusterize: true });
  objectManager.add(collection);

  map.geoObjects.add(objectManager);

}

Read about Object Manager. There you can find more examples.


text:
Q: React Native BottomTabs navigating to a specific tab I am trying to navigate to a specific tab from a screen, as the below code shows, I want to navigate to Tab2 from Screen1
Bottom Tabs
const BottomTabNavigator = createBottomTabNavigator({
    Tab1,
    Tab2},
  {
    initialRouteName: 'Tab1',

    })

Stack Navigator:
const AppNavigator = createStackNavigator(
  {

  BottomTabNavigator,
  Screen1,
  Screen2,
  Screen3
  }
);

I tried the below but as expected it does navigate to the initial route which is Tab1
const resetAction = StackActions.reset({index: 0,
actions: [NavigationActions.navigate({ routeName: 'BottomTabNavigator', }),],});

this.props.navigation.dispatch(resetAction);

A: You can set action on the NavigationAction.navigate's input object in order to also define the tab route.
NavigationActions.navigate({
  routeName: 'BottomTabNavigator',
  action: NavigationActions.navigate({
    routeName: 'Tab2'
 })
})

or in your case
const resetAction = StackActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate(
      routeName: 'BottomTabNavigator',
      action: NavigationActions.navigate({
        routeName: 'Tab2'
      })
    )
  ]
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: require is not defined in app.js for laravel passport I want to use Laravel Passport in my project, I have followed this tutorial of Laravel Passport https://laravel.com/docs/5.3/passport.
After following this tutorial, I am getting Uncaught ReferenceError: require is not defined error.
Please have a look into my files :

*

*gulpfile.js
var elixir = require('laravel-elixir');
require('laravel-elixir-webpack');

elixir(function(mix) {

    mix.scripts('app.js');

    mix.styles([
                'bootstrap.min.css',
                'font-awesome.min.css',
                'gentelella.min.css'
               ],'public/css/app.css');

});

*resource/assets/js/app.js
Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

const app = new Vue({
    el: '#manage-passport'
});

*home.blade.php
@extends('layouts.blank')
@section('content')

    <passport-clients></passport-clients>

    <passport-authorized-clients></passport-authorized-clients>

    <passport-personal-access-tokens></passport-personal-access-tokens>

@stop

*blank.blade.php

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Passport! | </title>

    <meta name="token" id="token" value="{{ csrf_token() }}">

    <link href="/css/app.css" rel="stylesheet">

            @yield('content')

    <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">

    @stack('scripts')

A: Maybe the problem in the absence of token?
blank.blade.php

also, check whether the transmitted parameters such as token
Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});


text:
Q: Chrome, NodeJS and HTTPS Here is my server side:
var fs = require('fs');

var options = {
    key: fs.readFileSync('/cert.key'),
    cert: fs.readFileSync('/cert.crt')
};

var app = require('express')();
var http = require('https').Server(options, app);
var io = require('socket.io')(http);
var port = 1234;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/../subdomains/labs/socketio.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
    console.log("\n\n--------------------------------");
    console.log('Currently Listening on port %d',port);
    console.log("--------------------------------\n\n");
});

And my client side:
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    var socket = io('https://labs.domain.com:1234');
    $('form').submit(function(){
        socket.emit('chat message', $('#chat-message').val());
        $('#chat-message').val('');
        return false;
    });
    socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
    });
</script>

All works fine in internet explorer (agh!)  But when using it in chrome it dies:
GET https://labs.domain.com:1234/socket.io/?EIO=3&transport=polling&t=1463123926844-3 net::ERR_INSECURE_RESPONSE

It works fine in both browsers if I remove the HTTPS aspect of it.
It's quite frustrating as it seems to be an issue with Chrome only, which is the browser I use the most.  How can I fix this?

A: I've had issues with Chrome not allowing secure websocket connections if there are any issues with the certificates. I was able to get socket.io working with our app here by using certificates obtained via LetsEncrypt. I'm not saying this is the only way to do it, but here is how our (working) configuration is setup:
1 - Both me and my team-mate have dynamic DNS setup to point to each of our development machines (e.g.: mac.example.com)
2 - We each have certificates set up for our domains (e.g. mac.example.com), obtained from LetsEncrypt; the reason for this is that Chrome is super picky about the certs you are using when it sets up WebSockets and there is no way (currently) for a developer or end user to override and accept certs that are less secure/self-signed.
3 - Our code that configures socket.io in our node.js app looks like:
const server = https.createServer(/* ssl options: cert etc. */, myExpressApp)
const io = require('socket.io')(server)

We are using socket.io v1.4.6
It sounds like the issue from your question is that the certs are setup on your server, but like Chrome still complains about them.  That is probably the culprit, and it sounds like you might not have the sysadmin privileges to change it?
TL;DR Don't use self-signed certs or certs that Chrome might deem "less" secure.


text:
Q: Anonymous runnable and memory leak Let's say we have a some static method in some static class which runs some operations(has a runnable) in separate thread and returns result by some listener:
public class SomeStaticClass {
private static ExecutorService mExecService = Executors.newCachedThreadPool();
........
public interface IDataLoadCompleteListener {

    public void onDataLoadComplete(Object result);

}
........

public static void getSomeData(final IDataLoadCompleteListener listener) {
    if (listener != null) {
        mExecService.execute(new Runnable() {
            @Override
            public void run() {
               ........
               do something
               ........
               Object result = new Object();
               listener.onDataLoadComplete(result);
            }
        });
    }
}
}

And in other class we call method getSomeData():
public class SomeOtherClass {
private Object mResult;

public void someMethod(){

   SomeStaticClass.getSomeData(new IDataLoadCompleteListener(){

     @Override
     public void onDataLoadComplete(final Object result) {
        mResult = result;
     }

   });

}

}

So here in this situation I want to know when anonymous runnable that was created in mExecService become available to be a garbage collected?? There Is some memory leaks issue in this snippet or not?? In my opinion, this anonymous runnable will exist a long time until SomeOtherClass or its field mResult  garbage collected, cause we create an object in runnable and passed-by-reference in listener, am I right?

A: The problem with anonymous classes memory leaks is opposite. The IDataLoadCompleteListener you create have an implicit reference to the outer class instance: SomeOtherClass in your case. Thus SomeOtherClass instance cannot be garbage collected until the listener is collected. But it seems ok in your case. As for Runnable, it does not have such problem, because it's created inside the static method. Thus after your Runnable is executed, it will be eligible for GC along with anonymous listener. No memory leaks are created in your case.

A: Dug through some of the java source code. The threads are stored in a private Worker class in the ThreadPoolExecutor. All the workers are stored in a map as long as they are not completed. Upon completion or termination, they are removed from the map. The Worker, and by extension the Thread and Runnable are garbage, and will be picked up.


text:
Q: How can I get the number of entities by type? I have tried to get it using:
http://ip:1026/v2/entities?type=Audi&details=on

It doesn't work.

A: Try:
GET /v2/entities?type=Audi&options=count

You should get the count in the fiware-total-count header in the response.
Maybe you find useful the pagination documentation in the Orion manual.


text:
Q: WPF MenuItem apply style to boxed header I'm currently trying to apply styling to my menuItem. I had to center it's header inside the control, and the only way to it that I had found is this:
<MenuItem>
    <MenuItem.Header>
        <TextBlock Text="About" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </MenuItem.Header>
</MenuItem>

Now, I am trying to apply styles, but I can't seem to manage to bind the textboxes' text from style to the actual xaml value.
My style:
<Style x:Key="MenuItemBaseStyle" TargetType="MenuItem">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Background" Value="#0a99f3" />
                    <Setter Property="Foreground" Value="White"/>
                </Trigger>
            </Style.Triggers>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type MenuItem}">
                        <Grid Background="{TemplateBinding Background}">
                            <MenuItem>
                                <MenuItem.Header>
                                    <TextBlock Text="{TemplateBinding Text}" />
                                </MenuItem.Header>
                            </MenuItem>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

TemplateBinding is just one of the approaches I tried, though none worked even remotely close.
EDIT - FULL XAML ON REQUEST:
<Window x:Class="DownloadManager.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DownloadManager"
        xmlns:controls="clr-namespace:DesignInControl"
        mc:Ignorable="d"
        Title="MainWindow" Height="700" Width="1000" Background="#22282a" ResizeMode="NoResize">
    <Border BorderThickness="1" BorderBrush="#ffcd22" Margin="10,10,10,10">
        <Grid>
            <controls:CircularProgressBar VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,10,10" SegmentColor="#ffcd22" StrokeThickness="5" Percentage="100" Radius="80" Grid.ZIndex="0"/>
            <Border VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,10,10" Width="170" Height="170">
                <TextBlock FontSize="60" Text="10%" FontFamily="simplifica" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Border>
            <Image x:Name="noshare_png" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="-8,10" Source="noshare.png" Width="100" Height="100"/>
            <Border Width="210" Height="100" Margin="97,10,665,540">
                <TextBlock Text="NoShare" FontSize="85" FontFamily="simplifica" Foreground="#ffcd22" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </Border>
            <Menu x:Name="menu" HorizontalAlignment="Left" Height="100" Margin="352,10,0,0" VerticalAlignment="Top" Width="600" FontFamily="simplifica" FontSize="30">
                <MenuItem Height="100" Width="200" Style="{StaticResource MenuItemBaseStyle}">
                    <MenuItem.Header>
                        <TextBlock Text="File"/>
                    </MenuItem.Header>
                </MenuItem>
                <MenuItem Height="100" Width="200" Style="{StaticResource MenuItemBaseStyle}">
                    <MenuItem.Header>
                        <TextBlock Text="Settings"/>
                    </MenuItem.Header>
                </MenuItem>
                <MenuItem Height="100" Width="200" Style="{StaticResource MenuItemBaseStyle}">
                    <MenuItem.Header>
                        <TextBlock Text="About"/>
                    </MenuItem.Header>
                </MenuItem>
            </Menu>
        </Grid>
    </Border>
</Window>

A: Use MenuItem.HeaderTemplate.
<Style x:Key="MenuItemBaseStyle" TargetType="MenuItem">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{Binding}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="#0a99f3" />
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
</Style>

Updated: Combined your style with the original solution.


text:
Q: Assign an object to an array within a loop in VBA I try to fill an array with objects that are created within a loop as follows. The problem is that all cells seem to have the same object in the end. The explanation might be that obj is not a local variable with respect to the loop.
Sub foo()
    Dim Arr(1 To 3) As Class1
    Dim i As Integer
    For i = 1 To 3
        Dim obj As New Class1
        obj.name = i
        Set Arr(i) = obj
    Next
    For i = 1 To 3
        Debug.Print Arr(i).name
    Next
End Sub

Surprisingly, the output is
3
3
3

I have also tried to remove the Set and instead have Arr(i) = obj. That results in Object variable or with block variable not set.

A: Your issue is the declaration of your object.
Dim foo as New bar

That is called a self-assigned declaration what makes setting a new object optional. If you call an objects member and it is not allready set it get's created (implicitSet foo = New bar). But as you allready created an instance (on first call toobj.name). that one is reused and the same reference is stored three times for the same objects-instance. That's why all elements in array return the same value as they are the same objects-instance, not three different ones.
So don't useNewin declarations, then you always need aSet fooand can check the object instance onNothing.
A second issue with your code is that assigninig an object to an array is that deleting elements from an array is error prone and not deleted references lead to not disposed, but unused objects.
The prefered storage for object(-references) is aCollection.
Sub foo()
    Dim ObjCollection as Collection
    Set ObjCollection = New Collection
    Dim i As Integer
    For i = 1 To 3
        Dim obj As bar
        Set obj = New bar
        obj.name = i
        ObjCollection.Add obj
    Next
    For i = 1 To 3
        Debug.Print ObjCollection(i).name
    Next
End Sub

A: This is the way:-
Sub foo()
    Dim Arr(1 To 3) As Variant
    Dim i As Integer

    For i = 1 To 3
        Set Arr(i) = Worksheets(i)
    Next
    For i = 1 To 3
        Debug.Print Arr(i).Name
    Next
End Sub

A: You have 2 ways to do this:
Notes: obj has not been recreated, so when you call for the next time obj in Arr (1) is still affected by the subsequent call.
First:
Sub foo()
    Dim Arr(2) As Variant

    Dim i As Integer
    Dim obj As New Class1
    For i = 0 To 2
        Set obj = New Class1 '<<<-----
        obj.name = i
        Set Arr(i) = obj
    Next
    For i = 0 To 2
        Debug.Print Arr(i).name
    Next
End Sub

Second:
Sub foo()
    Dim Arr(2) As Variant
    Dim i As Integer
    For i = 0 To 2
        Dim obj As New Class1
        obj.name = i
        Set Arr(i) = obj
        Set obj = Nothing  <<<-----
    Next
    For i = 0 To 2
        Debug.Print Arr(i).name
    Next
End Sub

A: Try this, it'll save you a lot of headaches. Cheers!
Option Explicit

Sub foo()
    Dim Arr(1 To 3) As New Class1 ' < good to know this version
    Dim i As Long
    For i = 1 To 3
       With Arr(i) ' < saves you some typing
          .Name = i
          Debug.Print .Name
       End With
    Next
End Sub


text:
Q: How to Publish an Azure Bot Just learning how to use Azure Bot Service and Azure Bot Framework. I created a Bot in Azure portal following this Official Azure tutorial. Does this bot need to be published somewhere? I read somewhere that you Build-->Test-->Publish-->Evaluate. I've tested it in Azure portal itself as explained here. Not sure about the Publish part of it.

A: How do you intend to use your bot? Azure Bots work by connecting them to existing channels like Skype, Facebook Messenger, SMS, etc or making REST calls from a custom application.
However you can also reach your bot directly from: https://webchat.botframework.com/embed/YOUR_BOT_ID?t=YOUR_TOKEN_HERE
You can embed it on any web page with this HTML tag:
<iframe src="https://webchat.botframework.com/embed/YOUR_BOT_ID?t=YOUR_TOKEN_HERE"></iframe>

Please note that both of these methods expose your token and would allow other developers to add your bot to their pages as well.
Bot ID is the name of your bot and you can get the token from the portal by going to your bot and choosing "Channel" blade and then clicking the "Get bot embed codes" link.
Edit: I went ahead and wrote a blog post on this topic https://medium.com/@joelatwar/how-to-embed-your-azure-web-app-bot-in-any-web-page-120dfda91fdc

A: When you create a web app bot in the Azure portal, an App service for the same bot would have been created. You can check this by going to the resource group in azure where you had created the bot in. Now what the web app ensures is that, the bot is already online (available to the world), so its already published.
Now the next question that comes is, how to make the other people / users use the bot, so that's where the channel comes in. Consider channel as a medium by which you enable your bot for others to use with a much better user experience.
There are multiple channels available for the bot to be published in, and yes you can publish the same bot in all the channels. Like Joel Guerra mentioned, webchat is just one channel and the one which is enabled by default and the way to see it is :

*

*Open your bot in the Azure Portal and click Channels blade.

*Click Edit for the Web Chat channel

*Under Secret keys, click Show for the first key

*Copy the Secret key and the Embed code.

*Click Done
So the embed code is actually an iframe which you can place in your website or share with others who want to use your bot. Or you can use the src of the iFrame too to reach the bot directly.
Again this is just one channel. You can take a look at the Configure channels documentation for steps to enable the bot in more channels like Skype, Microsoft Teams, Email, Facebook, Slack, Telegram, etc.

A: You can find information here Publish bot to BotService
Hope this helps.


text:
Q: Rank of the harmonics in a Fourier series expansion Let $\boldsymbol{A}(t)$ be a $T$-periodic matrix with rank $r$, and $\boldsymbol{A}_n$ the harmonics of its Fourier series expansion, so that
$$
\boldsymbol{A}(t) = \sum_{n=-\infty}^{+\infty} \boldsymbol{A}_n e^{\mathrm{i}n\frac{2\pi}{T} t}.
$$
Also the matrices $\boldsymbol{A}_n$ will be of rank $r$?

A: This already fails in the $1$-dimensional case: a nonzero function may have some  Fourier coefficients equal to zero.
Let $A(t) = I \,\exp(2\pi in t/T)$, where $I$ is the identity matrix of size $r$. Then the rank of $A(t)$ is $r$ for all $t$, but the coefficient $A_2$ is the zero matrix. (As are all coefficients except $A_1=I$).


text:
Q: Run a C program from within a C program The question pretty much explains itself I have three different C programs and to try and compare their efficiency I tried to test their runtime by making them run several times varying their parameter (which is proportional to time taken) and write how long it takes each program to run for certain parameter (so later i can plot the results).
The following is my code
   # include <stdio.h>
    # include <stdlib.h>
    # include <math.h>
    # include <time.h>

   int main(void){

    int i;
    struct timeval bni, bmi, bfi, bnf, bmf, bff;
    FILE *in;
    char filename1[30] = "shuff.dat";
    int a1,a2,b1,b2,c1,c2;
    char command[100];

    in = fopen(filename1, "w");
    //for(i = 0; i<=100000; i +=100){
    for(i = 0; i<=10; i +=1){

        if (snprintf(command, sizeof(command), "./barajas_n.x %d", i) < sizeof(command)){
        a1 = gettimeofday(&bni , NULL);
        system(command);
        a2 = gettimeofday(&bnf , NULL);
        }

        if (snprintf(command, sizeof(command), "./barajas_m.x %d", i) < sizeof(command)){
        b1 = gettimeofday(&bmi , NULL);
        system(command);
        b2 = gettimeofday(&bmf , NULL);
        }

        if (snprintf(command, sizeof(command), "./barajas_fy.x %d", i) < sizeof(command)){
        c1 = gettimeofday(&bfi , NULL);
        system(command);
        c2 = gettimeofday(&bff , NULL);
        }
        fprintf(in, "%d %d %d %d \n", i, (a2-a1),(b2-b1),(c2-c1));
    }
    fclose(in);
}

I get the following message on the terminal window:

Which means this program is running all of its steps, only not correctly executing the programs I want to time.
I've tested all three programs individually in the terminal like this
./barajas_*.x i

*

*Can someone please tell me why system() is taking it's input as a directory and,

*how to tell system() it to stop taking it as a directory and execute it?

EDIT: After a long discusion in a chat room the problem was as said by Jonathan Leffler: " a mismatch between the actual command name that existed and the command name that the program was attempting to run."
The actual question is answered by iharob's contribution, for anyone interested the snippet he provided should work if the command name matches the command name being run by the program.

A: The system() function takes only one argument of type const char *, if you need to build the command try with snprintf(), like this
char command[100];

if (snprintf(command, sizeof(command), "barajas_n.x %d", i) < sizeof(command))
{
    a1 = gettimeofday(&bni , NULL);
    system(command);
    a2 = gettimeofday(&bfi , NULL);
}

also, the return value of gettimeofday() is not useful for calculating the time difference. It's just to check errors, you can get the elapse time using this function
float elapsed_time(struct timeval *end, struct timeval *start)
{
    struct timeval result;
    if (end->tv_usec - start->tv_usec > 1.0E6)
    {
        double adjust;

        adjust          = (end->tv_usec - start->tv_usec) / 1.0E6;
        start->tv_usec += 1.0E6 * adjust;
        start->tv_sec  -= adjust;
    }
    result.tv_sec  = end->tv_sec  - start->tv_sec;
    result.tv_usec = end->tv_usec - start->tv_usec;

    return result.tv_sec + result.tv_usec / 1.0E6;
}

and then to print the elapsed time
printf("Elapsed time: %f\n", elapsed_time(&bni, &bfi);

As the other answer mentioned you need to add a slash to execute the programs, ./programname instead of .programname, but this is another solution:
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <unistd.h>

#include <sys/time.h>
#include <time.h>

/* This function, just calculates the difference in seconds, between end and start */
float elapsed_time(struct timeval *end, struct timeval *start)
{
    struct timeval result;
    if (end->tv_usec - start->tv_usec > 1.0E6)
    {
        float adjust;

        adjust          = (end->tv_usec - start->tv_usec) / 1.0E6;
        start->tv_usec += 1.0E6 * adjust;
        start->tv_sec  -= adjust;
    }
    result.tv_sec  = end->tv_sec  - start->tv_sec;
    result.tv_usec = end->tv_usec - start->tv_usec;

    return result.tv_sec + result.tv_usec / 1.0E6;
}

/* this function will execute the command and wrap the system call
 * with 'gettimeofday()' so you can return the elapsed time while
 * the called program was running.
 *
 * It also builds the command string with the right parameter.
 */
float run_command_and_return_time(const char *const program, int parameter)
{
    char           command[100];
    struct timeval start;
    struct timeval end;
    int            result;
    /* check that sprintf didn't need more characters */
    result = snprintf(command, sizeof(command), "%s %d", program, parameter);
    if ((result >= sizeof(command)) || (result < 0))
        return -1.0;
    gettimeofday(&start, NULL);
    system(command);
    gettimeofday(&end, NULL);

    return elapsed_time(&end, &start);
}

int
main(int argc, char **argv)
{
    char        cwd[PATH_MAX];
    const char *filename;
    FILE       *output;

    filename = "shuff.dat";
    output   = fopen(filename, "w");
    if (output == NULL)
        return -1;
    /* get the current working directory */
    getcwd(cwd, sizeof(cwd));
    /* add the cwd to the PATH variable, so your barajas_*.x programs are found,
     * this way you don't need the ./bara... anymore, just bara... will do it.
     */
    setenv("PATH", cwd, 1);
    /* from here it's pretty evident what the program does */
    for (int i = 0 ; i < 10 ; ++i)
    {
        float a, b, c;

        a = run_command_and_return_time("barajas_n.x", i);
        b = run_command_and_return_time("barajas_m.x", i);
        c = run_command_and_return_time("barajas_fy.x", i);

        fprintf(output, "%d %f %f %f \n", i, a, b, c);
    }
    /* don't forget to close the output file */
    fclose(output);

    return 0;
}

A: I note that your code currently reads:
if (snprintf(command, sizeof(command), ".barajas_n.x %d", i) < sizeof(command)){

It looks to me like you're missing a slash in that:
if (snprintf(command, sizeof(command), "./barajas_n.x %d", i) < sizeof(command)){

If that's just a typo, then one remaining problem is that gettimeofday() always returns 0:

The gettimeofday() function shall return 0 and no value shall be reserved to indicate an error.

Any elapsed time is found by computation on the struct timeval structures, more or less as shown in the answer by iharob.
Post-chat synopsis
I invited Carlos to chat with me.
After a bit of discussion in chat and seeing the actual results of running the program, we discovered that the problem was a typo — a mismatch between the actual command name that existed and the command name that the program was attempting to run.


text:
Q: Função jquery não funciona CSS:
.nav {
    width: 15%;
    height: 800px;
    background-color: #421;
    margin-top: 55px;
    float: left;
}
.nav-min {
    width: 5% !important;
    background-color: #ccc !important;
}

JS:
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
    $('#btn').click(function() {
            $('.nav').toggleClass('nav-min');
        });
</script>

HTML:
<nav class="nav">
    <button class="btn btn-menu" id="btn">Menu</button>
</nav>

Aqui tem testes que fiz e funcionaram
http://jsfiddle.net/ukpm1uey/3/
porém não rodou no localhost, alguém sabe o que pode ser?, já verifiquei se esta salvando, mas mesmo assim não funciona de maneira alguma

A: No localhost deve ter colocado na mesma ordem que fez a pergunta.
Isso quer dizer.:
<script type="text/javascript">
   $('#btn').click(function() {
        $('.nav').toggleClass('nav-min');
   });
</script>

Está primeiro do que.:
<nav class="nav">
   <button class="btn btn-menu" id="btn">Menu</button>
</nav>

Por isso não está a funcionar.
2 maneiras de ultrapassar

*

*Colocar o script no fim da pasta

*Alterar para.:
<script type="text/javascript">
  $(document).ready(function(){
     $('#btn').click(function() {
        $('.nav').toggleClass('nav-min');
     });
  });
</script>


text:
Q: Bokeh - How to Click and Drag? I would like to click-and-drag the scatter points the points of a bokeh scatter plot. Any ideas how to do this?
(edit: this is an example of what I'd like to do)
For an example of a scatter, the code below generates the scatter plot chart found half-way through this page.
from bokeh.plotting import figure, output_file, show

# create a Figure object
p = figure(width=300, height=300, tools="pan,reset,save")

# add a Circle renderer to this figure
p.circle([1, 2.5, 3, 2], [2, 3, 1, 1.5], radius=0.3, alpha=0.5)

# specify how to output the plot(s)
output_file("foo.html")

# display the figure
show(p)

A: Multi-gesture edit tools are only a recent addition, landing in version 0.12.14. You can find much more information in the Edit Tools section of the User's Guide.
Specifically to be able to move points as described in the OP, use the PointDrawTool:

Here is a complete example you can run that also has a data table showing the updated coordinates of the glyphs as they are moved (you will need to activate the tool in the toolbar first, it is off by default):
from bokeh.plotting import figure, output_file, show, Column
from bokeh.models import DataTable, TableColumn, PointDrawTool, ColumnDataSource

output_file("tools_point_draw.html")

p = figure(x_range=(0, 10), y_range=(0, 10), tools=[],
           title='Point Draw Tool')
p.background_fill_color = 'lightgrey'

source = ColumnDataSource({
    'x': [1, 5, 9], 'y': [1, 5, 9], 'color': ['red', 'green', 'yellow']
})

renderer = p.scatter(x='x', y='y', source=source, color='color', size=10)
columns = [TableColumn(field="x", title="x"),
           TableColumn(field="y", title="y"),
           TableColumn(field='color', title='color')]
table = DataTable(source=source, columns=columns, editable=True, height=200)

draw_tool = PointDrawTool(renderers=[renderer], empty_value='black')
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool

show(Column(p, table))


text:
Q: Why doesn't C return an error when I use a large int Hello I am learning C and I believe I made a mistake in declaring
signed int testing=4294967295; I didn't think this would work because while I know I could create an unsigned int of that size I thought that the range of a signed int was -2,147,483,648 to 2,147,483,647, therefore I expected an overflow error but I didn't get one. Can someone please tell me why this is happening?

A: signed int overflow results in undefined behavior. Compiler may or may not produce any warning or error.
C11: 3.4.3 (p3):

An example of undefined behavior is the behavior on integer overflow

A: Overflow is not an error. It is just a bahaviour of int. I guess that in your case when overflow has happened your int just have different value than the one you've set.
Try printing int value. Depending on your settings and hardware many things can happen, but you will see some strange behaviour.

A: The C standard states:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

That means if you get an overflow, you're out of luck - no behavior of any kind guaranteed. Unsigned types are a special case, and never overflow .


text:
Q: Develop a website for an iPhone without having iPhone/Mac I need to develop a website which will be used exclusively on iPhone and iPad. I don't have those devices, neither do I have a Mac.
What are the possible free solutions for me to be able to test the website during development?
The most obvious one would be to use an iPhone SDK, but since it costs $100/year but since it is available only for Mac, it is not a solution in my case.

A: You can test your website in any browser, but yes, mobile browser probably behave different at some points.
If you cannot find a mobile web browser simulator for iPhone than the "cheapest" alternative would probably be an iPod touch.
Update:
You might want to have a look at iBBDemo:

iBBDemo2 - Cross Platform iPad and iPhone Simulator

A: You could try using something like:
www.testiphone.com/

A: Download Safari 5 for Windows, enable the Developer Menu features and change the User Agent to Mobile Safari iPad or Mobile Safari iPhone. This will let you see how your website looks when an iPad or iPhone renders it. Just make the window smaller to get the full experience.
If analyst predictions are right, there will soon likely be an abundance of iPhone 3G devices on eBay as lots of people are eligible to upgrade to iPhone 4 tomorrow. Picking up a cheap 3G may be the best solution to your testing requirements.
Or you can test it out at an Apple Store if your website is accessible over the internet or available on a laptop with an ad-hoc WiFi connection.

A: Recommend you use jsconsole
Remotely debug a mobile web app
jsconsole.com is a simple JavaScript command line tool. However, it also provides the ability to bridge across to other browser windows to remotely control and debug that window - be it in another browser or another device altogether.
In fact, mobile web app debugging is so damn tricky, that I gave up, and decided to build this very tool instead. See the videos examples if you'd rather see this in action now.
Creating a session
To create a new session, in the jsconsole prompt, simply run:
:listen

This will yield a unique key along the lines of FAE031CD-74A0-46D3-AE36-757BAB262BEA. Now using this unique key, include a  anywhere in the web app that you wish to debug:
<script src="http://jsconsole.com/remote.js?FAE031CD-74A0-46D3-AE36-757BAB262BEA"></script>

Now any calls to console.log from your web app will display the result in the jsconsole session that is listening to your key. Equally, if you run a command in the jsconsole session, the code will injected in to your web app and the result returned to jsconsole.
In addition to generating a new code with :listen, you can also ask jsconsole to listen to a predefined code (but for your own security, try to chose something unique that only you know):
:listen FAE031CD-74A0-46D3-AE36-757BAB262BEA

Now I can use the same remote key in my web app to avoid having to regenerate a new code each time. Note that only the last remote client (i.e. your web app) to connect to jsconsole will recieve remote debug calls - previous windows will be ignored.
To know when the web app has connected, jsconsole will notify you by showing your the userAgent string for the device:
:listen FAE031CD-74A0-46D3-AE36-757BAB262BEA
Creating connection...
Connected to "FAE031CD-74A0-46D3-AE36-757BAB262BEA"
Connection established with Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8

A word of warning
Note that this technique is also injecting code directly in to your web app - this tool should only be used for debugging. I can't take respibility for how you use this tool, basically: take care!
Current known support
Remote debugging has been developed to work on all platforms, even if the technology isn't supported. However, jsconsole remote debugging has specifically tested and working on the follow mobile devices (feel free to add to this list):

*

*iOS 4.2.x - iPad, iPhone 4

*Andriod 2.2.2 - Nexus One

*webOS - Palm Pre
There are some Video examples too
More detailed information please see this links:
http://jsconsole.com/remote-debugging.html

A: There are some obvious things here:
1)Work very hard to make your site work on all major browsers - including Safari and any other mobile devices other than iPad... this will let you make sure it works on smaller screens well.
2)Read up on known glitches in these browsers and see if you can avoid them.
3)Whenever you are with friends showing off their iPad, or who have an iPhone, ask to test your site on it.

A:

I need to develop a website which will be used exclusively on iPhone and iPad

This seems a bad idea. if it's only used on iPad/iPhone, surely you should write an App and get all the benefits of UI, etc.

A: Websites should not be tied to specific devices.
This is not 1998 : Best viewed in I.E. In fact your suggestion is worse than that.
If you really want a website that only works on those devices then you'll need to check the user-agent string, but otherwise html is html and unlike what Apple may want you to believe, works just as well on Symbian, Blackberry, Android, S40, Windows, Windows Mobile, etc etc..
(In fact, it works better on Symbian as Symbian actually supports Flash.)


text:
Q: I am getting the Heroku H12 - Request timeout error for no apparent reason In my parse server I have a class called Stats which contains the column timeScore (number)
I am using cloud code to update all 250k rows in the column timeScore.
My code works well except for the fact that I get the following H12 - Request timeout error for no apparent reason.
heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/parse/functions/timeScore

I get the timeout error regardless of what batchSize I choose and I get it every 30 seconds. I get it for a total of 5 times. After the 5th time I dont get it anymore and the process continues and finishes without any issues or errors. I get the 5th and last error at around 2.5 minutes into the process (30seconds*5).The whole process takes about 14 minutes. These timeout errors does not effect the process in any way. All 250k objects are updated and saved regardless of the selected batchSize and despite the timeout errors.
I thought maybe because I never call results.error or results.success the server thinks I am still doing some work and shows the error. However I updated my code as seen below to include them and I still get the timeout errors.
The problem is after each timeout error processBatch() is called once again from the beggining. Since I get 5 timeout errors processBatch() gets called 5 times. So after the 5th timeout error there are 5 processBatch() functions running simultaneously (I confirmed this with logs). This makes the process take much longer that it should take.
I am not performing any long running actions. I am just updating and saving data on my parse server.
Here is my code:
var _ = require("underscore");
Parse.Cloud.define("timeScore", function(request, response) {
var counter = 0;
function processBatch(query, batchSize, startingAt, process) {
    query.limit(batchSize);
    query.skip(startingAt);

    return query.find().then(results => {

        return process(results).then(() => results.length);
    }).then(length => {

        return (length === batchSize)? processBatch(query, batchSize, startingAt+length, process) : {};
    });
}

function setTimeScores(stats) {
        console.log("LENGTH " + stats.length);
    _.each(stats, stat => {

        counter ++;
        stat.set("timeScore", counter);

    });
    return Parse.Object.saveAll(stats);
}

var query = new Parse.Query("Stats");

processBatch(query, 1000, 0, setTimeScores).then(results => {
        response.success(results);
    }).catch(error => {
        response.error(error);
    });

});

Here is how I call it
#!/usr/bin/env node
var Parse = require("parse/node");
Parse.initialize("xx",   "xx");
Parse.serverURL = "http://randomapp.herokuapp.com/parse";
Parse.Cloud.run('timeScore');

What is causing the heroku timeout errors I am getting? How do I fix it?


text:
Q: Absolute positioned ::before element ignores z-index stacking I am creating a very simple navbar and I want hover transitions on the links. I would like to add ::before elements in each link to smoothly transition a different color background on hover. The problem is (as far as I am concerned) that those ::before elements ignore their z-index staking and they hide the link text behind.
I would link to know if I am trying to do something impossible or there is actually a solution I am unable to find.

ul.menu-principal>li {
  display: inline-block;
}

ul.menu-principal>li>a {
  color: #000;
  display: block;
  text-transform: uppercase;
  padding: 10px;
  position: relative;
  z-index: 96;
}

ul.menu-principal>li>a::before {
  content: '';
  position: absolute;
  z-index: 95;
  top: 0;
  left: 0;
  width: 100%;
  height: 0;
  background: orange;
  transition: all .2s linear;
}

ul.menu-principal>li>a:hover::before {
  height: 100%;
}

ul.menu-principal>li:hover a {
  color: #fff;
}

Item-01

Item-01

Item-01

Item-01

Website
http://canfosses.mastercamping.com
Thank you all for the responses.

A: You can just use for your case z-index: -1:

ul.menu-principal>li {
  display: inline-block;
}

ul.menu-principal>li>a {
  color: #000;
  display: block;
  text-transform: uppercase;
  padding: 10px;
  position: relative;
  z-index: 96;
}

ul.menu-principal>li>a::before {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  width: 100%;
  height: 0;
  background: orange;
  transition: all .2s linear;
}

ul.menu-principal>li>a:hover::before {
  height: 100%;
}

ul.menu-principal>li:hover a {
  color: #fff;
}

Item-01

Item-01

Item-01

Item-01


text: Q: How to pass additional compiler/linker options in msbuild command line? So the thing is I am trying to do something that requires adding additional compiler and linker options while building a project. I do not want that option to be added to the default compile options so that it is not messed up for others. In visual studio I can add additional options to the compiler and linker by editing the properties of the project. It will be good to have a one-time switch between adding or not adding these additional options. Say in command line using msbuild /compilerOption /linkerOption to add these addiontal options. Or having a configure file that can be loaded by msbuild command. Is there a good way to do that? Thanks!


text:
Q: Error while deploying Spring Batch in Weblogic BeanCreationException: Error creating bean with name 'jobRepository' I want to test Spring Batch, but I need to use it without maven or gradle because there are some restrictions in the network. I read a tutorial on spring  and the spring documentation to configure a Job, but I get an "Error creating bean with name 'jobRepository'"
This question has been asked already without an answer.
I'm using Jeveloper and Weblogic 12.1.3.0.0.
My project has the following dependencies which I get from another project configured with Eclipse Maven:
com.ibm.jbatch-tck-spi-1.0.jar
commons-logging-1.2.jar
hsqldb-2.3.3.jar
javax.batch-api-1.0.jar
jcl-over-slf4j-1.7.12.jar
jettison-1.2.jar
jul-to-slf4j-1.7.12.jar
log4j-over-slf4j-1.7.12.jar
logback-classic-1.1.3.jar
logback-core-1.1.3.jar
slf4j-api-1.7.12.jar
snakeyaml-1.14.jar
spring-aop-4.1.8.RELEASE.jar
spring-aspects-4.1.8.RELEASE.jar
spring-batch-core-3.0.5.RELEASE.jar
spring-batch-infrastructure-3.0.5.RELEASE.j
spring-beans-4.1.8.RELEASE.jar
spring-context-4.1.8.RELEASE.jar
spring-context-support-4.1.8.RELEASE.jar
spring-core-4.1.8.RELEASE.jar
spring-expression-4.1.8.RELEASE.jar
spring-instrument-4.1.8.RELEASE.jar
spring-instrument-tomcat-4.1.8.RELEASE.jar
spring-jdbc-4.1.8.RELEASE.jar
spring-jms-4.1.8.RELEASE.jar
spring-messaging-4.1.8.RELEASE.jar
spring-orm-4.1.8.RELEASE.jar
spring-oxm-4.1.8.RELEASE.jar
spring-test-4.1.8.RELEASE.jar
spring-tx-4.1.8.RELEASE.jar
spring-web-4.1.8.RELEASE.jar
spring-webmvc-4.1.8.RELEASE.jar
spring-webmvc-portlet-4.1.8.RELEASE.jar
spring-websocket-4.1.8.RELEASE.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.7.jar

The java classes are:
JobLauncherController.java
package batch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class JobLauncherController {
    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job job;

    @RequestMapping("/jobLauncher.html")
    public String handle() throws Exception{
        System.err.println("Hello Spring Batch!");
        jobLauncher.run(job, new JobParameters());
        return "redirect:index";
    }
}

MyTasklet.java
package batch;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

public class MyTasklet implements Tasklet{

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
        System.err.println("¡Hello World TASKLET!");
        return RepeatStatus.FINISHED;
    }
}

web.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Test Batch App</display-name>

   <servlet>
      <servlet-name>testBatch</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>testBatch</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
       <jsp-config>
    <taglib>
        <taglib-uri>http://www.springframework.org/tags/form</taglib-uri>
        <taglib-location>/WEB-INF/spring-form.tld</taglib-location>
    </taglib>
</jsp-config>
</web-app>

testBatch-servlet.xml
<beans:beans xmlns="http://www.springframework.org/schema/batch"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="batch"/>
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>
     <beans:bean id="transactionManager"
                class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"></beans:bean>
    <beans:bean id="jobRepository"
                class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
        <beans:property name="transactionManager" ref="transactionManager"/>
    </beans:bean>
    <beans:bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <beans:property name="jobRepository" ref="jobRepository"/>
        <beans:property name="taskExecutor">
            <beans:bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
        </beans:property>
    </beans:bean>
    <beans:bean id="myTasklet" class="batch.MyTasklet"></beans:bean>
    <job id="job">
        <step id="test">
            <tasklet ref="myTasklet"/>
        </step>
    </job>
</beans:beans>

And last but not least, the stacktrace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherController': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.batch.core.launch.JobLauncher batch.JobLauncherController.jobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeweblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
        at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
        at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.batch.core.launch.JobLauncher batch.JobLauncherController.jobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
        at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
        ... 66 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
        ... 68 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:269)
        ... 83 more
    Caused by: java.lang.reflect.MalformedParameterizedTypeException
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:53)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:95)
        at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
        at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
        at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
        at sun.reflect.generics.repository.ClassRepository.getSuperInterfaces(ClassRepository.java:100)
        at java.lang.Class.getGenericInterfaces(Class.java:814)
        at org.springframework.core.GenericTypeResolver.getTypeVariableMap(GenericTypeResolver.java:164)
        at org.springframework.core.GenericTypeResolver.resolveReturnType(GenericTypeResolver.java:101)
        at org.springframework.beans.GenericTypeAwarePropertyDescriptor.getPropertyType(GenericTypeAwarePropertyDescriptor.java:88)
        at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:138)
        at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:386)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1289)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        ... 92 more
    <21/10/2015 02:01:45 AM COT> <Error> <HTTP> <BEA-101216> <Servlet: "testBatch" failed to preload on startup in Web application: "testBatch".
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherController': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.batch.core.launch.JobLauncher batch.JobLauncherController.jobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        Truncated. see log file for complete stacktrace
    Caused By: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.batch.core.launch.JobLauncher batch.JobLauncherController.jobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
        at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        Truncated. see log file for complete stacktrace
    Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
        Truncated. see log file for complete stacktrace
    Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/testBatch-servlet.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
        Truncated. see log file for complete stacktrace
    Caused By: java.lang.reflect.MalformedParameterizedTypeException
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:53)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:95)
        at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
        at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
        Truncated. see log file for complete stacktrace
    >
    WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.
    WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.
    <21/10/2015 02:01:45 AM COT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "32136025790510" for task "15". Error is: "weblogic.application.ModuleException: java.lang.reflect.MalformedParameterizedTypeException"
    weblogic.application.ModuleException: java.lang.reflect.MalformedParameterizedTypeException
        at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
        Truncated. see log file for complete stacktrace
    Caused By: java.lang.reflect.MalformedParameterizedTypeException
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:53)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:95)
        at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
        at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
        Truncated. see log file for complete stacktrace
    >
    <21/10/2015 02:01:45 AM COT> <Error> <Deployer> <BEA-149202> <Encountered an exception while attempting to commit the 9 task for the application "TestBatch".>
    <21/10/2015 02:01:45 AM COT> <Warning> <Deployer> <BEA-149004> <Failures were detected while initiating deploy task for application "TestBatch".>
    <21/10/2015 02:01:45 AM COT> <Warning> <Deployer> <BEA-149078> <Stack trace for message 149004
    weblogic.application.ModuleException: java.lang.reflect.MalformedParameterizedTypeException
        at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
        Truncated. see log file for complete stacktrace
    Caused By: java.lang.reflect.MalformedParameterizedTypeException
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:53)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:95)
        at

Any suggestion will be appreciated, thanks in advance.
UPDATE
I think is something related to Weblogic 12.1.3.0(12c). I made a web project in Netbeans (with and without Maven), and these work fine. Maybe Weblogic requires some special configuration?
the following jars were generated with netbeans and maven (spring-batch-core, 3.0.5.RELEASE and spring-webmvc, 4.0.5.RELEASE) as Malguna said
aopalliance-1.0.jar
com.ibm.jbatch-tck-spi-1.0.jar
commons-logging-1.1.3.jar
javax.batch-api-1.0.jar
jettison-1.2.jar
spring-aop-4.0.5.RELEASE.jar
spring-batch-core-3.0.5.RELEASE.jar
spring-batch-infrastructure-3.0.5.RELEASE.jar
spring-beans-4.0.5.RELEASE.jar
spring-context-4.0.5.RELEASE.jar
spring-core-4.0.5.RELEASE.jar
spring-expression-4.0.5.RELEASE.jar
spring-retry-1.1.0.RELEASE.jar
spring-tx-4.0.5.RELEASE.jar
spring-web-4.0.5.RELEASE.jar
spring-webmvc-4.0.5.RELEASE.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.7.jar

UPDATE II
I made a workaround to this issue, although It doesn't tackle the real problem It let me keep forward in what I really want. That is, making Jdeveloper (12c), Weblogic and Spring Batch work together.
I add a jobRepository and a datasource whit hsqldb in the testBatch-servlet.xml. After that, add hsqldb-2.3.3.jar and spring-jdbc-4.0.5.RELEASE.jar

    <beans:bean id="jobRepository" class="org.springframework.batch.core.repository.support.SimpleJobRepository">
        <beans:constructor-arg>
            <beans:bean class="org.springframework.batch.core.repository.dao.MapJobInstanceDao"/>
        </beans:constructor-arg>
        <beans:constructor-arg>
            <beans:bean class="org.springframework.batch.core.repository.dao.MapJobExecutionDao" />
        </beans:constructor-arg>
        <beans:constructor-arg>
            <beans:bean class="org.springframework.batch.core.repository.dao.MapStepExecutionDao"/>
        </beans:constructor-arg>
        <beans:constructor-arg>  <!-- Extra constructor argument -->
            <beans:bean class="org.springframework.batch.core.repository.dao.MapExecutionContextDao"/>
        </beans:constructor-arg>
    </beans:bean>

A: If you get an java.lang.reflect.MalformedParameterizedTypeException this means there are some class that is trying to use a method by means of reflection, but it has malformed the parameters needed to call it.
This is common when you have wrong dependencies, that is, when you are using wrong dependency version and thus a dependent method has changed its parameters list.
I created a void pom.xml with only spring-batch-core version 3.0.5.RELEASE and it gives me the following dependencies list:
aopalliance-1.0.jar
com.ibm.jbatch-tck-spi-1.0.jar
commons-logging-1.1.3.jar
javax.batch-api-1.0.jar
jettison-1.2.jar
spring-aop-4.0.5.RELEASE.jar
spring-batch-core-3.0.5.RELEASE.jar
spring-batch-infrastructure-3.0.5.RELEASE.jar
spring-beans-4.0.5.RELEASE.jar
spring-context-4.0.5.RELEASE.jar
spring-core-4.0.5.RELEASE.jar
spring-expression-4.0.5.RELEASE.jar
spring-retry-1.1.0.RELEASE.jar
spring-tx-4.0.5.RELEASE.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.7.jar

So as you can see, you are using spring version 4.1.8.RELEASE instead 4.0.5.RELEASE. This could be the cause of your error.
Please review your hand managed dependencies to fit those I shown you. Maybe it resolves your problem.
Hope it helps!

A: To solve the problem I need to use Spring Batch 2.2.7 together with Weblogic 12.1.3.
I thought that The error was configuration in my xml file but It seems that is a support issue with weblogic, because I found a similar error later.
The dependency list:
 aopalliance-1.0.jar
 commons-logging-1.1.3.jar
 jettison-1.1.jar
 spring-aop-3.2.9.RELEASE.jar
 spring-batch-core-2.2.7.RELEASE.jar
 spring-batch-infrastructure-2.2.7.RELEASE.jar
 spring-beans-3.2.9.RELEASE.jar
 spring-context-3.2.9.RELEASE.jar
 spring-core-3.2.9.RELEASE.jar
 spring-expression-3.2.9.RELEASE.jar
 spring-retry-1.0.2.RELEASE.jar
 spring-tx-3.2.9.RELEASE.jar
 spring-web-3.2.9.RELEASE.jar
 spring-webmvc-3.2.9.RELEASE.jar
 xpp3_min-1.1.4c.jar
 xstream-1.3.jar


text:
Q: How to fit image in PictureBox C#? I was set in PictureBox is:
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
But the result I receive is pictureBox1.Image very large.
How to fit the image in PictureBox?
I created gif animation to describe my problem.
Note:
In this gif image, pictureBox is custom control I added. And the parent of pictureBox1 is a pictureBoxParent. I create program to insert text(label) or logo(pictureBox) in main background image.
Update:
I add more code to show in gif I did.
This button creates a new PictureBox name ctrl.
public PictureBox ctrl = new PictureBox();

public void btnAddLogo_Click(object sender, EventArgs e)
{
    Random rnd = new Random();
    int randNumber = rnd.Next(1, 1000);
    String picName = "Pic_" + randNumber;
    //ctrl = new PictureBox();
    ctrl.Location = new Point(200, 170);
    ctrl.Size = new System.Drawing.Size(100, 60);
    ctrl.Name = picName;
    ctrl.SizeMode = PictureBoxSizeMode.Zoom;
    ctrl.Font = new System.Drawing.Font("NativePrinterFontA", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    ctrl.BackColor = Color.Chocolate;
    ctrl.MouseEnter += new EventHandler(control_MouseEnter);
    ctrl.MouseLeave += new EventHandler(control_MouseLeave);
    ctrl.MouseDown += new MouseEventHandler(control_MouseDown);
    ctrl.MouseMove += new MouseEventHandler(control_MouseMove);
    ctrl.MouseUp += new MouseEventHandler(control_MouseUp);
    picPreview.Controls.Add(ctrl);
    btnBackgroundImage.Enabled = true;
}

I've added ImageBackGround to ctrl PictureBox.
private void btnBackgroundImage_Click(object sender, EventArgs e)
{
    OpenFileDialog choofdlog = new OpenFileDialog();
    choofdlog.Filter = "All Files (*.*)|*.*";
    choofdlog.FilterIndex = 1;
    if (choofdlog.ShowDialog() == DialogResult.OK)
    {
        string sFileName = choofdlog.FileName;
        ctrl.Image = Image.FromFile(sFileName);
        ctrl.SizeMode = PictureBoxSizeMode.StretchImage;
    }
    else
    {
        return;
    }
}

In button save the image, I call again ctrl.SizeMode but not happen.
ctrl.SizeMode = PictureBoxSizeMode.StretchImage;
g.DrawImage(ctrl.Image, Point.Round(StretchImageSize(postPoint, picPreview)));

Describe my problem when using SizeMode in PictureBox


text:
Q: Why doesn't this query work on Heroku? Trying to implement a simple search with RoR and Heroku.  This works fine on localhost but as soon as I push to Heroku, the search returns no results.  I'm using SQlite locally and Heroku uses Postgres, correct?  I think this is the problem but after quite a bit of research I can't seem to find the solution.  Any idea what might be going on?  Help appreciated as always.
def self.search(search)
  if search
   where("title LIKE ? OR description LIKE ?", "%#{search}%", "%#{search}%")
  else
   find(:all)
  end
end

A: Probably because SQLite's LIKE is (partially) case insensitive but PostgreSQL's LIKE is case sensitive. Try this:
where("LOWER(title) LIKE ? OR LOWER(description) LIKE ?", "%#{search.downcase}%", "%#{search.downcase}%")

PostgreSQL also has ILIKE as a case insensitive version of LIKE but SQLite (nor standard SQL) doesn't so you shouldn't use ILIKE unless you are specifically targeting PostgreSQL.
And switch your development environment to PostgreSQL if you're publishing to Heroku, you will save yourself a fair bit of grief and confusion.
Another possibility is that you don't have any data (or any matching data) in your Heroku database.


text:
Q: Android BroadCastReceiver for volume key up and down If a user presses volume key up or down is it possible to detect it in my broadcast receiver? I need the full code.
Here is my Intent filter
IntentFilter filter = new IntentFilter();
filter.addAction("android.media.VOLUME_CHANGED_ACTION");

and my onReceive method is
public void onReceive(Context arg0, Intent intent) {
      KeyEvent ke = (KeyEvent)intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
        if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                System.out.println("I got volume up event");
         }else if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                System.out.println("I got volume key down event");
         }
    }

It gives me a null KeyEvent... any idea?

A: The intent does not have an EXTRA_KEY_EVENT extra. It does have an extra android.media.EXTRA_VOLUME_STREAM_VALUE which contains the new volume.
int volume = (Integer)intent.getExtras().get("android.media.EXTRA_VOLUME_STREAM_VALUE");

If you store the old value, you can infer whether volume up or down was pressed.


text:
Q: How to disable fotoroma fullscreen image gallery?
I want to disable fotoroma fullscreen image and I did that by disabling the fullscreen in view.xml in the theme but it doesn't make any effect.
Any help is appreciated.


text:
Q: Get latest AMI ID for AWS instance I wanted to fetch the latest ami id for AWS Linux machine while creating an ec2 instance for an autoscaling architecture.
I was trying the aws cli to get the images types, but it would print out a lot of information if I used the describe-images command.
My requirement was to get only the image id, so that I could use it to create a launch configuration or launch an instance with the latest ami-id.

A: A little-known recent feature is the ability to Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog.
The namespace is made up of two parts:

*

*Parameter Store Prefix (tree): /aws/service/ami-amazon-linux-latest/

*AMI name alias: (example) amzn-ami-hvm-x86_64-gp2
These:
aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn*" --query 'sort_by(Images, &CreationDate)[].Name'

Get-EC2ImageByName -Name amzn* | Sort-Object CreationDate | Select-Object Name

can be changed into:
aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --region us-east-1

Get-SSMParameter -Name /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 -region us-east-1

Plus, it can be used in a CloudFormation template:
# Use public Systems Manager Parameter
 Parameters :
 LatestAmiId :
 Type : 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
 Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'

Resources :
 Instance :
 Type : 'AWS::EC2::Instance'
 Properties :
 ImageId : !Ref LatestAmiId

A: From Ref:
https://aws.amazon.com/blogs/compute/query-for-the-latest-amazon-linux-ami-ids-using-aws-systems-manager-parameter-store/
For AWS CloudFormation Specifically:
# Use public Systems Manager Parameter
Parameters:
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'

Resources:
 Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Ref LatestAmiId

From AWS CLI:
aws ssm get-parameters-by-path --path "/aws/service/ami-amazon-linux-latest" --region us-east-1

Powershell:
Get-SSMParametersByPath -Path "/aws/service/ami-amazon-linux-latest" -region us-east-1

A: The answers by Vaulstein and John Rotenstein helped me understand this solution. Thank you!
In my case, we have a lot of private AMIs posted by different owners (there are 2-3) and there is a mix of their custom private AMIs created using CentOS or AmazonLinux2 as the base. The task is to find the latest AMI which works on the x86 architecture and is based on AmazonLinux2.
Note that I am not using --owner because in my case the AMIs are posted by different teams and have different Owner IDs. But if you have a single owner/team which posts these, this is a recommended option to include to filter out all other AMIs that you don't want.
This is what worked for us:
aws ec2 describe-images \
--query 'sort_by(Images, &CreationDate)[-1].Name' \
--region eu-west-1 \
--no-include-deprecated \
--executable-users self \
--output text \
--filters "Name=name,Values=here-ami-amzn2-*" \
    "Name=architecture,Values=x86_64" \
    "Name=image-type,Values=machine" \
    "Name=state,Values=available" \
    "Name=virtualization-type,Values=hvm" \
    "Name=root-device-type,Values=ebs"

Explanation:
What we are doing here is:
This gets the results sorted by CreationDate. We are grabbing the -1 (last/latest) item's name from the result.
--query 'sort_by(Images, &CreationDate)[-1].Name'

Note that the available AMIs may vary by region, so be sure to specify the region where you intend to instantiate it.
--region eu-west-1 \

To avoid deprecated AMIs, if any. We didn't have any but decided to be future safe.
--no-include-deprecated \

To ensure that the fetched AMI is actually usable by you.
--executable-users self \

This is optional. If its text, the AMI name is returned without the double quotes
--output text \

Filters are used to narrow down results and to exclude unwanted results. Fortunately, our organization had named the AMIs in a way easy to differentiate with wither amzn2 or CentOS in the AMI name. We wanted the Amazon Linux 2 AMI
--filters "Name=name,Values=org-name-ami-amzn2-*" \

We have both ARM as well as x86_64 versions of AMIs, and my team's code has only been tested on X86_64. So choose that:
"Name=architecture,Values=x86_64" \

This could have different values, I think for most people this will be machine
"Name=image-type,Values=machine" \

Choose only the AMIs in the available state:
"Name=state,Values=available" \

This is the way virtualization is implemented. Most people can safely choose hvm:
"Name=virtualization-type,Values=hvm" \

Choose AMIs with root volume being an EBS
"Name=root-device-type,Values=ebs"

A: AWS CLI
A way to filter the output and get the only the required attributes is using a combination of filters,queries on the aws describe-images command as below:
aws ec2 describe-images \
--owners 'amazon' \
--filters 'Name=description,Values=Amazon Linux AMI*' \
--query 'sort_by(Images, &CreationDate)[-1].[ImageId]' \
--output 'text'

Command Explanation:

*

*owners : For images by amazon, use 'amazon'. To query your own images, use 'self'

*filters : You can use a list of filters to filter out the instance that you are looking for. I prefer description because I found the name filter missing for some images. Values support wildcards. More on filters

*query : Query can be used to filter only what is required from the output. You can also sort on fields that would be present in the output. I have sorted on the images and the creation date to get the last created image and filtered the ImageId

*output : Output can be json or text based on the way you plan to consume it.

Using Python
You can do the same using the below python script:
import boto3
from operator import itemgetter

client = boto3.client('ec2')
response = client.describe_images(
    Filters=[
        {
            'Name': 'description',
            'Values': [
                'Amazon Linux AMI*',
            ]
        },
    ],
    Owners=[
        'amazon'
    ]
)
# Sort on Creation date Desc
image_details = sorted(response['Images'],key=itemgetter('CreationDate'),reverse=True)
ami_id = image_details[0]['ImageId']

Update:
You can use fine-grain filters to get a quicker response. The filters mentioned in @Jack's answer work.
filters = [ {
    'Name': 'name',
    'Values': ['amzn-ami-hvm-*']
},{
    'Name': 'description',
    'Values': ['Amazon Linux AMI*']
},{
    'Name': 'architecture',
    'Values': ['x86_64']
},{
    'Name': 'owner-alias',
    'Values': ['amazon']
},{
    'Name': 'owner-id',
    'Values': ['137112412989']
},{
    'Name': 'state',
    'Values': ['available']
},{
    'Name': 'root-device-type',
    'Values': ['ebs']
},{
    'Name': 'virtualization-type',
    'Values': ['hvm']
},{
    'Name': 'hypervisor',
    'Values': ['xen']
},{
    'Name': 'image-type',
    'Values': ['machine']
} ]

# Use above filters
response = client.describe_images(
  Filters=filters,
  Owners=[
      'amazon'
  ]
)

A: I saw a similar script here
https://github.com/bwood/latest-ami/blob/master/latest-ami.py
however for some reason this when run, i get errors


text:
Q: new project :: adv. contactbook , but i am facing some issues i am a beginner at python , i was working with this project from a long time.
in this project the user should be able to create different account . and the account username and password should be kept in .txt file. then when the user wish they can create a contact book and then write some contact details. the user should also open the contact book whenever they want. but i am getting of error . so could somebody help me.
this is the codes --
name=(user2+".txt")

contact_book=open(name,"a")

contact_book.write("\n")
option=input("hello,do you want to save a new contact:(yes/no) ")
space=("                     ")

def openbook():
    option=input("do you want to open the contacts (yes/no)")
    if option == ("yes"):
        openfile=open(name,"r")
        print(space)
        openfile=openfile.read()
        print(openfile)
        contact_book.close()

def book():
    print("ok")
    name=input("what is the name?: ")
    print(space)
    phone=input("what is the phone number?: ")
    print(space)
    address=input("what is the address?: ")

    contact_book.write("\n")
    contact_book.write(name+"    "+phone+"    "+address)
    contact_book.write("\n")
    print("ok,done")
    print(space)
    contact_book.close()

    option1=input("do you want to save a new contact:(yes/no)")
    while option1==("yes"):
         book()

    if option1==("no"):
             openbook()

x=2

while x==2:

    if option==("yes"):
        book()
        delete=input("do you want to delete the contact book!! (yes/no)")
        if delete == ("yes"):
            os.remove(name)

    if option ==("no"):
        openbook()
        delete=input("do you want to delete the contact book!! (yes/no)")
        if delete == ("yes"):
            os.remove(name)
        if delete==("no"):
            print("ok")
            input("")
        if delete == ("yes"):
            os.remove(name)
        x=x-2


text:
Q: Google Maps, set the center coordinates to be off centered in the container The setCenter method focuses on the coordinates at 50:50 height:width of the google maps div. What I want to do is change to center from 50% left to 25% left. Does Google Maps allow this or is there a trick around it?

A: If you take a look at the Google Maps API you'll see several methods for the Map element.
Using a script like this (not tested) :
var ne = map.getBounds().getNorthEast();
var sw = map.getBounds().getSouthWest();

var lat = sw.lat() + 0.5*(ne.lat() - sw.lat());
var long = sw.lng() + 0.25*(ne.lng() - sw.lng());

map.setCenter(new google.maps.LatLng(lat,long));

you should achieve what you would like to do.
working example


text:
Q: Retrieve String from Binary Data i am working with UDP Multicast in Java.My code is as follows:
import java.io.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.lang.*;
import java.nio.charset.Charset;

public class MulticastTest {

    static String MCAST_ADDR = "224.0.1.129";
    static int DEST_PORT = 320;
    static int BUFFER_LENGTH = 4096;

    public static void main(String args[]) {

        try {
            byte[] b = new byte[BUFFER_LENGTH];
            DatagramPacket dgram = new DatagramPacket(b, b.length);
            MulticastSocket socket = new MulticastSocket(DEST_PORT);
            socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
            socket.receive(dgram); // blocks until a datagram is received
            System.err.println("Received " + dgram.getLength() + " bytes from " + dgram.getAddress());
            dgram.setLength(b.length); // must reset length field!

    String received = new String(dgram.getData());
    System.out.println("Bytes received and printed at Console: " + received);

            } catch (Exception e) {
        }
    }
}

I am able to receive the data from another node but only as binary data.
Could someone please tell me how to convert the variable "received" into something meaningful such as Strings/Character so that it is readable to humans.And could you please write the code exactly, i am really new to programming.I would really appreciate any help.

A:  String received = new String(dgram.getData());

This is where you get the received data from the other node, and it is already in String format. The problem you're having is that you're converting from byte to String and since your buffer is 4096 in size, your String variable has blank characters in it. This will appear just after the actual data in your variable.
What you could do to make it more "readable to humans", is to pass it through some string manipulation function to remove the blank characters.
The idea is to go through the String you received, and retrieve all alphanumeric characters present there.
Hope this helps.
You could use this to extract your data
String received = new String(dgram.getData());
String dataReceived = "";
for(int i = 0;i<received.lenght();i++){

char charac = received.charAt(i);//this will allow you to get all data in String
switch(charac){

    case 'a': dataReceived = dataReceived.concat(String.valueOf(charac));
    case 'b': dataReceived = dataReceived.concat(String.valueOf(charac));
    case 'c': dataReceived = dataReceived.concat(String.valueOf(charac));
    case 'd': dataReceived = dataReceived.concat(String.valueOf(charac));
    ...
    case '1': dataReceived = dataReceived.concat(String.valueOf(charac));
    case '2': dataReceived = dataReceived.concat(String.valueOf(charac));
    ...
    case '.': dataReceived = dataReceived.concat(String.valueOf(charac));
    case ',': dataReceived = dataReceived.concat(String.valueOf(charac));
    ..
   }
 }
System.out.println("Data Received: "+dataReceived);

Note that the code is incomplete, if your string will contain only letters no need to check for numbers and symbols.
GoodLuck!


text:
Q: How can you prompt for the EULA in Kickstart? I am trying to modify a Kickstart script so that it does not auto-accept the EULA (which it seems to skip right now.)

A: The parameter is:
eula Accepted

A: The EULA presentation is a function of Firstboot, not Kickstart itself. Firstboot runs if the requirements below are satisfied:

Firstboot is only available on systems after a graphical installation or after a kickstart installation where a desktop and the X window system were installed and graphical login was enabled. If you performed a text-mode installation or a kickstart installation that did not include a desktop and the X window system, the firstboot configuration tool does not appear.

You might not be seeing Firstboot if your installation does not meet these requirements or if it has been explicity disabled with the Kickstart option; firstboot --disable.


text:
Q: Explain the LINQ to XML for a beginner below? Can someone explain the LINQ to XML below?  Also, what is the correct way to check if the method returned a List with Data?  Do you just check if the List is empty.
Code:
public List<Listing> GetList()
{
    if (File.Exists(this.xmlFilePath))
    {
        XDocument doc = XDocument.Load(this.xmlFilePath);

        var listings = from row in doc.Root.Elements("listing")
                       select new Listing
                       {
                           A = (string)row.Element("A"),
                           B = (string)row.Element("B"),
                           C = (string)row.Element("C"),
                           D = (string)row.Element("D"),
                           E = (string)row.Element("E")
                       };

        return listings.ToList();
    }
    else
    {
        return new List<Listing>();
    }
}

XML:
<Listings>
   <listing>
     A
     B
     <c>C</c>
     <d>D</d>
     <e>E</e>
    </listing>
    <listing>
     F
     G
     <c>C</c>
     <d>H</d>
     <e>I</e>
    </listing>
</Listings>

A: You can check if listings has any data by examining the result of the Count() method on the listings variable, and to answer the question asked in the comments section below, "So, there is no way to actually return null? I have to return a List<listing>() object?", please see the following code:
public List<Listing> GetList()
{
  if (File.Exists(this.xmlFilePath))
  {
    XDocument doc = XDocument.Load(this.xmlFilePath);

    var listings = from row in doc.Root.Elements("listing")
             select new Listing
             {
               A = (string)row.Element("A"),
               B = (string)row.Element("B"),
               C = (string)row.Element("C"),
               D = (string)row.Element("D"),
               E = (string)row.Element("E")
             };

    // Check if we have any matches
    if(listings.Count() > 0)
    {
      return listings.ToList();
    }

    return null;
  }
  return null;
}

I think that's what you're after.
There isn't much to explain about how the code works. In the first part of the query:
var listings = from row in doc.Root.Elements("listing")

The expression doc.Root.Elements("listing") selects all of the <listing> elements below the document root (<Listings>).
The second part of the query creates a new Listing object for each <listing> element and assigns the inner text of each of the A,B,C,D and E child elements to each of the A,B,C,D and E properties of each new Listing object created.
The line containing: return listings.ToList(); returns a generic List<T> of Listing objects.
Using the sample XML provided, you'll find that each Listing object's A,B,C,D, and E properties will be null. This is because the character case of each of the row.Element() selectors is different from the XML being queried, i.e. your XML has  and row.Element("A") uses an uppercase 'A'. XML node matching in LINQ to XML is case-sensitive.


text:
Q: Data task with URL timed out I am trying to access a website. I am using a dataTaskWithURL request.
Here is my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in

    print("2")

    if let urlContent = data {

        print("3")

        let stringContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)!

        let arr = stringContent.componentsSeparatedByString("The computer's solutions will appear below
")

        let second = arr[1]

        let newArr = second.componentsSeparatedByString("

")

        let results = newArr[0]

        self.resultsLabel.text = results

        self.stopActivity()
    } else {
        print(error)
        self.stopActivity()
    }
})

task.resume()

I have also tried running this code on the main block:
dispatch_async(dispatch_get_main_queue(), {() -> Void in
    // Code
})

However, neither of these has been successful. I repeatedly get the following error

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7ff0a3f4c6e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=THE URL I AM TRYING TO ACCESS, NSErrorFailingURLKey=THE URL I AM TRYING TO ACCESS, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})

I have tried looking at this post and this one as well. However, I have not been successful with them. The website loads fairly quickly. How do I get rid of this error?

A: It could be caused by a number of things; If the issue is happening in the Simulator, I suggest restarting it as per the suggestions in the SO posts below:

*

*Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

*Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."

*NSURLErrorDomain Code=-1001 error when a http post request is sent

*Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

*How to use NSURLSessionDataTask in Swift
It might be help to print response as well to see if the HTTP headers can provide a clue.

A: I realized that I was using https:// instead of http://.