text:
Q: matplotlib forcing pan/zoom to constrain to x-axes Matplotlib has a feature where if you hold down the "x" or "y" keys it constrains panning or zooming to the corresponding axis.
Is there a way to cause this to be the default? For some reason my CPU does not allow touchpad movement when a letter key is held down. And I only want the x-axis to be pan/zoomed, not the y-axis.

edit: found the pan/zoom function at https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes.py#L3001
which contains an internal function format_deltas. But I have no idea how to override the Axes class with a subclass when Axes objects are created automatically from Figure objects.

A: simonb's approach worked but I had to tweak it for the press_zoom behavior, so that it keeps the press_zoom method a feature of the class, not the instance, but I added a hook to fixup the per-instance behavior.
import types

def constrainXPanZoomBehavior(fig):
    # make sure all figures' toolbars of this class call a postPressZoomHandler()
    def overrideZoomMode(oldZoom, target):
        def newZoom(self, event):
            oldZoom(self, event)
            if hasattr(self, 'postPressZoomHandler'):
                self.postPressZoomHandler()
        return newZoom
    def overrideToolbarZoom(fig, methodname, functransform, *args):
        toolbar = fig.canvas.toolbar
        oldMethod = getattr(toolbar.__class__, methodname)
        newMethod = functransform(oldMethod, toolbar, *args)
        setattr(toolbar.__class__, methodname, newMethod)
    overrideToolbarZoom(fig, 'press_zoom', overrideZoomMode)

    # for this specific instance, override the zoom mode to 'x' always
    def postPressZoomHandler(self):
        self._zoom_mode = 'x'
    fig.canvas.toolbar.postPressZoomHandler = types.MethodType(postPressZoomHandler, fig.canvas.toolbar)
    return fig

A: It is possible to use your own axes class. In your case you can inherit from matplotlib.axes.Axes and change the drag_pan method to always act as though the 'x' key is being pressed. However the zooming doesn't seem to be defined in that class. The following will only allow x axis panning:
import matplotlib
import matplotlib.pyplot as plt

class My_Axes(matplotlib.axes.Axes):
    name = "My_Axes"
    def drag_pan(self, button, key, x, y):
        matplotlib.axes.Axes.drag_pan(self, button, 'x', x, y) # pretend key=='x'

matplotlib.projections.register_projection(My_Axes)

figure = plt.figure()
ax = figure.add_subplot(111, projection="My_Axes")
ax.plot([0, 1, 2], [0, 1, 0])
plt.show()

For the zooming, you may have to look at the toolbar control itself. The NavigationToolbar2 class has the drag_zoom method which seems to be what's relevant here, but tracking down how that works is quickly complicated by the fact that the different backends all have their own versions (e.g. NavigationToolbar2TkAgg
edit
You can monkeypatch the desired behaviour in:
import types
def press_zoom(self, event):
    event.key='x'
    matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg.press_zoom(self,event)
figure.canvas.toolbar.press_zoom=types.MethodType(press_zoom, figure.canvas.toolbar)

You could do it properly and make a subclass of the toolbar, but you have to then create instances of Figure, FigureCanvas and your NavigationToolbar and put them in a Tk app or something. I don't think there's a really straightforward way to just use your own toolbar with the simple plotting interface.


text:
Q: Install El Capitan in Virtual Box for testing purposes I enrolled to Apple's beta program as I want to test some software under El Capitan. Therefore, I would like to instal El Capitan in Virtual Box.
Is there a recommended way of doing this? As I understand I have to install Yosemite first and then upgrade to El Capitan beta?
I understand, that I have to convert the .app I download into a bootable image which I can use to install it in a virtual machine - can somebody point me to a reliable (tested) howto how I can do this?

A: The instructions below, found in Creating a bootable El Capitan ISO image, worked for me after a download of OS X El Capitan from the App Store.
hdiutil attach "/Applications/Install OS X El Capitan.app/Contents/SharedSupport/InstallESD.dmg" -noverify -nobrowse -mountpoint /Volumes/esd
hdiutil create -o ElCapitan3.cdr -size 7316m -layout SPUD -fs HFS+J
hdiutil attach ElCapitan3.cdr.dmg -noverify -nobrowse -mountpoint /Volumes/iso
asr restore -source /Volumes/esd/BaseSystem.dmg -target /Volumes/iso -noprompt -noverify -erase
rm /Volumes/OS\ X\ Base\ System/System/Installation/Packages
cp -rp /Volumes/esd/Packages /Volumes/OS\ X\ Base\ System/System/Installation
cp -rp /Volumes/esd/BaseSystem.chunklist /Volumes/OS\ X\ Base\ System/
cp -rp /Volumes/esd/BaseSystem.dmg /Volumes/OS\ X\ Base\ System/
hdiutil detach /Volumes/esd
hdiutil detach /Volumes/OS\ X\ Base\ System
hdiutil convert ElCapitan3.cdr.dmg -format UDTO -o ElCapitan3.iso
mv ElCapitan3.iso.cdr ElCapitan3.iso

Additionally for running within VirtualBox:

*

*Create a new OS X El Capitan from Wizard.

*Change "System->chipset" to PIIX3, mount created ISO and boot up.

*If you only see a the CD/DVD as installation target within the installation program choose "Utilities > Disk Utility" and erase the VirtualBox disk, which will lead to an empty HFS+ Journaled disk, which now could be chosen as target.

A: VirtualBox appears to have support for El Capitan. This screen shot is of the dialog for creating a new virtual machine.

If you can't find instructions for going from the El Capitan .app to a VirtualBox VM, you may want to follow directions for doing so with Yosemite and hope they work. This guide worked for me.
Update Another idea: Use the above-linked guide to get Yosemite working in VirtualBox, and then upgrade to the beta from within the VM. I just tried this, and it worked for me.

Note that VirtualBox doesn't seem to have any integration software for OS X, so you can't do things like drag to change the guest OS resolution, or enable clipboard sharing, unless I'm really missing something!

A: I was able to follow this tutorial and get El Capitan up and running with only a few snags:

*

*On Step 5 I think there is something wrong with the syntax to remove the broken link, I ended up just opening it in finder and trashed it.

*There's a bit of a typo on Step 7, some of the html got stuck in the expression

Besides that it all seems to be working so far :)

A: There is a new option now which is the easiest: Parallels Light, which is free when running Mac or Linux OS, available from the App Store. Perfect for this type of job.

A: The high level, brief answer is that you should run the beta software on bare metal for best results. I'm not aware of any virtualization package that supports El Capitan yet (hours after it was announced).
Surely the vendors will update their tools in time, but in general, I don't think VirtualBox has the best support of any OS X as a guest operating system when running on Mac hardware due to it being focused on multiple host OS compatibility as opposed to a Mac centric design.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIViewControllerRepresentable ignoresSafeArea not working import SwiftUI
import UIKit

extension Color {
    static var random: Color {
        return Color (
            red: .random(in: 0...1),
            green: .random(in: 0...1),
            blue: .random(in: 0...1)
        )
    }
}

struct ContentView: View {
    let pages = (0..<3).map { _ in Color.random }
    var body: some View {
        PageView(pages: pages)
            .ignoresSafeArea()
    }
}

struct PageView<Page: View>: View {
    var pages: [Page]
    @State private var currentPage = 0

    var body: some View {
        PageViewController(pages: pages, currentPage: $currentPage)
    }
}

struct PageViewController<Page: View>: UIViewControllerRepresentable {
    var pages: [Page]
    @Binding var currentPage: Int

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageViewController = UIPageViewController(
            transitionStyle: .scroll,
            navigationOrientation: .horizontal)
        pageViewController.dataSource = context.coordinator
        pageViewController.delegate = context.coordinator
        return pageViewController
    }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        pageViewController.setViewControllers(
            [context.coordinator.controllers[currentPage]], direction: .forward, animated: true)
    }

    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        var parent: PageViewController
        var controllers = [UIViewController]()

        init(_ pageViewController: PageViewController) {
            parent = pageViewController
            controllers = parent.pages.map { UIHostingController(rootView: $0) }
        }

        func pageViewController(
            _ pageViewController: UIPageViewController,
            viewControllerBefore viewController: UIViewController) -> UIViewController? {
                guard let index = controllers.firstIndex(of: viewController) else {
                    return nil
                }
                if index == 0 {
                    return controllers.last
                }
                return controllers[index - 1]
            }

        func pageViewController(
            _ pageViewController: UIPageViewController,
            viewControllerAfter viewController: UIViewController) -> UIViewController? {
                guard let index = controllers.firstIndex(of: viewController) else {
                    return nil
                }
                if index + 1 == controllers.count {
                    return controllers.first
                }
                return controllers[index + 1]
            }

        func pageViewController(
            _ pageViewController: UIPageViewController,
            didFinishAnimating finished: Bool,
            previousViewControllers: [UIViewController],
            transitionCompleted completed: Bool) {
                if completed,
                   let visibleViewController = pageViewController.viewControllers?.first,
                   let index = controllers.firstIndex(of: visibleViewController) {
                    parent.currentPage = index
                }
            }
    }
}

A: It should be not only for container, but for internal view as well (to fill that external container), because by default every view respects safe area.
So the fix is
init(_ pageViewController: PageViewController) {
    parent = pageViewController
    controllers = parent.pages.map {
        UIHostingController(rootView: $0.ignoresSafeArea())  // << here !!
    }
}

Tested with Xcode 13.3 / iOS 15.4


text:
Q: Control value persistance across postbacks Given the following code, can anyone explain how on earth the dropdownlist is remembering its selected value across postbacks, given that viewstate is disabled and the control is being constructed after the viewstate has finished tracking values.
DropDownList ddl;
protected void Page_Load(object sender, EventArgs e)
{
    ddl = new DropDownList() {AutoPostBack = true, EnableViewState = false, ViewStateMode = ViewStateMode.Disabled };
    ddl.Items.Add(new ListItem("1"));
    ddl.Items.Add(new ListItem("2"));
    div.Controls.Add(ddl);
}

A: A control uses ControlState, which is separate from the ViewState.  But similar in implementation.
ControlState vs. ViewState

A: Viewstate is not used to retain the value posted to the server.  It may be used to retain the value that was selected the last time it was served to the client in viewstate but this is only so it can generate server side events such as selectedindexchanged.  Its current value however is determined by what was posted by the control to the server.  DropDownList implements IPostBackDataHandler which "Defines methods that ASP.NET server controls must implement to automatically load postback data."
Again, the current value of the DropDownList is not retrieved from ViewState, it is retrieved from the posted form values.  If you do not need it to maintain its value, set its selected index to 0 (or whatever the default index is) after you have added it to the control tree.  It is important you do it after you have added otherwise the posted value will be loaded when you add it to the control tree.


text:
Q: Removing logging with ProGuard doesn't remove the strings being logged
Possible Duplicate:
Removing unused strings during ProGuard optimisation

I have an Android application with dozens of logging statements. I'd prefer they wouldn't appear in the release version, so I used Proguard with something like this in the proguard.cfg file:
-assumenosideeffects class android.util.Log {
    public static *** d(...);
}

But the problem is that there are a lot of Log.d("something is " + something), and although the Log.d() statement is being removed from the bytecode, the strings are still there.
So, following this answer, I created a simple wrapper class, something along the lines of:
public class MyLogger {
    public static void d(Object... msgs) {
        StringBuilder log = new StringBuilder();
        for(Object msg : msgs) {
            log.append(msg.toString());
        }
        Log.d(TAG, log.toString());
    }
}

Then I edited my proguard.cfg:
-assumenosideeffects class my.package.MyLogger {
    public static *** d(...);
}

But the strings are still found in the generated bytecode!
Other than this, I am using the standard proguard.cfg provided by the Android SDK. Am I doing something wrong?

Edit: after examining the generated bytecode, I saw that the strings were there, but they were not being appended one to another, as I thought. They were being stored in an array. Why? To pass them as variable parameters to my method. It looks like ProGuard doesn't like that, so I modified my logger class like this:
public static void d(Object a) {
    log(a);
}

public static void d(Object a, Object b) {
    log(a, b);
}

(... I had to put like seven d() methods ...)

private static void log(Object... msgs) {
    (same as before)
}

It's ugly, but now the strings are nowhere in the bytecode.
Is this some kind of bug/limitation of ProGuard? Or is it just me not understanding how it works?

A: Proguard doesn't work me, too, and I don't like to create a wrapper around Log, so I've tested the following solutions:
WORKING Solution
final static boolean IsDebugging = false;

and in your code:
if(IsDebugging)
   Log.i(TAG, "Debugging");

consider that you must use final keyword so that IsDebugging become true or false at compile time and log strings doesn't appear in final bytecode.
NOT WORKING (IsDebugMode)
    public static boolean IsDebugMode(Context context) {
    PackageManager pm = context.getPackageManager();
    PackageInfo pi;
    try {
        pi = pm.getPackageInfo(context.getPackageName(),0);
    } catch (NameNotFoundException e) {
        return false;
    }
    return (pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
}

and in my code:
    boolean IsDebugging = Utils.IsDebugMode(this);

    if(IsDebugging)
      Log.i(TAG, "Debugging");

The above solution doesn't print any Log in Logcat but the log string are compiled and exist in final bytecode which is bad.
The other solution was :
NOT WORKING (BuildConfid.DEBUG)
    if(BuildConfig.DEBUG)
      Log.i(TAG, "Debugging");

This is same as IsDebugMode solution. It doesn't print anything but strings are in final bytecode. Bad again!

A: Your solution with different methods for different numbers of arguments is probably the most convenient one. A single method with a variable number of arguments would be nicer, but the current version of ProGuard is not smart enough to remove all the unused code.
The java compiler compiles a variable number of arguments as a single array argument. On the invocation side, this means creating an array of the right size, filling out the elements, and passing it to the method. ProGuard sees that the array is being created and then being used to store elements in it. It doesn't realize (yet) that it then isn't used for actual useful operations, with the method invocation being gone. As a result, the array creation and initialization are preserved.
It's a good practice to check the processed code if you're expecting some particular optimization.


text:
Q: Highchart how to create lollipop type chart with circle and line top/bottom at different positions I'm looking for chart to show series with high low and average. High/Low reflected by the y coordinate of the high/low values, and a circle at the y coordinate of the average.
Any suggestions on how to achieve this using highcharts (in reactjs)?
Thanks,
Reuven

A: I think that the easiest way to achieve that is to add each of the category group as a separate series and add dynamically the average point for the group.
Demo: https://jsfiddle.net/BlackLabel/ytfquvhg/
  chart: {
    events: {
      load() {
        let chart = this;

        chart.series.forEach(s => {
          let avrPoint = s.yData.reduce((a, b) => a + b, 0) / s.yData.length
          s.addPoint({
            y: avrPoint,
            x: s.points[0].x,
            marker: {
              enabled: true
            },
            name: 'average'
          })
        })
      }
    }
  },

API: https://api.highcharts.com/highcharts/chart.events.load


text:
Q: How to call a function every x seconds with updated state (React) Im having a lot of trouble with this and i have tried various things. I want to call a function every second after i have clicked a start button and then have it paused after i click a stop button. I keep getting weird behaviour that i cant explain.
How can i do this in react without classes?
somethings i have treid:
      const simulation = () => {
    if (!running) {
      console.log('hit');
      return

    } else {
      // console.log(grid);
      console.log('hey');
      setTimeout(simulation, 1000)
    }
  }

and
    enter  setInterval(() => {
    let newGrid = [...grid]
    for (let i = 0; i < numRow; i++) {
      for (let k = 0; k < numCol; k++) {
        let n = 0;
      }
    }
    console.log(grid);
  }, 5000)

I have tried a lot more, In some cases it would update the state should i have added to it but not updated it after i reset the state.
How can i call a function to run every one second with updated values of state * Note the function that i want to run will update the state

A: You may do the following:

*

*keep track of the current counter value along with the counter on/off state in your component state;

*employ useEffect() hook to be called upon turning counter on/off or incrementing that;

*within useEffect() body you may call the function, incrementing count by one (if ticking is truthy, hence timer is on) with delayed execution (using setTimeout());

*once count variable is changed in the state, useEffect() gets called once again in a loop;

*in order to clean up the timer upon component dismantle, you should return a callback, clearing the timer from useEffect()

const { useState, useEffect } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')

const App = () => {
  const [ticking, setTicking] = useState(true),
        [count, setCount] = useState(0)

   useEffect(() => {
    const timer = setTimeout(() => ticking && setCount(count+1), 1e3)
    return () => clearTimeout(timer)
   }, [count, ticking])

   return (

{count}

      <button onClick={() => setTicking(false)}>pause</button>
      <button onClick={() => setTicking(true)}>resume</button>

   )
}

render (
  <App />,
  rootNode
)

A: Late reply but maybe interesting for some people.
Look at npm package cron. In this case every 15min As easy as:
const [job] = useState(new cron.CronJob("0 */15 * * * *",async ()=>{
    await updateRiderCoords();
}));
useEffect(() => {
    job.start();
}, []);


text:
Q: ArrayList in java ArrayList<String> veri1 = new ArrayList<String>();

String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

How can I add veri2 to veri1 like one element? I mean, if I call veri.get(0), it returns veri2.

A: You should use the List interface and generics (for Java >= 1.5). Depending on what you want to do you can use this:
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

List<String> veri1 = new ArrayList<String>();
veri1.addAll(Arrays.asList(veri2)); // Java 6

List<String[]> veri3 = new ArrayList<String[]>();
veri3.add(veri2);

A: I just saw (due to fm), that you have an ArrayList<String>.  You can do:
ArrayList veri1 = new ArrayList();
veri1.add(veri2)

or
ArrayList<String[]> veri1 = new ArrayList<String[]>();
veri1.add(veri2)

You can also make ver1 a List, which gives you flexibility in changing implementations.

A: You can't actually do this.
veri2 is an array of strings, veri1 is an arraylist of individual strings
Thus, doing veri1.get(0) should return a single string, not an array of strings.

A: You should declare your list as a list of string arrays, not a list of strings:
List<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

veri1.add(veri2);

Note that in general it is better to declare your list as List instead of ArrayList, as this leaves you the freedom to switch to a different list implementation later.

A: It all depends on whether or not you want your ArrayList to be of one type or if you need it to hold multiple types.
If you just need it to hold String arrays throughout your code, declare as stated above:
ArrayList<String[]> list1 = new ArrayList<String[]>();

then just add the String array to it as follows:
list1.add(stringArray);

If you want it to be dynamic, declare it with the object type:
ArrayList<Object> anythingGoes = new ArrayList<Object>();

and then you can add anything later on as well:
anythingGoes.add(stringArray);
anythingGoes.add(myAge);
anythingGoes.add(myName);

A: I think you mean this:
import java.util.Arrays;

ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};

veri1.addAll(Arrays.asList(veri2);

A: You pretty much just need to add the array to the ArrayList.
ArrayList<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"a", "b", "c"};
veri1.add(veri2);

System.out.println(veri1.size());
for(String[] sArray : veri1)
    for(String s : sArray)
        System.out.println(s);


text:
Q: How to get Windows for to raise mouseclick event for programatically created PictureBox? I'm building a virtual board game, and I need to be able to click on the pieces to move them. The board is created as a picture in the background, and the pieces are pictureboxes over top of that. More specifically, they are a custom class GamePiece that inherits from PictureBox. I know PictureBox has a Name_Click method that is called when it's clicked, but I'm creating my pieces programatically, as follows:
    public Player(int identity, GameBoard Board)
    {
        ID = identity;
        for (int i = 0; i < 4; i++)
        {
            Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
        }
    }

Therefore, I don't want to hardcode in methods to be called for each Gamepiece, because that would defeat my purpose here.
Any suggestions? I can include any other code that would be helpful, and I'm pretty flexible as far as redesigning code, if that would make my life easier later. Thanks in advance.

A: Just add Control.Click event handler for your control:
public Player(int identity, GameBoard Board)
{
    ID = identity;
    for (int i = 0; i < 4; i++)
    {
        Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
        Pieces[i].Tag = ID;
        Pieces[i].Click += pieces_Click;
    }

on the Click event:
private void pieces_Click(object sender, EventArgs e)
{
    int id = (int) ((Pieces))sender.Tag;
    DoSomethingForId(id);
}

or using Anonymous Methods:
public Player(int identity, GameBoard Board)
{
    ID = identity;
    for (int i = 0; i < 4; i++)
    {
        Pieces[i] = new ....
        Pieces[i].Click += (sender, e) =>
                        {
                            // Do some thing
                        };
    }
}

A: (Wire up to an event handler)
Pieces[i].Click += new EventHandler(theOnClickEvent);

(The event handler)
void theOnClickEvent(object sender, EventArgs e)
    {
        //clicked.
    }

A: Could it be:
gamePiece.Click += myEventHandler;

Where gamePiece is the GamePiece object, and myEventHandler is any form of event handler... delegate, lambda, whatever.


text:
Q: UIAlertView from Tab Button - No Internet Connection Looking for some help again...
I've currently got 2 sections of my app that need internet connection, 1 is a photo gallery through Flickr and the other a Twitter Feed, I was wondering if this is the correct code for the UIAlertView... I can get it working from a button but thats all!
{
-(void)didTap_roundedRectButton1:(id)sender forEvent:(UIEvent *)event {
UIAlertView *alertView = [[UIAlertView alloc] init];
alertView.title = @"You are not connected to the Internet!";
alertView.message = @"Please check your connection and try again...";
[alertView addButtonWithTitle:@"Ok"];
[alertView show];
[alertView release];
}

A: You should try this:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"You are not connected to the Internet!"
                                                  message:@"Please check your connection and try again..."
                                                 delegate:nil
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles: nil];

  [alertView show];
  [alertView release];

and can you post the code how do you create the UIButton?

A: i think you need to use this example as i have used it to check is there any network is available and device is connected to any one of the network it is alos available on the apple's developer example site
example link is this


text:
Q: How can I get a shapefile of coverage from the Planet Labs scenes API? I'm using the Planet Labs Scenes API and need to get the results of a (large) search I'm making as a shapefile. Any hints on how to go about it? I'm comfortable with command line tools like the command line interface of the Planet Python Client and OGR, but not quite up for custom python coding.

A: There are a few different ways of doing this, but if we stick to command line tools, you can get all the footprints as a Shapefile with a simple OGR command.
The Planet Scenes API returns the results of a search as valid GeoJSON, which is a format that OGR understands. Therefore, if you run the search in your browser (https://api.planet.com/v0/scenes/ortho/ ...) and save the results as results.json, you can generate the Shapefile like this:
ogr2ogr results.shp results.json

The new search.shp will contain the footprints of all the scenes as well as the associated metadata.
If you are using the Planet CLI tool, then you can do this is in two steps:
planet search --where ... POLYGON((...)) > results.json
ogr2ogr results.shp results.json

You can also do it in one single command:
planet search --where ... POLYGON((...)) | ogr2ogr results.shp /vsistdin/

All of these OGR commands will probably warn you that some strip_id numbers were not successfully recorded in the Shapefile. This is because OGR interprets these as floating point numbers, which will have a different representation from the source GeoJSON. This is only important if you need the strip_id to be accurate in the Shapefile; otherwise, you can ignore this warning.
Disclaimer: I work for Planet Labs.


text:
Q: Not able to insert merge values in one row using ssis? I have two excel source on one excel file 1st fetching value date and 2nd fetching value price
now i have tried merge then union all also to get those two values in one derived column
but when i execute my package it is inserting values separately.
like this into two rows one by one but i want to insert these two values in one row only.
for example this is my problem:
date            price
 12-12-2001      null
date         price
 null         54
but i want it in one row only like
date         price
 12-12-2001   54

A: Create two derived columns with the same value (i.e. call them id1 and id2 and set both to have a value of 1).
Change the sort to sort by the new id columns.
Change the merge component to a merge join and use the newly created ids to link the data based on an inner join

which will give you a single row


text:
Q: Get windowId from inspected Window In a custom DevTools panel, I can use:
const tabId = chrome.devtools.inspectedWindow.tabId;

but looking at the docs, I can't figure out how to get the window id from chrome.devtools...
https://developer.chrome.com/extensions/devtools_inspectedWindow
is there a way to get the windowId, as well as the tabId?


text:
Q: How to use Mongo --authenticationDatabase in perl This is how I connect to mongoDB in perl
my $client = MongoDB::MongoClient->new(
    host     => 'badhost',
    port     => 37018,
    username => 'abc_user',
    password => 'abc_user',
    db_name  => 'cust_projectdb'
) or die "unable to connect to mongo\n";

when the connection string from shell is
mongo  cust_projectdb --port 37018 -uabc_user -pabc_user --host badhost
but how to connect when the connection string uses a different collection for authentication like this:
mongo  cust_projectdb --port 37018 -uabc_user -pabc_user --host badhost --authenticationDatabase admin

A: The db_name parameter sets the authentication database when you are connecting to the server, so you would want
db_name => 'admin'

to do the equivalent of your command line connection, although admin is the default here anyway so you can just omit it altogether
If you want to access the cust_projectdb database then you need to use get_database on the MongoDB::MongoClient object you just created to do that
my $db = $client->get_database('cust_projectdb')


text:
Q: Homebrew gcc can't find omp.h on OS X I've spent hours trying different solutions but nothing has worked so far.
I've installed gcc via Homebrew, and linked gcc to the Homebrew gcc. gcc -v returns this:
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/5.3.0/libexec/gcc/x86_64-apple-darwin14.5.0/5.3.0/lto-wrapper
Target: x86_64-apple-darwin14.5.0
Configured with: ../configure --build=x86_64-apple-darwin14.5.0 --prefix=/usr/local/Cellar/gcc/5.3.0 --libdir=/usr/local/Cellar/gcc/5.3.0/lib/gcc/5 --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-5 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --enable-libstdcxx-time=yes --enable-stage1-checking --enable-checking=release --enable-lto --with-build-config=bootstrap-debug --disable-werror --with-pkgversion='Homebrew gcc 5.3.0 --without-multilib' --with-bugurl=https://github.com/Homebrew/homebrew/issues --enable-plugin --disable-nls --disable-multilib
Thread model: posix
gcc version 5.3.0 (Homebrew gcc 5.3.0 --without-multilib)

However, when I try to compile I get
This is make_MWA_Tools.sh
using $CFITSIO =
building LFILE & read_mwac utilities
cc -g -O -Wall -D_FILE_OFFSET_BITS=64 -fopenmp  -c mwac_utils.c
mwac_utils.c:3:10: fatal error: 'omp.h' file not found
#include <omp.h>
         ^
1 error generated.
make: *** [mwac_utils.o] Error 1
!!!!!!!!!!!!!!!!!!!!!!
build_lfiles/read_mwac make failed !

I've looked in gcc located under Cellar and found mop.h, but for some reason its not being included. Any help would be greatly appreciated.
Edit: I don't believe this is a duplicate question because I could not find another question that Installed gcc from Homebrew, linked 'gcc' to the homebrew gcc installation, and still couldn't find omp.h


text:
Q: Airflow - task fail without log I have a pipeline that start with by getting a file in a GCS bucket and do several tasks on it.
Sometime, after big update I have to rerun every file one by one. That's what I did and everything goes well for 190 files (for around 290 in total) but suddenly on task fail, without log. This task should have launch a K8s pod but here nothing. No logs in airflow, no pod launched in K8s. If I try to clear the task but still fail the same way.
The task fail as soon as lunched. I restarted the instance, I have space on the disk... I have no idea what to do.


text:
Q: ARIMA model identification Having a bit of difficulty identifying the appropriate ARIMA model by looking at ACF/PACFs.
I know that AR(1) models, the ACF has a geometric progression from its highest value at lag 1 and the PACF has a spike at lag 1 and then then cuts off afterwards.
Could someone possibly explain how I identify the rest? AR and MA please?!?

A: 1) A pure AR(p) will have a cut off at lag p in the PACF:

ACF and PACF of a long AR(3) process
$ $
2) A pure MA(q) will have a cut off at lag q in the ACF.

ACF and PACF of a long MA(3) process
$ $
3) ARMA(p,q) will (eventually) have a decay in both; you often can't immediately tell p and q from empirical ACF and PACF -- though with some practice you can get better at it.
As Graeme Walsh points out, model identification is part of an iterative process (explicitly so in Box and Jenkins).

The ACF plot above suggests perhaps an MA(4) while the PACF plot might suggest an AR(5). One might instead try say an ARMA(1,1) and see what was "left over". There are other tools than the ACF and PACF, but they're usually even harder to interpret in practice (and may require even larger sample sizes to give a reliable indication).

A: About the ACF and PACF of ARMA(p,q) one can say: ACF tails off after lag (q-p) and PACF tails off after lag (p-q) [e.g. Wei (2005), S. 109], which makes it difficult to identify the orders p and q. Usually one uses the information criteria like the AIC, BIC, FPE, .... One estimates severeal models with different orders p and q and selects the one with the smallest value of the respective criterion.


text:
Q: AES use same IV for encryption and decryption I'm having some issues with my code whereby I am not using the same IV for encryption and decryption. I know in order to do this correctly I have to write the IV to my output file before the data however I am struggling implementing this. Could anyone help me with this issue?
Edited code code again to show full scope
public class TestFileEncryption {
    private static void mainCrypto(int cipherMode, File inputFile, File outputFile) throws Exception{
        //Let the user enter the key they wish to use
        Key secretKey = new SecretKeySpec(UITest.getStoreKey().getBytes(), UITest.getSendAlg()); //Generates a key based on the default keysize for the specified algorithm

        //Generate an Initialization Vector (IV)
        final int ALG_KEYLENGTH = UITest.getStoreKey().length(); //Change this as desired for the security level you want
        byte[] iv = new byte[ALG_KEYLENGTH]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
        SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
        prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

        //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
        Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

        //Initialize the Cipher for Encryption
        cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

        //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length() - ALG_KEYLENGTH];
        inputStream.read(iv);
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        inputStream.close();
        outputStream.close();
    }

    public static void encrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void decrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void main(String[] args) {}
}

A: You just have to write the IV before the ciphertext:
outputStream.write(iv);
outputStream.write(outputBytes);

Then, when decrypting, read the IV and the ciphertext:
byte[] iv = new byte[ALG_BLOCKSIZE];
byte[] inputBytes = new byte[(int) inputFile.length() - ALG_BLOCKSIZE];
inputStream.read(iv);
inputStream.read(inputBytes);

Here ALG_BLOCKSIZE needs to be 16 for AES-CBC.

A: Just extending answer of @Javier.
it looks like you'd like to use the same method for encryption and decrpytion (depending on the mode) however there's a difference in handling the IV.
You generated a random IV, then you overwrote it with the input of the (plain) input and at the end you wrote it to the output (regardless it's decryption).
So you have to distinguish if the mode is

*

*encryption - the IV is generated and written to the output before ciphertext

*decryption - the IV is read from the input and used for decryption, but not written to the output

something like that:
private void encrypt(File inputFile, File outputFile)  {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()];
    byte[] iv = new byte[16]; // 16 for AES-CBC
    SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
    prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }
}

private void decrypt(File inputFile, File outputFile) {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()-16];
    byte[] iv = new byte[16]; // 16 for AES-CBC

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
    inputStream.read(iv);
    inputStream.read(inputBytes);
    byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(outputBytes);
    outputStream.flush();
    inputStream.close();
    outputStream.close();
}

To leave out some detail, maybe you could directly use Java CipherOutputStream and CiptherInputStream and the implementation will handle these details for you (if you don't care about exact format).
Next what are you missing is an authentication tag, at least hash of the plaintext assuring integrity of the ciphertext. (it's called authenticated encryption)


text:
Q: Profile Activity Tracker Bug logged on today and my activity tracker suddenly changed to this:

but....

still about 40 away from even getting awarded the grammar badge.
Don't know what the tracker is thinking.


text:
Q: Can I use Velocity templates with InputStreams? I'm dealing with large files and I need to wrap XML around a base64 payload. My first naive implementation passed the payload as a java.lang.String into the [Velocity template][0], but with large files I want to use java.io.InputStream instead.
Here's my template:
<?xml version="1.0" encoding="UTF-8"?>
<Request>
    <AdditonalParameters>
#if( $headers.additionalParameters )
#foreach( $key in $headers.additionalParameters.keySet() )
        <Parameter>
            <Key>${key}</Key>
            <Value>${headers.additionalParameters.get($key)}</Value>
        </Parameter>
#end
#end
    </AdditonalParameters>
    <Content>${body}</Content>
</Request>

$body can potentially be very large, so I want to avoid using String or byte[]. Is it possible to pass an InputStream as $body into my template or can't I use Velocity for this?

A: Yes, this can be done. All it takes is an iteration that prints your InputString line by line. Since Velocity lacks a while-like construct and only knows about foreach loops, the iteration will look like an ugly hack in its most simple implementation:
#foreach ($i in [0..100000])
    #set ($line = false)
    #set ($line = $body.readLine())
    #if ($line)
        ${line}
    #else
        #break
    #end
#end

Here a very big numeric range is used to simulate an endless loop. The loop will #break when no more lines can be extracted from the InputStream (the $body). A caveat is in the third line:
#set (line = $body.readLine())

As always in Velocity, the left hand side of the assignment only changes when the value on the right side is not null. Since $line will never be assigned a null value, we'll need to pre-set it to false (a boolean value, not a string as returned by readLine). This way, if $line is still false after the second #set, we know that readLine returned null and it's time to exit the iteration.
A problem with this approach are white spaces in the template inserted between lines. There are a few tricks to avoid this (see here). Also, the #foreachhack can be avoided by creating a Java List whose iterator() method returns an Iterator that iterates over the lines of the InputStream. This would be less KISS but it would make your code more reusable.


text:
Q: Bash: Extracting parts of a line and rewriting them? I have a line (which is part of a list of more of the same) that looks something like:
au123456.us.something.net/789/net/Wonderful

... and so on.
I'd like to extract the 6 digits in the auXXXXXX part, and then also grab everything after the /, so I'm able to re-write the line to become:
cdn123456.au.somewhereelse.com/789/net/Wonderful

Is this possible? I'm at a loss with the substitution requirement and the regex... :facepalm:
I was using:
echo "au123456.us.something.net/789/net/Wonderful" | sed 's/au/cdn/g;s/us.something.net/au.somewhereelse.com/g'

But it's not robust enough for instances like: au123456.us.something.net/789/net/CaultonHex for example. The output becomes:
cdn123456.au.somewhereelse.com/789/net/CcdnltonHex

A: If you don't want to match globally, don't use g flag. g flag makes it replace all occurrences, without the g flag only the first occurrence is replaced.
$ printf "%s\n" au123456.us.something.net/789/net/Wonderful au123456.us.something.net/789/net/CaultonHex  | sed 's/au/cdn/; s/us.something.net/au.somewhereelse.com/'
cdn123456.au.somewhereelse.com/789/net/Wonderful
cdn123456.au.somewhereelse.com/789/net/CaultonHex

Note that in regex us.something.net the dot . represents any character.
$ echo au123456.us%something,net/789/net/Wonderful | sed 's/au/cdn/; s/us.something.net/au.somewhereelse.com/'
cdn123456.au.somewhereelse.com/789/net/Wonderful

Escape the dot with \. to match only a dot:
sed 's/au/cdn/; s/us\.something\.net/au.somewhereelse.com/'

I would personally prefer to match the pattern explicitly, along:
$ printf "%s\n" au123456.us.something.net/789/net/Wonderful au123456.us.something.net/789/net/CaultonHex  | sed 's@au\([0-9]\{6\}\)\.us\.something\.net/@cdn\1.au.somewhereelse.com@'
cdn123456.au.somewhereelse.com789/net/Wonderful
cdn123456.au.somewhereelse.com789/net/CaultonHex


text:
Q: When using the guice servlet extension is it possible to react to servlet destruction? I need to do some cleanup when guice servlet is removed. Is it possible to hook into the servlet destruction when using a guice servlet? I need to use the Injector to do the cleanup work.
I can override the contextDestroyed method in GuiceServletContextListener, but then how do I get access to the injector?
Is there a better way to react to servlet destruction?

A:
I can override the contextDestroyed method in GuiceServletContextListener, but then how do I get access to the injector?

You could do it like this:
public class MyGuiceServletConfig extends GuiceServletContextListener {
    private final Injector injector = Guice.createInjector(new ServletModule());

    @Override
    protected Injector getInjector() {
        return injector;
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        injector.getInstance(MyCleanUp.class);
    }
}

Or like this:
public class MyGuiceServletConfig extends GuiceServletContextListener {

    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Injector injector = (Injector) sce.getServletContext()
                                          .getAttribute(Injector.class.getName());
    }
}


text:
Q: Laravel - 2xHasMany Relations one other Table I have table Messages
with columns from and to
That corresponds to some users in table Users.
So I need something like (hasMany relationship in Users model - hasMany messages)
public function Messages()
    {
        return $this->hasMany('App\Models\Messages', 'from', 'id');
        return $this->hasMany('App\Models\Messages', 'to', 'id');
    }

But there are two returns, and the second one is an Unreachable statement.
So how to manage many relations when there is more many than one?

A: Create a second relation:
public function messageRetrieved()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
}

public function messageSend()
{
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

A: First you cannot use 2 return like this
public function Messages()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

It will better if you separate it to 2 method like this:
public function to()
{
    return $this->hasMany('App\Models\Messages', 'to', 'id');
}

public function from()
{
    return $this->hasMany('App\Models\Messages', 'from', 'id');
}


text:
Q: JRadio Buttons and Font change I am having a little bit of trouble trying to get my JRadio Buttons to change the color of the text depending on what the player chooses. I am just making the GUI for the game setup page. Something like, choose your army, followed by choose the number of players you want to interact with.
Here is what I have:
package SystemandDesign.RISK;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JFrame;
import javax.swing.ButtonGroup;

public class CharacterCreation extends JFrame{

  private Font redFont;
  private Font blueFont;
  private Font greenFont;
  private Font yellowFont;
  private Font grayFont;
  private Font blackFont;
  private JRadioButton three;
  private JRadioButton four;
  private JRadioButton five;
  private JRadioButton six;
  private JRadioButton red;
  private JRadioButton blue;
  private JRadioButton green;
  private JRadioButton yellow;
  private JRadioButton gray;
  private JRadioButton black;
  private JTextField textField;
  private ButtonGroup army;
  private ButtonGroup numPlayers;

  public CharacterCreation(){

    super("Character Creation");
    setLayout(new FlowLayout());

    textField = new JTextField("Your Army Color", 25);
    add(textField);

    //To remain true to the Game of Risk, instead of having individual name input for the game.
    //I am allowing which army color the player wants to be.
    //When the game is done being written out, I hope to have the font of individual player text, to be the color
    //of their army.

    //In the future when the model is done, the character screen will prevent players from having the same color army.
    redFont = new Font("Serif", Font.PLAIN, 14);
    blueFont = new Font("Serif", Font.PLAIN,14);
    greenFont = new Font("Serif", Font.PLAIN,14);
    yellowFont = new Font("Serif", Font.PLAIN,14);
    grayFont = new Font("Serif",  Font.PLAIN,14);
    blackFont = new Font("Serif",  Font.PLAIN,14);
    textField.setFont(redFont);

    red = new JRadioButton("Red Army", true);
    blue = new JRadioButton("Blue Army", false);
    green = new JRadioButton("Green Army", false);
    yellow = new JRadioButton("Yellow Army", false);
    gray = new JRadioButton("Gray Army", false);
    black = new JRadioButton("Black Army", false);
    add(red);
    add(blue);
    add(green);
    add(yellow);
    add(gray);
    add(black);

    army = new ButtonGroup();
    army.add(red);
    army.add(blue);
    army.add(green);
    army.add(yellow);
    army.add(gray);
    army.add(black);

    red.addItemListener(new RadioButtonHandler(redFont));
    blue.addItemListener(new RadioButtonHandler(blueFont));
    green.addItemListener(new RadioButtonHandler(greenFont));
    yellow.addItemListener(new RadioButtonHandler(yellowFont));
    gray.addItemListener(new RadioButtonHandler(grayFont));
    black.addItemListener(new RadioButtonHandler(blackFont));
    //End of the Army selection RadioButtons.

    //Now for the Player selection RadioButtons.

    three = new JRadioButton("3 players", true);
    four = new JRadioButton("4 players", false);
    five = new JRadioButton("5 players", false);
    six = new JRadioButton("6 players", false);
    add(three);
    add(four);
    add(five);
    add(six);

    numPlayers = new ButtonGroup();
    numPlayers.add(three);
    numPlayers.add(four);
    numPlayers.add(five);
    numPlayers.add(six);

  }

  private class RadioButtonHandler implements ItemListener{

    private Font font;

    public RadioButtonHandler(Font f){
      font = f;
    }

    public void itemStateChanged(ItemEvent event){

      textField.setFont(font);

      if(event.equals(red)){
        textField.setBackGround(Color.RED);
      }
      else if(event.equals(blue)){
        textField.setBackground(Color.BLUE);
      }
      else if(event.equals(green)){
        textField.setBackground(Color.GREEN);
      }
      else if(event.equals(yellow)){
        textField.setBackground(Color.YELLOW);
      }
      else if(event.equals(gray)){
        textField.setBackground(Color.GRAY);
      }
      else if(event.equals(black)){
        textField.setBackground(Color.BLACK);
      }

    }

  }

}

The background was Foreground but alas, neither have worked. What is it that I am doing wrong?

A: In itemStateChanged() you should compare the source of the event and not the event itself. For example:
  if(event.getSource().equals(red)){
    textField.setBackground(Color.RED);
  }

You can use ActionListener on radio buttons. See How to Use Radio Buttons for an  example.


text:
Q: Using apache mod_wsgi test error ---windows environment I have seen many solutions similar to my problem, but there is no one that suits me. Please help me solve it.
First, I want to test my apache's mod_wsgi.
httd.conf:
LoadFile "e:/zt_6.27/python/python35.dll"
LoadModule wsgi_module "e:/zt_6.27/python/lib/site-
packages/mod_wsgi/server/mod_wsgi.cp35-win_amd64.pyd"
WSGIPythonHome "e:/zt_6.27/python"

<VirtualHost *:80>
    WSGIScriptAlias /myapp E:\zt_6.27\Apache24\htdocs\myapp.wsgi
    <Directory 'E:\zt_6.27\Apache24\htdocs'>
        Require all granted
        Require host ip
        Allow from all
    </Directory>
</VirtualHost>

myapp.wsgi:
def application(environ,start_response):
  status='200 OK'
  output='Hello wsgi!'
  response_headers=[('Content-type','text/plain'),('Content-Length',str(len(output)))]
  start_response(status,response_headers)
  return[output]

I restart my apache service,call "http://localhost/myapp".
It return 500 Internal Server Error.
I open the error.log of apache.
it show:
[Fri Aug 10 10:33:35.803119 2018] [wsgi:error] [pid 9252:tid 1408] [client
::1:57261] mod_wsgi (pid=9252): Exception occurred processing WSGI script
'E:/zt_6.27/Apache24/htdocs/myapp.wsgi'.
[Fri Aug 10 10:33:35.803119 2018] [wsgi:error] [pid 9252:tid 1408] [client
::1:57261] TypeError: sequence of byte string values expected, value of type
str found\r

I checked the code carefully and it is no problem.
What did I do wrong?
Other than this,I successfully ran this code yesterday, it went wrong today.
help me please!!

A: If using Python 3, you must use:
def application(environ,start_response):
  status = '200 OK'
  output = b'Hello wsgi!'
  response_headers = [('Content-type','text/plain'),('Content-Length',str(len(output)))]
  start_response(status,response_headers)
  return[output]

That is, change to:
output = b'Hello wsgi!'

The list returned, must have byte strings in it, not unicode strings.
To return unicode strings you would need to convert them to byte strings. I cheated here by just marking it as byte string to start with, but you should encode them to byte strings as UTF-8 instead.
I would suggest using a micro framework like Flask as it will handle these sorts of details for you.


text:
Q: Conditional prior in PyMC3 I am trying to build a model in which the prior assigned to a distribution is contingent on a particular value, and that value is another variable that is sampled.  For example, a student answering a question correctly is modeled according to a Bernoulli trial with probability p.  If the student has the given prerequisites (themselves part of the model), p should be drawn from Beta(20,5). If not, p should be drawn from Beta(5,20).
I got this to work in PyMC2 with the following code:
# prior for thetas - same for all students
lambda1 = pymc.Beta('lambda1',alpha=20,beta=5)
#top-level node - one for each student
theta1 = []
for i in range(num_students):
    theta1.append(pymc.Bernoulli('theta1_%i' % i, p=lambda1, plot=False))

lambda2 = [
    pymc.Beta('lambda2_0', alpha=5,beta=20),
    pymc.Beta('lambda2_1', alpha=20,beta=5)
]
lambda2_choices = []
theta2 = []
for i in range(num_students):
    @pymc.deterministic(name='lambda2_choice_%i'%(i), plot=False)
    def lambda2_choice(theta1 = theta1[i],
                     lambda2 = lambda2):
        if theta1 == False:
            return lambda2[0]
        elif theta1 == True:
            return lambda2[1]
    lambda2_choices.append(lambda2_choice)
    theta2.append(pymc.Bernoulli('theta2_%i' % i,p=lambda2_choice))

In other words, the prior assigned to the Bernoulli random variable is a deterministic function that returns a stochastic variable depending on the SAMPLED value of some other value, in this case theta1[i].
I can't figure out how to do this in PyMC3, as the @deterministic decorator no longer exists and deterministic functions have to have input/output as Theano variables.
I'd really appreciate any insight or suggestions!!

A: Here you can use:
pymc3.switch(theta[i], lambda2[1], lambda2[0])


text:
Q: Error 'Pride not defined' when using app.post in Express Following this course on NodeJS here:
https://app.pluralsight.com/player?course=api-design-nodejs-express-mongo&author=scott-moss&name=91bae158-711d-4af0-a44d-7f48435436b9&clip=3&mode=live
https://github.com/leongaban/api-design-node/blob/step-2-fix/server/server.js
I have the following simple server:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const port = 3000

app.use(express.static('client'))
app.use(bodyParser.urlencoded({ extended: true }))

const lions = []
let id = 0

app.get('/lions', function(req, res) {
  res.json(lions)
})

app.get('/lions:id', function(req, res) {
  let paramId = req.param.id
  let lion = lions.filter((lion.id === paramId))
  res.json(lion || {})
})

app.post('/lions', function(req, res) {
  let lion = req.body
  id++
  lion.id = id + ''

  console.log('lion', lion)

  lions.push(lion)

  res.json(lion)
});

app.listen(port, () => console.log(`NODE RUNNING on port: ${port}`))

In the frontend client code I am able to send the following request data:

age: "3"
gender: "female"
name: "1"
pride: "2"

However in the server my log console.log('lion', lion) returns just this: lion { id: '1' } the req.body is empty.
Then in the frontend console I get this error:

VM1567:3 Uncaught (in promise) ReferenceError: pride is not defined

Thoughts on where pride is expected? And why the req.body is empty on the server?

A: I forgot to use this middleware:
app.use(bodyParser.json())


text:
Q: Objdump: Retrieve flags I'm actually studying the unix objdump command.
I want to retrieve the flags showed by the command "objdump -f file"
Here is an example

$>objdump -f /bin/ls
/bin/ls:     file format elf64-x86-64 architecture: i386:x86-64, flags 0x00000112:
EXEC_P, HAS_SYMS, D_PAGED
start address 0x0000000000404e68

I know that I can obtain 112 by making an | on the flags that are bitmasks defined in BSD lib.
The masks are:

#define BFD_NO_FLAGS    0x00
#define HAS_RELOC       0x01
#define EXEC_P          0x02
#define HAS_LINENO      0x04
#define HAS_DEBUG       0x08
#define HAS_SYMS        0x10
#define HAS_LOCALS      0x20
#define DYNAMIC         0x40
#define WP_TEXT         0x80
#define D_PAGED         0x100

Thanks to the elf struct and the e_type attribute I can obtain the HAS_RELOC flag and the EXEC_P flag.
How can I obtain the others?
Have I to retrieve 112 to get the flags or have I to retrieve the flags one by one? .


text:
Q: Best way to test continuous queries before adding them to production influxdb? Whats the best way to add a new continuous query to a production db influxdb? Clone the production influxdb ? I was hoping to avoid that. Is there a good way to test and try them it just through the web admin interface?

A: I guess you could:

*

*create a temporary measurement .. setup the CQ .. insert some sample data and check the result once the CQ executes

*[better approach] Send your timeseries data to 2 different measurement tables in parallel. Run your CQ experiments on one of them and discard it once you have the query you like.
The web interface might not help you much because CQ don't return results when you execute. They just pipe the output to a new measurement table you define. You can then run queries on the down sampled measurement table once at least 1 iteration of CQ finishes successfully.
Would love to hear other thoughts though.

A: New version of InfluxDB supports INTO clause:
https://docs.influxdata.com/influxdb/v1.4/query_language/data_exploration/#the-into-clause
So you can run your own CQ SELECT statement directly (don't forget add WHERE time clause for GROUP BY time).


text:
Q: Why does my log file say server failed to start, but application is running? Would like to preface I am by no means an AWS/Linux/Shell expert, some of my setup is probably not the greatest but most of it has been working for me so far.
I am running a Spring Boot app on an AWS EC2 instance (AWS Linux). I have setup CodeDeploy to deploy my source code, build it, and run the produced jar on the EC2 instance when I push to my main GitHub branch.
The app starts up just fine and runs. However, the log file that I am writing to always states:

APPLICATION FAILED TO START

description: Web Server failed to start. Port 80 was already in use

The app is running just fine on port 80 and is accessible via my domain I have setup to point to my EC2 instance's elastic ip.
When connected to the instance I have run ps -ef | grep jarName and found that two results come back. One is sudo nohup java -jar jarName.jar and the other is java -jar jarName.jar, am I somehow running the jar twice and that is why it is "failing" in the log file? When I stop everything and manually run sudo java -jar jarName.jar it runs fine, when I close it and look at the log file everything looks fine.
A few files that may be of interest:

*

*clean.sh (runs BeforeInstallation in appspec.yml):

cd /home/ec2-user
echo "killing jarName"
#Force to kill all "jarName" processes
SERVICES=$(ps -ef | grep jarName | grep -v grep | awk '{print $2}')
if [ $SERVICES != "" ]; then
    echo "killing jarName services already running"
    sudo kill -9 $SERVICES
fi

if [ "$?" != "0" ]; then
    echo "Killing process failed"
    exit 1
fi
# delete the app folder if it already exists
echo "removing sourceFolder folder"
sudo rm -rf sourceFolder
if [ "$?" != 0 ]; then
    echo "Removing folder failed"
    exit 1
fi

*

*gradleBuild.sh (runs as AfterInstallation in appspec.yml):

# runs the gradle build command
echo "starting gradleBuild.sh"
cd /home/ec2-user/sourceFolder
sudo ./gradlew --stop
sudo ./gradlew clean -x test build
if [ "$?" != "0" ]; then
    echo "error building jar"
    exit 1
fi

*

*startServer.sh (runs as ApplicationStart in appspec.yml):

echo "starting server"
cd /home/ec2-user/sourceFolder/path/jarLivesHere
# run as background and also close things according to AWS docs
sudo java -jar ./jarName.jar > /dev/null 2> /dev/null < /dev/null &

*

*Lastly my logback configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOGS" value="./logs" />
    <timestamp key="startTimeStamp" datePattern="yyyy-MM-dd'_'HH-mm-ss.SSS"/>
    <appender name="Console"
        class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="RollingFile"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/spring-boot-logger-${startTimeStamp}.log</file>
        <encoder
            class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>

        <rollingPolicy
            class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </root>

</configuration>

Appreciate any and all input/ideas!

A: I believe I have somehow solved this, or it just started to magically work more consistently. What I did:

*

*In my build.gradle, I disabled a "plain" jar that was being generated (a "fat" jar and plain jar were both being created). Not sure if this was really part of the problem

*I updated my scripts to include more echo statements to try and gather more information. This showed that occasionally I was having issues with killing the already running processes/services. In my first if statement of clean.sh I changed $SERVICES to "$SERVICES"

*I ran a search for the services again in startServer.sh to verify if anything was running immediately before calling to start the jar

After doing those 3 things, it seemed to start more consistently and the log file is being updated as expected.
If I find more out in the future I will try to update this response also.


text:
Q: Pygame Sprites randomly disappearing I made this game and it WORKS!! Well, it works occasionally. For some reasons, sometimes either the gas sprite or the redCar sprite just disappears for no reason...
Here is the code:
"""
Player Car
"""

import pygame, random
pygame.init()

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

class RedCar(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("red.png")
        self.image = pygame.transform.scale(self.image,(50,75))
        self.rect = self.image.get_rect()

        if not pygame.mixer:
            print("problem with sound")
        else:
            pygame.mixer.init()
            self.sndYay = pygame.mixer.Sound("yay.ogg")
            self.sndThunder = pygame.mixer.Sound("thunder.ogg")

    def update(self):
        mousex, mousey = pygame.mouse.get_pos()
        self.rect.center = (mousex, 430)

class GasCan(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("gas.png")
        self.image = pygame.transform.scale(self.image,(50, 50))
        self.image = self.image.convert_alpha()
        self.rect = self.image.get_rect()
        self.reset()

        self.dy = 5

    def update(self):
        self.rect.centery += self.dy
        if self.rect.top > screen.get_height():
            self.reset()

    def reset(self):
        self.rect.top = 0
        self.rect.centerx = random.randrange(0, screen.get_width())

class YellowCar(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("yellow.png")
        self.image = pygame.transform.scale(self.image,(50, 75))
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.centery += self.dy
        #self.rect.centery += random.randrange(5, 20)
        if self.rect.top > screen.get_height():
            self.reset()

    def reset(self):
        self.rect.bottom = 0
        self.rect.centerx = random.randrange(190, screen.get_width())
        self.dy = random.randrange(10, 30)

class Bush(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bush.png")
        self.image = pygame.transform.scale(self.image,(50, 50))
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.centery += 10
        if self.rect.top > screen.get_height():
            self.reset()

    def reset(self):
        self.rect.bottom = 0
        self.rect.centerx = random.randrange(0, 150)

class Road(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("road.png")
        #self.image = pygame.transform.scale(self.image,(640, 480))
        self.rect = self.image.get_rect()
        self.dy = 10
        self.reset()

    def update(self):
        self.rect.bottom += self.dy
        if self.rect.top >= 0:
            self.reset()

    def reset(self):
        self.rect.bottom = screen.get_height()

class Scoreboard(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.lives = 11
        self.score = 0
        self.level = 0
        self.font = pygame.font.SysFont("None", 50)

    def update(self):
        self.text = "Car: %d, score: %d, level: %d" % (self.lives, self.score, self.level)
        self.image = self.font.render(self.text, 1, (255, 255, 0))
        self.rect = self.image.get_rect()

def Game():
    pygame.display.set_caption("Car")

   # level =
    background = pygame.Surface(screen.get_size())
    background.fill((0, 0, 0))
    screen.blit(background, (0, 0))
    redCar = RedCar()
    gas = GasCan()
    yellowCar1 = YellowCar()
    yellowCar2 = YellowCar()
    yellowCar3 = YellowCar()
    yellowCar4 = YellowCar()
    yellowCar5 = YellowCar()
    bush1 = Bush()
    bush2 = Bush()
    bush3 = Bush()
    road = Road()
    scoreboard = Scoreboard()

    goodSprites = pygame.sprite.Group(gas, road, redCar)
    scoreSprite = pygame.sprite.Group(scoreboard)
    badSprites = pygame.sprite.Group(yellowCar1, yellowCar2, yellowCar3, yellowCar4, bush1, bush2, bush3)

    clock = pygame.time.Clock()
    keepGoing = True
    while keepGoing:
        clock.tick(30)
        pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False

      #  if scoreboard.score < 500:
      #      badSprites = pygame.sprite.Group(yellowCar1, yellowCar2, yellowCar3, bush1)
      #      scoreboard.level = 1
      #  elif scoreboard.score < 1000:
      #      badSprites.add(yellowCar4)
      #      badSprites.add(bush2)
      #      scoreboard.level = 2
      #  elif scoreboard.score < 1500:
      #      badSprites.add(yellowCar5)
      #      badSprites.add(bush3)
      #      scoreboard.level = 3

        if redCar.rect.colliderect(gas.rect):
            redCar.sndYay.play()
            gas.reset()
            scoreboard.score += 100

        if scoreboard.score % 5 == 0:
            scoreboard.lives + 1

        hitCar = pygame.sprite.spritecollide(redCar, badSprites, False)

        if hitCar:
            redCar.sndThunder.play()
            scoreboard.lives -= 1
            if scoreboard.lives <= 0:
                keepGoing = False
            for theCar in hitCar:
                theCar.reset()

        goodSprites.clear(screen, background)
        badSprites.clear(screen, background)
        scoreSprite.clear(screen, background)

        goodSprites.update()
        badSprites.update()
        scoreSprite.update()

        goodSprites.draw(screen)
        badSprites.draw(screen)
        scoreSprite.draw(screen)

        pygame.display.flip()

    pygame.mouse.set_visible(True)
    return scoreboard.score

def instructions(score):
    redCar = RedCar()
    road = Road()

    allSprites = pygame.sprite.Group(road, redCar)
    insFont = pygame.font.SysFont(None, 30)

    instructions = (
    "Car Survival.     Last score: %d" % score ,
    "Instructions:  Drive your car,",
    "and avoid cars and bushes.",
    "",
    "Gain points by driving over the gas cans.",
    "",
    "good luck!",
    "",
    "click to start, escape to quit."
    )

    insLabels = []
    # Create a rendered list of instructions, ready for display
    for line in instructions:
        tempLabel = insFont.render(line, 1, (255, 0, 0))
        insLabels.append(tempLabel)

    keepGoing = True
    clock = pygame.time.Clock()
    pygame.mouse.set_visible(False)
    while keepGoing:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
                donePlaying = True

            # Check for a mouse click
            if event.type == pygame.MOUSEBUTTONDOWN:
                keepGoing = False
                donePlaying = False
            # .... or a quit
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    keepGoing = False
                    donePlaying = True

        allSprites.update()
        allSprites.draw(screen)

        # Display the instructions
        for i in range(len(insLabels)):
            screen.blit(insLabels[i], (50, 30*i))

        pygame.display.flip()

    pygame.mouse.set_visible(True)

    return donePlaying

def main():
    donePlaying = False
    score = 0
    while not donePlaying:
        donePlaying = instructions(score)
        if not donePlaying:
            score = Game()
    pygame.quit()

if __name__ == "__main__":
    main()

Sometimes the redCar appears, but sometimes it doesnt. Does anybody have any clue?


text:
Q: Chrome typeahead menu displaying incorrectly I just installed Windows 7 Professional on my Asus laptop. I then install Google Chrome, version
Google Chrome   36.0.1985.125 (Official Build 283153) m

I am getting a strange display error when I type in the address bar of chrome. The height of the search prediction or typeahead box seems to be getting set incorrectly.

Zoomed in:

Any suggestions? Also, I apologize if I have posted this in the wrong stack exchange network. I am happy to move it.

A: I found a workaround for this by selecting 'Disable desktop composition' under Compatibility settings.
I had a similar problem with Mozilla Thunderbird's context menu after installing a complete custom theme. I'm not really sure if they're related, they were both fixed by checking 'Disable desktop composition' under Compatibility settings (reverting to the default theme for Thunderbird also fixed it). It also seems to be happening in Chrome with the boxes showing a link's location when you hover over a link.
Hoping someone else can shed some light on this, and possibly provide a better solution?


text:
Q: Should design documents be organized based on data model? In CouchDB, should design documents be made for each "data entity", or model, that is being stored in the database? Or, should there be one design document that encompasses views for all of your needed views?
For example, if I have some Users and Comments in the database, would I have a single design document possibly called _design/blog and in it I'd have views named like usersByName, or commentsByDate, etc.
Or, should I have seperate design documents, like _design/users, _design/comments, in which I have views named like byName, or byDate?

A: That is a good question.A design document by itself is just a collection of views ,list , show,update functions.All of the work of your "application layer" will be performed by these functions.So I feel that rather than having a different design document for each of of your entities the separation should be made on these functions.The blogging scenario that you have outlined in the question is a great example of how design documents should be used.
Think of design documents as the file structure of your application.If you were building applications using some other framework you would probably have only one file structure for your application.By the way there is nothing stopping you from creating more than one design document in the application.But I feel that it gets a little unmanageable this way.
Just to recap
One design document per application with separate view,show functions if needed.


text:
Q: Parsing JSON using Newtonsoft.JSON I have a JSON string as follows:
[{
    "ID":"1",
    "title":"New Product Launch",
    "fro":"Vitamin D",
    "summary":"New Vitamin D prodcut",
    "type":"image",
    "link":"http:\/\/www.foo.in\/upload\/image\/1.png",
    "detail":"13-11-2013",
    "fileSize":23763
},
{
    "ID":"2",
    "title":"New Product Launch",
    "fro":"Vitamin D",
    "summary":"New Vitamin D prodcut",
    "type":"image",
    "link":"http:\/\/www.foo.in\/upload\/image\/1.png",
    "detail":"13-11-2013",
    "fileSize":23763
}]

My code for parsing is as follows:
AnnouncementListObject resultsJSON = JsonConvert.DeserializeObject<AnnouncementListObject>(json); //line1

using (AnnouncementDataContext context = new AnnouncementDataContext(Con_String))
{
     AnnouncementData alData = new AnnouncementData();
     alData.announcementID = int.Parse(resultsJSON.ID);
             .
             .
             .
             .
       context.AnnouncementData.InsertOnSubmit(alData);
       context.SubmitChanges();
}

EDIT:
public class AnnouncementListObject
{
    public string ID { get; set; }
    public string title { get; set; }
    public string fro { get; set; }
    public string summary { get; set; }
    public string type { get; set; }
    public string link { get; set; }
    public string detail { get; set; }
    public object fileSize { get; set; }
}

But it throws error on line 1 where I deserialize the JSON data. I want to store this multiple data rows in database. I cannot use foreach loop here as JSON data is not enclosed under root node. Any help on how should I go about?

A: Try deserializing to a list like so
var resultsJSON = JsonConvert.DeserializeObject<List<AnnouncementListObject>>(json); //line1

You're dealing with an array of JSON objects, but you're trying to cast it as a single object.


text:
Q: Facebook like button not working on recent wordpress blog posts I have a facebook like button on each of my wordpress blog posts, this worked fine up until about 2 weeks ago, and now all recent blog posts don't have functioning like buttons.
This is the response I get when I click the like button (post link)
for (;;);{"__ar":1,"payload":{"requires_login":false,"success":false,"already_connected":false,"is_admin":false,"show_error":false,"error_info":null}}

and for the old blog posts that DO work (post link):
for (;;);{"__ar":1,"payload":{"requires_login":false,"error_info":null,"show_error":false,"node_type":"ExternalLink","node_id":"xxxxxxxxxxxxxxxxx","edge_type":"ExternalLinkLike","connect_text":0,"success":true,"already_connected":true,"user_profile":{"name":"xxxxxxx","profile_url":"http:\/\/www.facebook.com\/xxxxxxx","pic_square":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-snc4\/xxxxxx_xxxxxxxxx_xxxxxxx_x.jpg"},"story_fbid":"xxxxxxxxxxxxxxxxx","is_admin":false,"admin_url":""},"invalidate_cache":[0]}

I've tried replacing the like box code, removing the href attribute from the like box tag, running each link through Facebook URL Linter and none of this has worked!
I don't understand why it works for old blog posts and not new ones, there are no differences between them (that I know of).

A: This issue has nothing to do with your code. It is a FB issue I encounter on my websites as well. Did some research and came up with this:

*

*this behavior is intermittent, may work on some pages, may fail on others

*if you go on this page: http://developers.facebook.com/tools/lint/ and enter your url there, first time it will show up an error, afterwards the page will load. Hit some refreshes and afterwards the like button on your site (on the entered url) will suddenly start working... Very weird! I think it has something to do with FB crawler and (maybe) when accessing the lint tool you somehow force the crawler to recheck your page or something.

If anyone finds out something else, please share, the issue is really annoying...

A: Looking at the forums here:
http://forum.developers.facebook.net/viewforum.php?id=53
It looks like several other developers are running into the same issue. Some posts there also brought up having to use the lint tool to get their like buttons to work. I've also gotten it to work on my site by just mashing the Like button until it eventually accepts it so like what hpuiu said, i'm pretty confident that this problem's on their end.
Edit: And maybe on a related note, another post said that FB stopped scraping their site until they used the lint tool on their page and another said that they seem to consistently get this issue for any new posts that're around for less than 24 hours.

A: You could try to add the Iframe version of the like box instead of their javascript version. Sometimes it actually works better when loading multiple post for example.

A: Facebook doesn't like the '/' at the end of the url.  So you can use something like this to omit the '/' at the end of the url :
$title = get_permalink();
<fb:like href="<?php echo substr($title, 0, -1); ?>" layout="button_count" width="300" show_faces="false"></fb:like>


text:
Q: VBScript: Error 10023 in : Array index out of range (trouble when reusing an array variable) Using Sax ActiveX Scripting (long story), I have 3 nested if statements which reuse the same return variable. Script looks roughly like:
Dim rtnArray As Variant
If variable1 <> "" Then
    ' Perform SQL query against DB2 database
    rtnArray = DB2SQLSearch(Query)
    If UBound(rtnArray) = 0 Then
        ' ditto
        rtnArray = DB2SQLSearch(Query2)
        MsgBox "Gets this far"
        If UBound(rtnArray) = 0 Then ' Error!
            ' Never make it here

What's odd is that this same code structure is working in a script I wrote last week; I simply changed a couple of the queries and the name of the function (find > replace).
After the 2nd query, I've tried a MsgBox CStr(rtnArray(0)(0)) but it yields Error 10025 in : Array has a different number of indexes.
Error codes correspond to the following manual:
http://www.ftgsoftware.com/manuals/basic32.pdf

A: You can either store it in another variable, or ReDim the rtnArray variable to havve the proper size.  In order to Redim, you need to know the size.

A: Figured it out.
In this particular case, the user that I was connecting as had authorization to the first table, but not the second.
This did not throw an error, but there is a message I can check to see whether there was a success or not, so I can look for that and throw my own error, instead of passing back a null array. (it's not a proper Null, frankly I'm still not 100% sure what it is, aside from a Variant. But it sure doesn't like UBound()!


text:
Q: Is there a way to have a root element wrapper with javax.xml? I have a Jeresey application. I have several resources that use beans annotated with javax.xml annotations for providers so the result returns in xml or json depending on what is sent in the accept header with xml being the default. All that works fine. Now, I need to add a root element to every response.
Here is a sample Provider Bean that the resource sets with data and returns the result.
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "error")
public class ErrorProvider {

private String errorCode;
private String errorMessage;

public ErrorProvider(){}

public ErrorProvider(final String errorCode,final String errorMessage){
    setErrorCode(errorCode);
    setErrorMessage(errorMessage);
}

@XmlAttribute(name = "number")
public String getErrorCode() {
    return errorCode;
}

public void setErrorCode(final String errorCode) {
    this.errorCode = errorCode;
}

@XmlElement
public String getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(final String errorMessage) {
    this.errorMessage = errorMessage;
}
}

The produces annotation on the resource method is:
@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})

So the default return is in XML unless json is defined in the accept header of the request. Like I said, this works fine. It returns something like this:
<error code="100">
    <errorMessage>An error occurred</errorMessage>
</error>

OK, enough with the backdrop, now with the question. I need to add a root element to all of these providers, which will be the same for all. So it would look like this:
<transaction>
    <status>ok</status>
    <error code="100">
        <errorMessage>An error occurred</errorMessage>
    </error>
</transaction>

It would be cool to have something like an @XmlElementWrapper at the class level. I tried creating another bean annotated with the javax.xml and tried to extend it, tried to do a generic type bean. I just can't figure it out. The best thing I was able to do is to have the transaction annotation inside the error XML like it was another element. I know I could edit each provider bean to include the transaction root element, but I think there should be a way to create that once and apply to every provider bean.

A: You could add a ContainerResponseFilter that wraps your responses using the Transaction object. This is how it could look like (untested):
public class MyFilter implements ContainerResponseFilter {
    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        response.setEntity(new Transaction(response.getEntity()));
        return response;
    }
}

You can find out more about how to register filters here: http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/container/filter/package-summary.html


text:
Q: How to seperate longer stringvalues with tidyr into two columns When I try to seperate a column with (long) string values:
df <- tbl_df(c("Indian | Londen", "Greek | Amsterdam", "Hamburger and BBQ | Paris du Nord"))
df <- separate(df, col = value, into = c("var1","var2"), sep = " | ")

i get a warning message which says that there are too many values at three locations and when i look the altered dataframe i don't get the desired df
# A tibble: 3 × 2
       var1  var2
*     <chr> <chr>
1    Indian     |
2     Greek     |
3 Hamburger   and

It seems to split at each space, does anyone know a way to work around this? var2 should contain the city or area name, thanks.

A: separate interpret sep parameter as regular expression when it is character. So you need to escape | which is a special character (or) in regex, pattern | (whitespace or whitespace) is the same as a whitespace in regex, which is why your strings are split by space:
df <- separate(df, col = value, into = c("var1","var2"), sep = " \\| ")

df
# A tibble: 3 × 2
#               var1          var2
#*             <chr>         <chr>
#1            Indian        Londen
#2             Greek     Amsterdam
#3 Hamburger and BBQ Paris du Nord

A: Just do :
Since pipe has a special meaning in regex , it means "OR" ,hence you have to escape it first. you can also use it under character class [|] to get the same result
df1 <- separate(df, col = value, into = c("var1","var2"), sep = "\\|")

OR
df1 <- separate(df, col = value, into = c("var1","var2"), sep = "[|]")

BASE R way:
dfx<- data.frame(do.call("rbind",strsplit(df$value,split="\\|")))

Output:
> dfx
                  X1             X2
1            Indian          Londen
2             Greek       Amsterdam
3 Hamburger and BBQ   Paris du Nord


text:
Q: Integrating Codeigniter 2 with phpspec2 I want to integrate phpspec2 with CodeIgniter 2. I've succesfully installed phpspec using composer as described on phpspec website. Now I'd like to integrate it into my CodeIgniter 2 installation. I've found an article by AniDear  on this subject and did everything as described. However when I run bin/phpspec I get an error:
PHP Warning: require(core/Common.php): failed to open stream: No such file or directory
in  C:\xampp\htdocs\eljotengine\spec\ci_bootstrap.php on line 37

Warning: require(core/Common.php): failed to open stream: No such file or directory in C:\xampp\htdocs\eljotengine\spec\ci_bootstrap.php on line 37

and so on. My file structure looks like this:
eljotengine
|-application
|-sytem
|- ... other CI
|-spec
| |- ci_bootstrap.php

I am using xampp on Windows 7. My ci_bootstrap.php file looks like the one in the above mentioned article by AniDear.
I've tried to change the paths in the ci_bootstrap.php file (it seems to be the problem) however it did not change much.
Any ideas how to make this work?
Greets :)

A: I am having problem with PHPSpec2 too.
Since I have only tried it with PHPSpec (not PHPSpec2), I would suggest you to install PHPSpec  instead. Just change the file composer.json, on the line "phpspec/phpspec2": "*" to "phpspec/phpspec": "*" , then runs composer update again.
Run this phpspec, by using command vendor\bin\phpspec.php.bat spec on your project path, whereas "spec" is the folder containing spec files.
And since you're running phpspec from your project directory, I suggest changing content inside  ci_bootstrap.php as follow
define('BASEPATH',realpath('system/').'/'); //set absolute path to CI system/
define('APPPATH', 'application/'); //set relative path to CI application
set_include_path(
    get_include_path().PATH_SEPARATOR.
    realpath(APPPATH).PATH_SEPARATOR.
    realpath(BASEPATH).PATH_SEPARATOR.
    'spec');  //adding 'spec' in path, for easily do require 'ci_bootstrap.php' from inside spec files

require BASEPATH.'core/Common.php';
require APPPATH.'config/constants.php';
require BASEPATH.'core/Controller.php';


text:
Q: Why does MultiBinding with a Converter not work within a ToolTip? For part of a fairly-complex WPF ToolTip, I'm attempting to use a MultiBinding to produce formatted text based on two properties. The problem is, the binding's MultiConverter receives DependencyProperty.UnsetValue for each item in its values array.
The following works, using a single Binding:
<ToolTipService.ToolTip>
  <StackPanel>
    <TextBlock>
      <TextBlock.Text>
        <Binding Path="Amt" Converter="{StaticResource singleValueConverter}"/>
      </TextBlock.Text>
    </TextBlock>
  </StackPanel>
</ToolTipService.ToolTip>

And so does this, using a MultiBinding with StringFormat:
<ToolTipService.ToolTip>
  <StackPanel>
    <TextBlock>
      <TextBlock.Text>
        <MultiBinding StringFormat='{0:C} in {1}'>
          <Binding Path="Amt"/>
          <Binding Path="Currency"/>
        </MultiBinding>
      </TextBlock.Text>
    </TextBlock>
  </StackPanel>
</ToolTipService.ToolTip>

But a MultiBinding with a Converter does not:
<ToolTipService.ToolTip>
  <StackPanel>
    <TextBlock>
      <TextBlock.Text>
        <MultiBinding Converter="{StaticResource multiValueConverter}">
          <Binding Path="Amt"/>
          <Binding Path="Currency"/>
        </MultiBinding>
      </TextBlock.Text>
    </TextBlock>
  </StackPanel>
</ToolTipService.ToolTip>

The bindings in the last example don't receive any value. This isn't the case outside of a ToolTip - what is going on such that binding fails in this specific case?

A: Try setting Mode="OneWay" on your binding.
Also, have you checked this problem and solution:
http://social.msdn.microsoft.com/Forums/en-IE/wpf/thread/15ada9c7-f781-42c5-be43-d07eb1f90ed4

The reason of this error is the
  tooltips have not been loaded, so
  DependencyProperty.GetValue returns
  DependencyProperty.UnsetValue. You
  should add some code to test that is
  value is Dependency.UnsetValue. The
  following code shows how to do this.

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    if (values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue)
        return "";
    [...]
}

A: Try this:
<ToolTipService.ToolTip>
    <StackPanel>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding Converter="{StaticResource multiValueConverter}">
                    <MultiBinding.Bindings>
                        <BindingCollection>
                            <Binding Path="Amt"/>
                            <Binding Path="Currency"/>
                        </BindingCollection>
                    </MultiBinding.Bindings>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </StackPanel>
</ToolTipService.ToolTip>


text:
Q: Calculate the applied force associated with uniform distortion of an area I am exploring Hooke's Law and considering how it might apply to an arbitrary area (perhaps as a slice of some volume).
Since $$ F = -kx $$
Would it be correct to calculate the force, $F$, associated with uniform distortion of an area as follows:
$$F = -kx^2$$

A: No, it is not like that. First of all, you don't represent energy by $F$. That's probably a typo. And for the calculation of energy, it is not just $E=F \times x = kx^2$ because as the $x$ changes, the force acting on that part of the object also changes. Hence the force is not uniform and we have to integrate taking differential portions in order to get the required expression.
Say we consider a portion at a distance $x$ from one side. So force acting on that portion is $F=kx$. Now for $dx$ displacement due to the stress applied, the work done = energy used = $E= kx \cdot dx$
Hence the total energy is given by summing all such $dx$ parts i.e. by integrating:
$$E=\int kx \cdot dx = \frac{1}{2}kx^2$$


text:
Q: mod_rewrite on parent and subfolder I ran into some strange behaviour using mod_rewrite under Apache. Here's how the current RewriteRules look:
RewriteRule ^(.*)/collections/(.*)/(.*)/?$ bootstrap.php?controller=category&user=$1&collection=$2&category=$3 [L]
RewriteRule ^(.*)/collections/(.*)/?$ bootstrap.php?controller=collection&user=$1&collection=$2 [L]

My expectations of the above rules is that accessing a URL such as domain.com/BenM/collections/0/1/ should take me to the category controller, while domain.com/BenM/collections/0/ should take me to the collection controller.
At the moment, both URL structures rewrite to bootstrap.php?controller=category....
My understanding was that if the [L] flag is specified, Apache looks no further and performs the rewrite.
Could anyone point in the right direction here, as I just cannot beat this... What should the rewrites look like to achieve the functionality I explained above?

A: You're dealing with greediness-related issues. Also, you probably want a length of at least one, and you almost certainly don't want slashes in your params.
Potential solution:
^([^/]+)/collections/([^/]+)/([^/]+)/?$
^([^/]+)/collections/([^/]+)/?$


text:
Q: How to save ArrayAdapter in onSaveInstanceState? I am doing a messenger app and for the message history I created a ListView with ArrayAdapter. I have a service that do the messaging activities, so supposedly it should receive a message even when the user is interacting with something else. However when I return to the app after pressing the home button I get an empty list view which is a bizarre thing for my app. H tried saving the Adapter in onsavingInstance but it's not working because it's not serialzable. please help me with that how could I preserve my list view. below is some patches of my code.
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;

private ListView mConversationView;
// Initialize the array adapter for the conversation thread

mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);

/**
 * save the listView

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("mArrayAdapter",  (Serializable) mConversationArrayAdapter);
    Toast.makeText(this, "History saved.", Toast.LENGTH_SHORT).show();
    }
 */

public void onStart(Bundle savedInstanceState) {
    super.onStart();
    if(D) Log.e(TAG, "++ ON START ++");
   // if (savedInstanceState != null) {
  //    mConversationArrayAdapter = (ArrayAdapter<String>) savedInstanceState.getSerializable("mArrayAdapter");
  //  }
    setupChat();
}

A: onSaveInstanceState is not a place to save persistent data... in fact, it might not even be called.
I suggest you populate your ArrayAdapter in onResume and save it in onPause.


text:
Q: My domain name is followed by index.php ,when I open any webpage I'm developing website using wordpress, running on Ec2 instence. My issue is index.php is followed by all my pages.
so if my page is xyz and I open it, it will open as abc.com/index.php/xyz/ , while it should open as abc.com/xyz/
I have not used any permalink. I tried to change and remove index.php from perma link .It will stop working. All my files are in root directory. PLEASE solve my issue.
How can I get it to work directly as abc.com/xyz/ ?

A: You probably don't have mod_rewrite enabled (if you are using Apache). Login to your EC2 instance, run sudo a2enmod rewrite, then restart apache sudo service apache2 restart. Make sure to update your Permalink Settings in Wordpress. Should work after that.
This question has also been asked numerous times on Stack Overflow already -- please try searching next time.


text:
Q: Breaking out of an for statement in Java If i do something like this
boolean ret;
for(int i = 2;i<30;i++) {
  if ( 30%i == 0){
    ret = true;
  } else {
    ret = false;
  }
}

ret becomes true allready at 2, but also at 5,10 15, is there anyway to break out of the for statement as soon as ret becomes true?

A: Have you considered the break command
boolean ret = false;
for(int i = 2; i < 30; i++){
    if(30%i == 0){
       ret = true;
       break;
    }
}

A: Without using a structure breaking instruction, you can simply perform a check in the for condition.
boolean ret = false;
for(int i = 2;i<30 && !ret;i++) {
    if ( 30%i == 0){
        ret = true;
    } else {
        ret = false;
    }
}

A: You can't break out of an if. By the time it has decided which way the condition goes, it's already over and there's nothing left to skip. You only can break out of a loop, like the for.
But the incomparably better way of exiting early is to put your sample code into a method and use return. More readable, and with a good method name the purpose of the entire code (and the return) is immediately clear.