text:
Q: Gallery has stopped while cropping image in kitkat Nexus7 Problem:
I am fetching image from gallery and after that cropped that image and its working perfect in all device. But it is giving me error while running in Nexus 7 kitkat since i have checked build version for it with "Gallery Stopped" error. I have implemented code and all other neccessary permission in manifest file still not getting response. So can anybody resolve this?
Here is my Code:
 final String[] items = new String[] { "Take from camera",
            "Select from gallery" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.select_dialog_item, items);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Select Image");
    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) { // pick from
                                                                // camera
            if (item == 0) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                mImageCaptureUri = Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "tmp_avatar_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg"));

                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        mImageCaptureUri);

                try {
                    intent.putExtra("return-data", true);

                    startActivityForResult(intent, PICK_FROM_CAMERA);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
            } else { // pick from file

                Intent intent;

                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");
                    startActivityForResult(Intent.createChooser(intent,
                            "Complete action using"), PICK_FROM_FILE);
                } else {
                    intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");
                    startActivityForResult(Intent.createChooser(intent,

                    "Complete action using"), PICK_FROM_FILE);
                }
                /*
                 * Intent intent = new Intent();
                 *
                 * intent.setType("image/*");
                 * intent.setAction(Intent.ACTION_GET_CONTENT);
                 *
                 * startActivityForResult(Intent.createChooser(intent,
                 * "Complete action using"), PICK_FROM_FILE);
                 */
            }
        }
    });

    final AlertDialog dialog = builder.create();

    btnTakephoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.show();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK)
        return;

    switch (requestCode) {
    case PICK_FROM_CAMERA:
        doCrop();

        break;

    case PICK_FROM_FILE:

        if (Build.VERSION.SDK_INT < 19) {
            mImageCaptureUri = data.getData();

        } else {
            mImageCaptureUri = data.getData();
            ParcelFileDescriptor parcelFileDescriptor;
            try {
                parcelFileDescriptor = getContentResolver()
                        .openFileDescriptor(mImageCaptureUri, "r");
                FileDescriptor fileDescriptor = parcelFileDescriptor
                        .getFileDescriptor();
                myBitmap = BitmapFactory
                        .decodeFileDescriptor(fileDescriptor);
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        doCrop();

        break;

    case CROP_FROM_CAMERA:
        Bundle extras = data.getExtras();

        if (extras != null) {
            myBitmap = extras.getParcelable("data");

        }

        File f = new File(mImageCaptureUri.getPath());

        if (f.exists()) {
            f.delete();
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

        byteArray = stream.toByteArray();

        Intent n = new Intent();
        n.setClass(getApplicationContext(), EffectsActivity.class);
        n.putExtra("picture", byteArray);
        startActivity(n);
        break;

    }
}

private void doCrop() {
    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setType("image/*");

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(
            intent, 0);

    int size = list.size();

    if (size == 0) {
        Toast.makeText(this, "Can not find image crop app",
                Toast.LENGTH_SHORT).show();

        return;
    } else {
        if (mImageCaptureUri != null) {
            intent.setData(mImageCaptureUri);
        }

        intent.putExtra("outputX", 350);
        intent.putExtra("outputY", 350);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);

        if (size == 1) {
            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);

            i.setComponent(new ComponentName(res.activityInfo.packageName,
                    res.activityInfo.name));

            startActivityForResult(i, CROP_FROM_CAMERA);
        } else {
            for (ResolveInfo res : list) {
                final CropOption co = new CropOption();

                co.title = getPackageManager().getApplicationLabel(
                        res.activityInfo.applicationInfo);
                co.icon = getPackageManager().getApplicationIcon(
                        res.activityInfo.applicationInfo);
                co.appIntent = new Intent(intent);

                co.appIntent
                        .setComponent(new ComponentName(
                                res.activityInfo.packageName,
                                res.activityInfo.name));

                cropOptions.add(co);
            }

            CropOptionAdapter adapter = new CropOptionAdapter(
                    getApplicationContext(), cropOptions);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Choose Crop App");
            builder.setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            startActivityForResult(
                                    cropOptions.get(item).appIntent,
                                    CROP_FROM_CAMERA);
                        }
                    });

            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                    if (mImageCaptureUri != null) {
                        getContentResolver().delete(mImageCaptureUri, null,
                                null);
                        mImageCaptureUri = null;
                    }
                }
            });

            AlertDialog alert = builder.create();

            alert.show();
        }
    }

CropAction:
 public class CropOption {
  public CharSequence title;
  public Drawable icon;
  public Intent appIntent;
 }

CropOptionAdapter.java
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;

public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
    super(context, R.layout.crop_selector, options);

    mOptions = options;

    mInflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup group) {
    if (convertView == null)
        convertView = mInflater.inflate(R.layout.crop_selector, null);

    CropOption item = mOptions.get(position);

    if (item != null) {
        ((ImageView) convertView.findViewById(R.id.iv_icon))
                .setImageDrawable(item.icon);
        ((TextView) convertView.findViewById(R.id.tv_name))
                .setText(item.title);

        return convertView;
    }

    return null;
}
    }

A: To resolve the problem what i have done is to,
just change the code from this
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
    Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);

to
intent = new Intent(Intent.ACTION_PICK);
intent.setType("*/*");
intent.putExtra(
    android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri
);
startActivityForResult(
    Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);

Working like charm.


text:
Q: XBee ZDO active end point requests are not passed out to the UART when AO is set to 3 I configured my XBee 2 modules using X-CTU, one as a router API and other as a coordinator API by setting AO to 3. But when I send ZDO active end point requests, it is not passed out to the UART on the router side. But for our application we want the requests to be passed to the UART so that the controller can handle the requests. I tried both XB24-ZB and XB24-SE, but the XBee itself is providing a response for ZDO requests.
When I used profile ID 0x0109, the ZDO requests are passed to the UART for both XB24-ZB and XB24-SE. But according to the data sheet, the profile ID must be set to 0 to send ZDO commands. But when I do that, the request is not passed out to the UART. I am using firmware version 23A7 for the XB24-ZB router API and 21A7 for the XB24-ZB coordinator API.

A: Can you show the bytes you're sending as part of the request, or the frame that you're sending to the XBee that contains the ZDO request?  You need to make sure the source and destination endpoints are 0 and that the profile ID is 0.
The zigbee_walker sample from https://github.com/tomlogic/xbee_ansic_library sends Active Endpoint Requests, and responds to them.  You might want to try using that code for your tests.

A: As I saw in datasheet, XBEE handles supported ZDO requests itself when AO=3, and only pass non-supported ones to UART. you should set AO=1 to pass all ZDO requests to UART

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symfony CreateForm function runs out of memory I'm working on a 2.8 symfony project and I can't solve a problem I've been dealing with for a few weeks.
Every form I'm trying to create gets me a "Allowed memory size exhausted" error. This should be a configuration problem because my project is working on dev and prod environments, and on other computers. It's just not working on mine.

Error exemple : OutOfMemoryException in BundleEntryReader.php line
  134:
Error: Allowed memory size of 134217728 bytes exhausted (tried to
  allocate 134217736 bytes)

I'm working on Ubuntu. I tried remove and re-install both apache and php (7.1), but no success. I also tried to allow more memory and execution time, but my scripts keep running for dozens of minutes.
$projectForm = $this->createForm(
     new ProjectType($choices, $user->getCompany()),
     $project,
     ['action' => $this->generateUrl('company_project_create',['projectId' => $project->getId() ])]
);

I'd like to be able to generate a form. the problem is in the form generation. In every script I use, evrything is ok until the "$this->createForm()" function. Let's says that this application runs on computers with less ram.
/*****EDIT*****/
I found that the problem came from two types in my ProjectType : user and address :
$builder
     ->add('user', UserType::class, [
          'label' => 'customer.user.label',
     ])
     ->add('address', ProjectAddressType::class, [
          'label' => 'customer.project.address.label',
     ])

Here is for example where my userType has problem :
public function buildForm(FormBuilderInterface $builder, array $options)
{
     parent::buildForm($builder, $options);
     $builder
          ->add('photo', HiddenType::class, ['required'    => false])
          ->add('isSendDailyMail', CheckboxType::class, [
              'label'    => false,
              'required' => false,
     ]);
}


text:
Q: how can we run Neptune graph database on docker how can we run Neptune graph database on docker
Since Neptune DB has been productized recently it is not available on Localstack can someone guide me how to deploy AWS Neptune DB Service into docker container

A: You don't deploy neptune, you deploy a client application which uses an appropriate client library to access neptune.  The neptune software/hardware is managed by AWS and you can't access it except via API.

A: My guess is that you're attempting to create a local Neptune compatible docker container (i.e. some docker container with a compatible API). This would be similar to using minios when performing local integration testing with S3. If this is indeed what you're in search of I'd recommend using tinkerpop's gremlin-server image. This should get the job done for you since Neptune uses Gremlin for its query language.

A: For now, I found only one way. It is Pro version of Localstack. It contains Neptune DB. https://localstack.cloud/features/ Unfortunately free version of test container does not support DB interface. =(

A: Neptune is a fully managed graph database, and not a binary that can be independently deployed in your personal containers or infrastructure. You can run your client application in your own custom docker containers, and setup your network such that the container makes requests to the managed Neptune cluster that you have created.
Hope this helps.


text:
Q: Update one combobox by changing the second combobox I want to update one combobox by changing the second combobox.
for example:
I have this response (string):
var response = [{
    "A": "a2",
    "B": "b2",
    "C": "c2"
},
{
    "A": "a3",
    "B": "b3",
    "C": "c3"
},
{
    "A": "a3",
    "B": "b331",
    "C": "c33"
},
{
    "A": "a3",
    "B": "b33221",
    "C": "c3"
},
{
    "A": "a4",
    "B": "b4",
    "C": "c4"
},
{
    "A": "a2",
    "B": "b221",
    "C": "c222"
}];

and I want that in "myDropDownA" will be "a2, a3, a4".
and for example:
if I choose "a3" in "myDropDownA", than in "myDropDownB" will appear only: "b3, b331, b33221" (because they only refer to a3).
and I don't want repeated of "A" objects.
var myDropDownA = $("#myDropDownA");
$.each(response, function (index, obj) {
    //alert(index + ": " + obj.A);
    myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});

    var myDropDownB = $("#myDropDownB");
    $.each(response, function (index, obj) {
        //alert(index + ": " + obj.B);
        myDropDownB.append($("<option />").val(obj.B).text(obj.B));
});

what do I need to change (or to add) to make it work as above?

A: What you're missing is attaching an eventhandler to the change event of dropdown A repopulating dropdown B with relevant values.
var response = [
    { "A": "a2", "B": "b2", "C": "c2" },
    { "A": "a3", "B": "b3", "C": "c3" },
    { "A": "a3", "B": "b331", "C": "c33" },
    { "A": "a3", "B": "b33221", "C": "c3" },
    { "A": "a4", "B": "b4", "C": "c4" },
    { "A": "a2", "B": "b221", "C": "c222"}
];

var uniqueByProperty = function(arr, prop) {
    var seen = {};
    return arr.filter(function(elem) {
        var val = elem[prop];
        return (seen[val] === 1) ? 0 : seen[val] = 1;
    })
}

var aList = uniqueByProperty(response, "A");
var myDropDownA = $("#myDropDownA");
var myDropDownB = $("#myDropDownB");

// Populate dropdown A
$.each(aList, function(index, obj) {
    myDropDownA.append($("<option />").val(obj.A).text(obj.A));
});

// Attach event handler for dropdown A
myDropDownA.on('change', function(){
    var ddl = $(this);

    // Get related objects
    var bList = response.filter(function(elem) {
        return (elem.A === ddl.val());
    });

    // Populate dropdown B
    myDropDownB.empty();
    $.each(bList, function(index, obj) {
        myDropDownB.append($("<option />").val(obj.B).text(obj.B));
    });
});

// Trigger population of dropdown B
myDropDownA.change();

See this jsfiddle for a working demonstration.


text:
Q: test the presence of items in a list and return item or index I would like to know how to test the presence of multiple items in a list and return an associated item or index
import React from "react";
import { useState } from "react";

export default function AlertDialog() {
  function createData(name, weight, id) {
    return { name, weight, id };
  }

  const [id, setid] = useState(null);

  const rows = [
    createData("Frozen yoghurt", 200, 0),
    createData("Frozen yoghurt", 500, 1),
    createData("Eclair", 60, 2),
    createData("Cupcake", 30, 3)
  ];

  // return id
  const funct = () => {
    // rows.map((item) => (item.name === "Frozen yoghurt", item.weight === 500));
  };

  return
{funct()}
;
}

codesandbox.io

A: to

*

*test multiple items: check the length

*get an item: use filter

*get an index

relevant JS:
  // return id
  const funct = () => {
    // console.log(item.name === "Frozen yoghurt", item.weight === 500);
    // check length
    return rows && rows.length > 0
      ? rows
          // case of item
          .filter(
            (item) => item.name === "Frozen yoghurt" || item.weight === 500
          )
          // case of index
          .filter((item, index) => index === 1)
          .map((item) => (

              {item.name} - {item.weight} - {item.id}

          ))
      : null;
  };

  return (

      {rows && rows.length > 0 ? (

            Name - Weight - ID

          {funct()}

      ) : null}

  );

forked and updated codesandbox

A: I think it can be simply solved by using findIndex. It will return the index of the item matching to the conditions. If it doesn't exist, it will return -1.
If you want to have the item instead of its index, you can use the find method.
To get all items matching to the conditions, you can use the filter with the map.
1. For getting the index:
const funct = () => {
    return rows.findIndex((item) => item.name === "Frozen yoghurt" && item.weight === 500);
};

return
{funct()}
;

2. For getting the item:
const funct = () => {
    const item = rows.find((item) => item.name === "Frozen yoghurt" && item.weight === 500);
    return item ? {item.id} - {item.name} - {item.weight} : '';
};

return
{funct()}
;

3. For getting multiple items:
const funct = () => {
    return rows.filter((item) => item.name === "Frozen yoghurt")
        .map(item => (
{item.id} - {item.name} - {item.weight}
));
};

return
{funct()}
;


text:
Q: Is there a minimum range for an Intercontinental Ballistic Missile? To be more concrete: Would it be possible to fire a ICBM Minuteman III from Malmstrom Air Force Base in Montana (USA) to hit Helena (the capital of Montana) about a hundred kilometers away?
If not, what is the minimal distance the missile needs to travel before hitting its target?

A: I don't see any reason why a ballistic missile cannot hit an arbitrarily close point, unless there are such limitations in a specific design (say, software limitations). Moreover, it can hit a close point using a high trajectory or a low trajectory. If one uses a high trajectory, one should take into account the Earth's rotation. For example, if the missile speed is about 8 km/s, the high trajectory flight will take about 1600 s, and Helena, Montana, will move on the order of 400 km in 1600 s due to Earth's rotation, if I am not mistaken. @IamAStudent mentioned "a much sharper turn at the apex", but the missile would have low speed at the apex, so this should not be a problem.

A: Yes..  It would be possible to hit something that close with an ICBM.   The system would have to be reprogrammed.  The warhead would enter into space and would travel around the globe before re-entering and hitting your target.
This is a pretty good video of what happens on an ICBM launch.
https://www.youtube.com/watch?v=lOHHtIVP8Pw
A short-range ballistic missile (SRBM) is a ballistic missile with a range of about 1,000 kilometers (620 mi) or less. ... Within the U.S. Department of Defense, a medium-range missile is defined by having a maximum range of between 1,000 and 3,000 km and an ICBM is greater than 3500km.
So - to answer your question - could you launch a missile and have the warhead hit 100 miles away?  Yes, but it is not straight up and straight down.


text:
Q: Probability that A meets B in a specific time frame A and B are going to the math palace. A arrives between 12:00 and 13:00 o'clock and stays for 10 minutes, whereas B arrives between 12:00 and 14:00 o'clock and leaves immediately.
The time point in which they arrive is uniformly distributed on the stated intervals.
What is the probability that A and B meet each other?
My try:
P($X_{B}\in [X_{A}-10m;X_{A}+10m]) = F_{X_{B}}(X_{A}+10m)-F_{X_{B}}(X_{A}-10m)$
$= \frac{X_{A}+10m-12h}{14h-12h} - \frac{X_{A}-10m-12h}{14h-12h} = \frac{1}{6}$
Which is wrong. The correct solution would be $\frac{1}{12}$

A: I've got an alternative solution, done quite differently: Let $x$ be the time at which $A$ arrives and $y$ be the time at which $B$ arrives. Also, instead of considering the time, we consider the number of minutes from 12:00, i.e. $0<x<60$ and $0<y<120$ which is our sample space. In addition to that, we know that $A$ must arrive before $B$, so $y>x$ because if $B$ arrives first, he/she will leave immediately. Lastly, we know that after $A$ arrives at $x$, $B$ must arrive within 10 minutes, which means $y-x \leq 10$. Now we have two inequalities $$y\leq x + 10 \\ y>x$$ where $0<x<60$ and $0<y<120$. Plotting these yields the following graph:

The ratio of the dark blue area to the whole rectangle is $1/12$.

A: P($X_{B}\in [X_{A};X_{A}+10m]) = F_{X_{B}}(X_{A}+10m)-F_{X_{B}}(X_{A})$
$= \frac{X_{A}+10m-12h}{14h-12h} - \frac{X_{A}-12h}{14h-12h} = \frac{1}{12}$


text:
Q: Discord.js printing out ReferenceError: command is not defined I'm quite new to programming and i thought I'd mess around and try coding a discord bot using discord.js to mess with my friends.
Unfortunately though Im getting some errors, full log attached below (UnhandledPromiseRejectionWarning: ReferenceError: command is not defined)
Here is the full code:
const BotName = "name"; // Name
const Token = "token"; // Token
const SpamMessage = "hello"; // Message
const YourDiscordID = 398561449078685717; // My discord ID

// Actual bot code

const Discord = require("discord.js");
const prefix = "-";

const bot = new Discord.Client({disableEveryone: true});

bot.on("ready", async () => {
 bot.user.setActivity("Getting Things Ready", "https://twitch.tv/")

 console.log(`${BotName} Loaded!`);

 try {
     let link = await bot.generateInvite(["ADMINISTRATOR"]);
     console.log(link);
 } catch(e) {
     console.log(e);
 };
});

bot.on("message", async message => {
 if(message.author.bot) return;

 if(!command.startsWith(prefix)) return;

     if(command === `${prefix}spam`) {
         if(!message.author.id === YourDiscordID) return;
         let Ping = message.mentions.users.first();
         setInterval(function(){
             Ping.send(SpamMessage)
         },
             1200
         );
     };
});

bot.login(Token);

I expect to receive "Ready!" in the console after letting the bot join my server, instead its stuck on the message with a log in URL and if I type the command (-spam) on discord, I get the errors listed below.
Full console log

A: When your bot receives an event of type message, it invokes your callback and inside your callback you only receive message, so of course command will be undefined. Looking through some examples, I believe it should be like this:
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();

Here is the full example, I suggest checking it out.


text:
Q: Failure running spring application : NoSuchBeanDefinitionException I have some trouble running a java spring application : main component is fr.sgcib.cva.accounting.Computation inside Accounting.jar.
I am trying this command :
java -cp spring/*:./*:spring-core-3.1.1.RELEASE.jar:spring-context-3.1.1.RELEASE.jar:spring-beans-3.1.1.RELEASE.jar:log4j-1.2.16.jar:commons-lang3-3.1.jar:commons-logging-1.1.1.jar:spring-asm-3.1.1.RELEASE.jar:spring-expression-3.1.1.RELEASE.jar:.:Accounting.jar fr.sgcib.cva.accounting.Computation 3

The applicationContext.xml file is located in spring/, and looks like this :
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xmlns:security="http://www.springframework.org/schema/security" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

<import resource="classpath:spring/persistence.xml"/>

<context:annotation-config />
<context:component-scan base-package="fr.aaa.accounting, com.bbb.access"/>

<util:properties id="jdbcProps" location="jdbc.properties" />

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
         <value>classpath:configuration.properties</value>
         <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

The main class Computation.java :
package fr.aaa.accounting;

@Component
public class Computation {
static Logger logger = Logger.getLogger(Computation.class);

@Autowired
Runs runs;

public Computation() {
}

public Run initialize(Long runId) {
    Run run = runs.getRun(runId);
    return run;
}

public Runs getRuns() {
    return runs;
}

public void setRuns(Runs runs) {
    this.runs = runs;
}

/**
 * @param args
 */
public static void main(String[] args) {
    Long runId = Long.parseLong(args[0]);
    logger.info("RUNNING RUN_ID " + runId);

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
    Computation computer = context.getBean(Computation.class);
    /* etc. */

}
The console output I get when running the above command :
10:44:41,745 INFO main fr.aaa.accounting.Computation:299 - RUNNING RUN_ID 3
10:44:41,872 INFO main org.springframework.context.support.ClassPathXmlApplicationContext:495 - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@e0b6f5: startup date [Mon Mar 10 10:44:41 CET 2014]; root of context hierarchy
10:44:41,979 INFO main org.springframework.beans.factory.support.DefaultListableBeanFactory:557 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ee22f7: defining beans []; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [fr.aaa.accounting.Computation] is defined: expected single bean but found 0:
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:271)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101)
    at fr.aaa.accounting.Computation.main(Computation.java:302)

Why can't the JVM find that bean ?

A: Change this line:
 ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml);

to this:
  ("classpath:applicationContext.xml)  // without the star

When using the start you are basically creating an empty application context when the file could not be found.


text:
Q: Same SQL Query Working in Management Studio but Not Working From Visual Studio I have a SQL query which creates a database and declares the path of an mdf and its log files. The same query works when I execute it in management studio (I am sure it's the same query I copy paste it from SQL Profiler) but gives a syntax error below:

incorrect syntax near go.

I have tried using executeNonQuery, ExecuteReader and ExecuteScalar to execute my query but nothing worked. It was giving syntax error due to the lack of newlines in query from my code hence the newline methods in the query. Any help would be appreciated.
Visual Studio code:
 string truvamdf = @"C:\Truva\Data\"+VeritabaniAdiTextBox.Text+".mdf";
                string truvaldf = @"C:\Truva\Data\"+VeritabaniAdiTextBox.Text+"_log.ldf";
                string connectionString = (@"" + File.ReadAllText(@"C:\Truva\Ivdexcel\IVDVeritabaniconfig.ini") + "");
                string cmdtext = "" +
                    "USE[master] " + Environment.NewLine + "" +
                    "GO  " + Environment.NewLine + "" +
                    "DECLARE @mdfPath NVARCHAR(max), @ldfPath NVARCHAR(max) , @SQL NVARCHAR(MAX), @instName NVARCHAR(max) = '" + VeritabaniAdiTextBox.Text + "' " + Environment.NewLine + "" +
                    "SELECT @mdfPath = '" + truvamdf + "' " + Environment.NewLine + " " +
                    ",@ldfPath = '" + truvaldf + "'  " + Environment.NewLine + " " +
                    "FROM master.sys.master_files WHERE database_id = 1 " + Environment.NewLine + "" +
                    "SELECT @SQL = " + Environment.NewLine + "" +
                    "'CREATE DATABASE ["+VeritabaniAdiTextBox.Text+ "] " + Environment.NewLine + " " +
                    "CONTAINMENT = NONE " + Environment.NewLine + " " +
                    "ON PRIMARY " + Environment.NewLine + "" +
                    "(NAME = N'''+@instName+''', FILENAME = N'''+@mdfPath+''' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) " + Environment.NewLine + " " +
                    " LOG ON " + Environment.NewLine + " " +
                    " (NAME = N'''+@instName+'_log'', FILENAME = N'''+@ldfPath+''' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10 %)'  "+Environment.NewLine+ " " + Environment.NewLine + "" +

                    "EXECUTE(@SQL) " + Environment.NewLine + " " + Environment.NewLine + "" +
                    " GO ";
               // try
               // {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {

                        connection.Open();
                        SqlCommand cmd = new SqlCommand(cmdtext, connection);
                        cmd.ExecuteNonQuery();

                    }

The same SQL query in SSMS:
 USE[master]
GO
DECLARE @mdfPath NVARCHAR(max), @ldfPath NVARCHAR(max) , @SQL NVARCHAR(MAX), @instName NVARCHAR(max) = 'dddssd'
SELECT @mdfPath = 'C:\Truva\Data\dddssd.mdf'
 ,@ldfPath = 'C:\Truva\Data\dddssd_log.ldf'
 FROM master.sys.master_files WHERE database_id = 1
SELECT @SQL =
'CREATE DATABASE [dddssd]
 CONTAINMENT = NONE
 ON PRIMARY
(NAME = N'''+@instName+''', FILENAME = N'''+@mdfPath+''' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
  LOG ON
  (NAME = N'''+@instName+'_log'', FILENAME = N'''+@ldfPath+''' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10 %)'

EXECUTE(@SQL)

GO

A: I just deleted the GO statements from the query and it works now!!


text:
Q: fn keys for brightness not working on an hp 6735s I use ubuntu 11.10 on hp 6735s, fn keys work for sound adjustment, but for brightness %98 of the times not working, I mean till now only maybe three or four times it worked.
always I must set the brightness from boot time (and if I need any adjustment I must reboot and reset)
and this is screenshot for system settings --> screen , it does not contain brightness slider(this change recently happened before there was a slider).
(I couldnt upload it here because I'm new user level 1)

A: I've been having a similar problem and I have looked in a few places but try this...

*

*Open a terminal (Program - Accessories - Terminal)

*Type in sudo gedit /etc/default/grub

*Find the line that says: GRUB_CMDLINE_LINUX="quiet splash"

*Edit it so it says: GRUB_CMDLINE_LINUX="quiet splash acpi_backlight=vendor"

*Save and exit

*Run the command sudo update-grub

*Reboot and enjoy!

And if that doesn't work, instead of restarting try shutting down completely for 10 seconds and then starting up again. And I also tried the same thing and it worked for a while but then when I removed this piece of the line acpi_backlight=vendor and shutdown and turned on my laptop again the brightness buttons worked again.

A: recently, i had the same problem. Here is the link with the solution that worked on my laptop
http://algodecodigo.blogspot.mx/2012/07/problema-al-cambiar-brillo-en-pantalla.html
best regards :)

A: Questions, to clarify the Problem:

*

*Did you have this particular problem with "fn+brightness" from the very beginning, since you installed Ubuntu or just recently and do you use a second partition (Windows) in which this problem does not occur?!

*Also it would be interesting to know, if the other keys (F1, F2, F3 or arrow key) you use in combination with Fn works fine all the time.

Edit 01: Eventually it is a good idea to see, if you used this key-combination twice, for a different task, which might be conflicting fn+brightness), also a hardware related issue, like a stuck button, or bad contact can now be excluded.
At this point it is a good idea, to file a bug report, after we established that it is only this particular key-combination in Ubuntu, and in your other OS there is no problem at all!
Also take a look at System Settings -> Screen, where you can change/adjust the brightness manually. System Settings comes with the installed OS, see screenshot.
Edit 02: You also could install sudo apt-get install gnome-shell, which allows you, to boot into Ubuntu Unity, as you do right now, but also Unity 2d, Gnome-Shell, Gnome-Shell-Classic etc.., to see if the problem is solved there, or at least if the system settings are working properly. (Referring to your other comment, that "System Settings -> Screen" is missing the brightness-slider).
I am glad, that it worked out for you in the end, even if it is not clear to both of us why! I also deleted all my other comments beneath your question, as we agreed on it and put them in this answer!


text:
Q: How to bind combo box with dataset in WPF I want to bind the combo with dataset and take the value from combo as parameter to populate
another combo in WPF

A: This should get you started. The Window_Loaded event sets up a DataTable with a couple of rows, and sets the DataContext and DisplayMemberPath of a ComboBox. The Countries_SelectionChanged event grabs the SelectedItem (if there is any) and resets the Cities.ItemsSource property to be the result of a method call, which returns an IEnumerable<string>. This call can be whatever you want (database call, file operation, etc.). Hope this helps!
<UniformGrid Rows="2" Columns="2">
    <Label Content="Countries" VerticalAlignment="Center"/>
    <ComboBox Name="Countries" VerticalAlignment="Center" SelectionChanged="Countries_SelectionChanged" ItemsSource="{Binding}"/>
    <Label Content="Cities" VerticalAlignment="Center"/>
    <ComboBox Name="Cities" VerticalAlignment="Center"/>
</UniformGrid>

private void Window_Loaded(object sender, RoutedEventArgs e) {
    DataTable dt = new DataTable();
    dt.Columns.Add("Country", typeof(string));

    DataRow firstRow = dt.NewRow();
    DataRow secondRow = dt.NewRow();
    firstRow["Country"] = "USA";
    secondRow["Country"] = "Italy";
    dt.Rows.Add(firstRow);
    dt.Rows.Add(secondRow);

    Countries.DisplayMemberPath = "Country";
    Countries.DataContext = dt;
}

private void Countries_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    DataRowView dr = Countries.SelectedItem as DataRowView;
    if (dr != null) {
        Cities.ItemsSource = null;
        Cities.ItemsSource = GetCities(dr["Country"].ToString());
    }
}

private IEnumerable<string> GetCities(string country) {
    if (country == "USA")
        return new []{ "New York", "Chicago", "Los Angeles", "Dallas", "Denver" };
    if (country == "Italy")
        return new[] { "Rome", "Venice", "Florence", "Pompeii", "Naples" };
    return new[] { "" };
}


text:
Q: How to loop through a script with SLURM? (sbatch and srun) New to slurm, I have a script that was written to run the same command many times that has multiple inputs and outputs. If i have another shell script, is there a way that I can loop through that in multiple srun commands. My thought you would be something along the lines of:
shell script:
#!/bin/bash
ExCommand -f input1a -b input2a -c input3a -o outputa
ExCommand -f input1b -b input2b -c input3b -o outputb
ExCommand -f input1c -b input2c -c input3c -o outputc
ExCommand -f input1d -b input2d -c input3d -o outputd
ExCommand -f input1e -b input2e -c input3e -o outpute

sbatch script
#!/bin/bash
## Job Name
#SBATCH --job-name=collectAlignmentMetrics
## Allocation Definition
## Resources
## Nodes
#SBATCH --nodes=1
## Time limir
#SBATCH --time=4:00:00
## Memory per node
#SBATCH --mem=64G
## Specify the working directory for this job

for line in shellscript
do
    srun command
done

Any ideas?

A: Try replace your for loop with this:
while read -r line;
do
    if [[ $line == \#* ]]; continue ; fi
    srun $line
done < shellscript


text:
Q: WCF client does not include XML declaration in HTTP POST message This post regards the last hurdle in completing my task of communicating with a Cisco router via the Web Services Management Agent (WSMA), as described here and here. You will not have to read those posts to understand my current question, though.
The problem is this: I have build service and message contracts to match the router's web services, and configured a basicHttpBinding and an endpoint. And using a channel factory, I am now almost, but not quite, communicating successfully with the router.
I keep getting a SOAP fault in return, stating that "An expected XML tag or sequence is missing". Using WCF tracing, fiddler and debugging on the router, and manually posting messages over HTTP, I have finally figured out what's going on.
The WSMA agent on the router expects the SOAP message payload in the HTTP request to include an XML declaration. And WCF isn't sending one. As simple as that.
So my question is: How can I make WCF, using a basicHttpBinding, include an XML declaration in the message?
For reference, my binding configuration looks like this:
<basicHttpBinding>
  <binding name="BasicHttpBinding_IWsmaService" messageEncoding="Text" textEncoding="UTF-8" allowCookies="false">
    <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Basic" proxyCredentialType="None" realm="level_15" />
    </security>
  </binding>
</basicHttpBinding>

(in case you wonder - yes, I am aware that I'm sending clear-text credentials over an unencrypted transport)

A: You will have to create custom encoder. Check WCF samples. Provided sample shows how to create new encoder with composition of existing one. You will use TextMessageEncodingBindingElement to create inner MessageEncoder. Your WriteMessage implementatoin will write XML declaration and than call inner encoder to write serialized message.
You will also need to wrap your new encoder in custom binding element and use it in custom binding together with HttpTransportBindingElement.


text:
Q: CPU Intel Core i7-4790 PCI support I am planning to buy Intel Core i7-4790 and use it in combination with Asus Z97-AR motherboard. The motherboard has 2 PCI slots, will these be still working with the CPU?
The specs on Intel web site have details on the PCIe ports for the CPU, but PCI is not mentioned at all, which left me worried.
I have an old Creative X-FI PCI sound card, which I really love and don't want to lose the ability to use it.

A: What your motherboard uses is a "PCIe-PCI-bridge". Think of it as the high-performance version of a USB-Parallel printer adapter. It talks the newer language on one side, translating it to the older language on the other.
Many PCIe cards carry one of those on board. They consist of a PCI-based chip and a bridge to wire them to the new bus.
Long story short: It works reliably, and for whatever device finds enough bandwidth in a PCI slot, it won't have a problem.


text:
Q: $||f_n-f||_1 \to 0 $ iff $ \int| f_n|\ to \int|f| $ if $f_n \to f $ a.e. Assume $f_n , f \in L^1 $ and almost every where we have $ f_n \to f$ then I want to show that $\int|f_n-f| \to 0$ iff $\int|f_n| \to \int|f|$
One side is abvious by trinagle inequality , for the other side I think I must use a theorem like Dominated covergence theorem but I can not reach a conclusion. Is there a modiffied form of dominated covergence theorem.
I need some hint , thanks.


text:
Q: Why do I get same result from two difference?
Volume

        Choose Convert :

        <input type=radio name=volConvert id="LitToGal" value="LitToGal" checked>Litre To Gallon

        <input type=radio name=volConvert id="GalToLit" value="GalToLit">Gallon To Litre

            Input a data:

            <input name="volData" id="inVolData" type="text" size="10">

            <input type=button value="Convert" onClick="VolConvert()" />

var value = parseFloat(0);
var conValue = parseFloat(0);
function VolConvert() {
if (document.getElementById("LitToGal")) {

    var inputData = parseFloat(document.getElementById("inVolData").value);
    value = (inputData * 16.52);

} else if (document.getElementById("GalToLit")) {

    var inputData = parseFloat(document.getElementById("inVolData").value);
    value = (inputData * 113.50);
}

var conValue = value.toFixed(2);;

resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;

}

A: You need to compare the "checked" value
function VolConvert() {

if (document.getElementById("LitToGal").checked) {

    var inputData = parseFloat(document.getElementById("inVolData").value);
    value = (inputData * 16.52);

} else if (document.getElementById("GalToLit").checked) {

    var inputData = parseFloat(document.getElementById("inVolData").value);
    value = (inputData * 113.50);
}

var conValue = value.toFixed(2);;

resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;
}

A: In your code you have the following If-Statement:
if (document.getElementById("LitToGal")) {
    ...
else if (document.getElementById("GalToLit")) {
    ...
}

This document.getElementById("LitToGal") will always be true since the element exists in your HTML .
Meaning value = (inputData * 16.52); will always be the result.
To fix the statement, try the following:
if (document.getElementById("LitToGal").checked) {
    ...
else if (document.getElementById("GalToLit").checked) {
    ...
}

A: if(document.getElementById("LitToGal").checked)
if (document.getElementById("GalToLit").checked)


text:
Q: how to open a connection to an existing .sql file not using sql toolbox? I would like to try to use visual studio as an SQL(lite3) editor. I discovered the SQL server compact & SQLite Toolbox, but have a problem finding an easy enough tutorial. I would like to connect to an already existing .sql file any suggestions on how to make this as easy as possible?

A: You cannot coonect to a .sql file, this is a text file with sql commands. But use the root menu in the toolbox to connect to an existing or new sqlite database.


text:
Q: Using React.js and Vue.js Together in Laravel I really want to know, is it possible to using react.js and vue.js next to each other in a laravel? For Example, use ReactJs for admin dashboard and use VueJs for client dashboard. I know it's technically and logically better to use one of them.
What do you think? Can we use them together?

A: Yes. It is definitely possible. Polyglot programming is today's reality. There are a couple of approaches you can take. A most common approach would be that of a micro-frontends.
How you implement micro-frontend is up to you! But in general, you will have two different SPA served on two different routes. You will interlink these two applications using hyperlinks/anchor tags. However, note that, doing something that is a big cost and really meant for very large applications and teams building them.
There are many leaf components like buttons, links, dropdown, etc. which you will end up developing and maintaining for both frameworks. State management, routing, services will be rewritten for each framework. It is incredibly painful to match consistent style guide across frameworks.
Nowadays, if you really need to go ahead with this approach, you can consider using custom-elements for your leaf components. They should work for many SPA frameworks (see the notes). This will help you save the trouble of reinventing the wheel.

Note: React is not very friendly with web-components. It fails on many advanced tests.


text:
Q: Set Logic Question Let $U$ be a universe set. Use an element argument to prove the following statement:
For all sets $A$, $B$ and $C$ in $P(U)$, if $A - C ⊆ B - C$ then $ \cup   ⊆ \cup .$

A: If $x\in A\cup C$,
then $x\in C$,
or $x\in A-C$, in which case $x\in B-C$, in which case $x\in B$.
In either case, $x\in B\cup C$.


text:
Q: Trimble MAPS API zooming is affecting the entire web page Using the Trimble MAPS JavaScript API, the key down events for zooming (+/-) are affecting all the fields on the web page.
It there a way to unregister the map keypress event or focus it only on the map window and not the entire document?

A: Implementing the following JavaScript snippet into your code  will prevent zooming in/out on "+"/"-" key press :
for (var c in map.controls){
      if(map.controls[c].CLASS_NAME == "ALKMaps.Control.KeyboardDefaults"){
        map.controls[c].deactivate();
      }
 }

https://developer.trimblemaps.com/ has more details.


text:
Q: How to redirect after the file upload completes? I am using this form and wanted to redirect only when the file uploads completes .
       <form name="sentMessage" id="quote" enctype="multipart/form-data">

            <input type="text" name="name" class="form-control"
                   id="name" required
                       data-validation-required-message="Please enter your name" />
                          Name

            <input type="email" class="form-control" id="email" name="email" required
                       data-validation-required-message="Please enter your email" />
                          Email

            <input type="text" name="subject" class="form-control"
                   id="subject" required
                       data-validation-required-message="Please enter Subject" />
                          Subject

               <select class = "browser-default form-control extra" aria-required="true" name="selectType" required aria-invalid="false" required >
                 <option value = "" enable selected>Select Service</option>
                  <option value = "1">L</option>
                  <option value = "2">V</option>
                  <option value = "3">D</option>
               </select>

                 <textarea name="message" rows="10" cols="100" required class="form-control materialize-textarea"
                       idation-required-message="Please enter your message" minlength="5"
                       data-validation-minlength-message="Min 5 characters"
                        maxlength="999" style="resize:none"></textarea>
                            Message

  Attachment:<INPUT TYPE="file" NAME="image" MAXLENGTH=50 ALLOW="text/*" ></INPUT>

<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Your Message has been sent successfully, You will hear from us within 24 hours.

        <button type="submit" class="btn btn-primary waves-effect waves-dark pull-right">Send</button>

          </form>

and this is the script I am using which executes after onlick submit button.

but the issue is when I upload the file , and click on submit button it redirects to the url without submitting the form data with attachment . I want that once the upload is completed and a success message is shown then it need to be redirected not before that.

A: Additionally to what Michael said:

e.preventDefault();

This is preventing the form from being submitted and the subsequent line is triggering the redirect.
You need to manually send the data to the backend and once it has been sent, execute the redirect.


text:
Q: Sum of 1.5-powers of natural numbers I recently have met the following approximate equation:
$$\sum_{k=1}^n k^{1.5}\approx\frac{n^{2.5}+(n+1)^{2.5}}{5}.$$
It's a rather accurate approximation (for $n=40$ the absolute error is $\approx 1.67$ and it increases very slowly), and looks elegant, so I immediately tried to prove it by expanding the right-hand side using binomial expansion. What I got was
$$\frac25n^{2.5}+\frac12n^{1.5}+\frac{15}8n^{0.5}+\dots,$$
nothing particularly resemblant to the left-hand side. After that I went to googling for something about sums of powers of natural numbers, found Faulhaber's formula
$$\sum_{k=1}^n k^p = \frac{1}{p+1}\sum_{j=0}^p (-1)^j \genfrac{(}{)}{0}{}{p+1}{j}B_j n^{p+1-j},$$
and after (mis)using it with $p=1.5$ I obtained $$\frac25n^{2.5}+\frac12n^{1.5}.$$
While this last result is a more accurate approximation for $\sum_{k=1}^n k^{1.5}$, and is a partial sum for the expansion of the original right-hand side, I still can't understand how the original approximation was obtained. Can someone suggest its source, how one could have conceived of it?

A: We have the inequalities
$$\int_0^nx^{3/2}dx<\sum_{k=1}^n k^{3/2}<\int_0^{n+1}x^{3/2}dx$$
whereupon carrying out the integrals yields
$$\frac25 n^{5/2}<\sum_{k=1}^n k^{3/2}<\frac25 (n+1)^{5/2}$$
The approximation of interest is simply the average of the upper and lower limits of the sum and is expressed as
$$\bbox[5px,border:2px solid #C0A000]{\sum_{k=1}^n k^{3/2}\approx \frac{n^{5/2}+(n+1)^{5/2}}{5}}$$
A much better approximation is found using the Euler-Maclaurin Formula and is
$$\bbox[5px,border:2px solid #C0A000]{\sum_{k=1}^n k^{3/2}=\frac25n^{5/2}+\frac12 n^{3/2}+\frac18n^{1/2}+C+\frac{1}{1920}n^{-3/2}+O(n^{-7/2})}$$
where the constant $C$ can be found numerically and is approximately given by $C\approx -0.025496493$.

A: $${n^{2.5}+(n+1)^{2.5}\over5}={n^{2.5}\over5}\left(1+\left(1+{1\over n}\right)^{2.5} \right)$$
and
$$\left(1+{1\over n}\right)^{2.5}\approx1+{2.5\over n}$$
so
$${n^{2.5}+(n+1)^{2.5}\over5}\approx{n^{2.5}\over5}\left(2+{2.5\over n}\right)={2\over5}n^{2.5}+{1\over2}n^{1.5}$$


text:
Q: turn off off fliers in sns.boxplot I'd like to hide the fliers in sns.boxplot(), but I can't figure out how to do it. I've looked on here and there is not a solution that I can get working.
Is there any way to do this?

A: If you don't want to display them, you could do:
seaborn.boxplot(showfliers=False)

I hope it helps.


text:
Q: Find a specific SVN commit by comment and/or author We're 5 people on our project and sometimes we would want to find a specific commit on SVN, like a bug resolution.
Of course we don't know the revision number of the researched commit.
Does someone have an idea to find a commit by comment ?
I think it's possible by parsing svn logs and using regex but I hope there is a better way.

A: If you're running on a Windows environment you can use Tortoise SVN to search among commit comments, exploiting the Revision Log Dialog.

Search log messages... Search log messages for the text you enter. This searches the log messages that you entered and also the action
  summaries created by Subversion (shown in the bottom pane). The search
  is not case sensitive.

If you're running on a Linux environment you can use alternatives like RabbitVCS, which works almost in the same way.

A: If you prefer the cli, use log --search (see doc)
svn log --search your_comment_fragment


text:
Q: Using a average to get probability of a single occurance in a range of numbers So this is a interesting statistic related question.
What I have

*

*Average

*Range of possible occurrences

What I'm after

*

*The probability of a single occurrence in my range happening

A example would be a average of 10.3 . range of 1-20. Whats the chance 4 occurs? I need to use 10.3 as a sort of weight because if not each occurrence has a 1/20 chance of happening
Is there a statistical formula for something like this?
Coding
public void ReboundFormula(double TeamRebound, double OTeamRebound, double OffensiveRebound, double DefensiveRebound,
        double ShotsTotalAverage, double OShotsTotalAverage, double TeamShotAveragePercent, double OTeamShotAveragePercent,
        double PlayerORebound, double PlayerDRebound, double PlayerOPercentRebound, double PlayerDPercentRebound)
{
    //Possible rebounds using amount of shots that "miss" which result in a rebound chance. Note fouls, ball going out of bounds
    //, or other event that causes a rebound to not occur on a missed shot

    predictedPossibleRebounds = (ShotsTotalAverage*(1 -(double) TeamShotAveragePercent/100)) + OShotsTotalAverage*(1 - (double) TeamShotAveragePercent/100);

    Temp = (double) TeamRebound/(TeamRebound+OTeamRebound);

    Temp2 = (double) OTeamRebound/(TeamRebound+OTeamRebound);

    System.out.println("Percent of Team 1 Rebounds: " + Temp + " | Percent of Team 2 Rebound: " + Temp2);

    System.out.println();

    //Predicted rebounds a team will grab of the amount of rebounds they will likely get
    predictedTeamRebound = (double) predictedPossibleRebounds*Temp;

    predictedOTeamRebound = (double) predictedPossibleRebounds*Temp2;

    System.out.println("Amount of Rebounds to Team: " + predictedTeamRebound + " | Amount of Rebounds to OTeam: " + predictedOTeamRebound);
    System.out.println();

    //Rebounds predicted to be grabbed by teams
    Oratio = ((double) OffensiveRebound/TeamRebound)*predictedTeamRebound;
    Dratio = ((double) DefensiveRebound/TeamRebound)*predictedTeamRebound;

    System.out.println("Amount of Offensive Rebounds: " + Oratio + " | Amount of Defensive Rebounds: " + Dratio);
    System.out.println();

    System.out.println("Predicted Rebounds: " + predictedPossibleRebounds + " | Player Offensive Percent: " + PlayerOPercentRebound + " | Player Defensive Percent: " + PlayerDPercentRebound);

    //Player data time
    Temp = (Oratio*(PlayerOPercentRebound/100)) + (Dratio*(PlayerDPercentRebound/100));

    System.out.println();
    System.out.println("Player Predicted Rebound Total: " + Temp + " | Player Rebound Total Average: " + (PlayerORebound+PlayerDRebound) );
    System.out.println();

    System.out.println( "  " + (int) Math.round((Temp) - (Temp*0.75)) + "     " + (int) Math.round((Temp) - (Temp*0.5)) + "     " + (int) Math.round((Temp) - (Temp*0.25)) + "     " + (int) Math.round((Temp) - (Temp*0.1)) + "    " + (Temp)
            + "  " + (int) Math.round((Temp) + (Temp*0.1)) + "    " + (int) Math.round((Temp) + (Temp*0.25)) + "     " +  (int) Math.round((Temp) + (Temp*0.5)) + "     " + (int) Math.round((Temp) + (Temp*0.75)));
    System.out.println("-75%  -50%  -25%  -10%   Predicted Average  +10%  +25%   +50%   +75%");
    System.out.println();

Feeding data
run.ReboundFormula(54, 48.2, 13.662, 40.338, 89.86, 87.06, 45.2, 45.7, 3.7, 6.2, 12.9, 22.8);

A: You would need to specify the distribution of outcomes. Merely to specify the average and range does not suffice. For example, an unbalanced die with a 1/12 chance of reading 1 and a 3/12 chance of reading 5, other outcomes having equal probability, averages 3.83. However, other unbalanced dice are also possible with the same average, for example a die with a 1/12 chance of reading 2 and a 3/12 chance of reading 6.
I suspect that what you want is a binomial distribution. The binomial distribution results from a finite number of discrete trials (as your program's rebounds), each of which either succeeds or fails, each trial of equal weight.
If you follow the link, you will see many formulas, probably more than you wanted, but a principle underlies the formulas and the principle is what you mainly want to grasp. That won't be so easy, but once you have grasped the principle the chief formulas will naturally follow.


text:
Q: Unused argument error when creating a Tibble table I am working with this data:
library("RCurl")
library("plm")
library("tibble")
library("dplyr")
library("car")
library("AER")
library("arm")
library("broom")

x <- getURL("https://raw.githubusercontent.com/dothemathonthatone/maps/master/main_merge1.csv")
maindf <- read.csv(text = x)

I am trying to do something very simple:
data <- maindf %>% as_tibble() %>% select(reg_schl, year, age_group, fee_monthly, daily_hours, fee_per_inc, deubthrt_total) %>% print()

I get the following errror:
Error in select(., reg_schl, year, age_group, fee_monthly, daily_hours, : unused arguments (reg_schl, year, age_group, fee_monthly, daily_hours, fee_per_inc, deubthrt_total)
Traceback:

1. maindf %>% as_tibble() %>% select(reg_schl, year, age_group,
 .     fee_monthly, daily_hours, fee_per_inc, deubthrt_total) %>%
 .     print()
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. function_list[[i]](value)

So I tried the same code using R data:
data(Fatalities, package = "AER")
road <- Fatalities %>%
as_tibble() %>%
select(state, year, beertax, fatal, pop) %>%
print()

and I got the same error.

A: When you load library(ARM) you should see the following message:

Loading required package: MASS
Attaching package: 'MASS'
The following object is masked from 'package:dplyr':
select

This means that when you call select you're using MASS::select and not dplyr::select
Instead you could be explicit and run:
maindf %>% as_tibble() %>%
  dplyr::select(reg_schl, year, age_group, fee_monthly, daily_hours,
                fee_per_inc, deubthrt_total)

clashes between MASS::select and dplyr::select are very common. You can also redefine select to use dplyr::select using: select <- dplyr::select to save some typing.


text:
Q: Get one value from javascript array I'm sure there's something stupid I am doing and the answer to this is very simple but all the searches I have done have dealt with looping over the array, I don't want that.
I have an ajax call that is returning a response in the form of a very simple array.  In the success function of my ajax call if I do this:
console.log(response);

The array is logged to the console as expected.  [0] => 100, [1] => 200 etc.
If I try:
console.log(response[1]);

I am expecting to get 200 but it does nothing.  I eventually want to insert the value into a redirect like this...
window.location.replace('index.php?id=200');

But all I get is "index.php?id="
Please someone put me out of my misery. What am I doing wrong?
Edit:
Changed the PHP to include the following:
exit(json_encode("id"=>$id,"message"=>$message));

which returned an object (not a string).
Then in the success part of the ajax function:
success: function(response) {
window.location.replace('index.php?id=' + response.id + '&message=' + response.message);
}

This... for some reason, works fine. Don't ask me why.

A: The easiest way of sending information to and from PHP/Javascript is with JSON.
In PHP you can use json_encode() to turn your array into a JSON string. Then use JSON.parse() in Javascript to turn the string back into an object.
If you are using jQuery for the AJAX request and don't have the dataType set it will automagically detect it is JSON and parse it for you, this is probably why you didn't have to.


text:
Q: how to make list comprehension using while in loop I have such loop:
ex = [{u'white': []},
 {u'yellow': [u'9241.jpg', []]},
  {u'red': [u'241.jpg', []]},
   {u'blue': [u'59241.jpg', []]}]

for i in ex:
    while not len(i.values()[0]):
        break
    else:
        print i
        break

I need always to return first dict with lenght of values what is higher then 0
but i want to make it with list comprehension

A: A list comprehension would produce a whole list, while you want just one item.
Use a generator expression instead, and have the next() function iterate to the first value:
next((i for i in ex if i.values()[0]), None)

I've given next() a default to return as well; if there is no matching dictionary, None is returned instead.
Demo:
>>> ex = [{u'white': []},
...  {u'yellow': [u'9241.jpg', []]},
...   {u'red': [u'241.jpg', []]},
...    {u'blue': [u'59241.jpg', []]}]
>>> next((i for i in ex if i.values()[0]), None)
{u'yellow': [u'9241.jpg', []]}

You should, however, rethink your data structure. Dictionaries with just one key-value pair suggest to me you wanted a different type instead; tuples perhaps:
ex = [
    (u'white', []),
    (u'yellow', [u'9241.jpg', []]),
    (u'red', [u'241.jpg', []]),
    (u'blue', [u'59241.jpg', []]),
]


text:
Q: how to align left UIImage in objective c - (void)viewDidLoad
{
   [super viewDidLoad];
   [self setTitle:@"myTitle"];
   UIImageView *titleLabel = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.PNG"]];
   titleLabel.frame = CGRectMake(0, 0, 120, 40);
   self.navigationItem.titleView = titleLabel;
}

A: UIImageView *titleLabel = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nature.jpeg"]];
titleLabel.frame = CGRectMake(0, 0, 120, 40);
titleLabel.contentMode = UIViewContentModeRight;
self.navigationItem.titleView = titleLabel;

A: I think the best is to use UIImageView contentMode property.
You can use like this:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
imageView.contentMode = UIViewContentModeLeft;

It should be ok.


text:
Q: Is it possible to put test files under pages directory in Next.js? I'm writing integration tests for the API routes in a Next.js application and I'm wondering if there is any problem with putting the index.test.ts file under the /pages directory. I'd prefer the test to be as close to the file as possible rather than having to map the project structure inside __test__ directory.
./pages/api/path/index.ts
handler.get(async (req: NextApiRequest, res: NextApiResponse) => {
  ...
});

export default  handler;

./pages/api/path/index.test.ts
import { testClient } from "__test__/utils/testClient";

describe("Testing API  POST: /api", () => {
  test("Should return 401 when not authenticated", async () => {
    const request = testClient({ handler });
    const res = await request.post("/api/applications");
    expect(res.status).toEqual(401);
  });
});

A: TL;DR: While not possible by default, you can co-locate test files inside the pages folder by customising the pageExtensions option in next.config.js.

By default, Next.js will take into account any file ending with tsx, ts, jsx or js under the pages folder for the purpose of building pages/API routes and routing.
From the Custom Page Extensions documentation:

Next.js assumes every tsx/ts/jsx/js file in the pages directory is a
page or API route, and may expose unintended routes vulnerable to
denial of service attacks, or throw an error like the following when
building the production bundle

Adding a file named index.test.ts in the pages folder (or any subfolder) will include that file as an actual page, and potentially throw errors during build time.
You can circumvent this by modifying the extensions Next.js expects using the pageExtensions property in next.config.js.
module.exports = {
    // Default value is ['tsx', 'ts', 'jsx', 'js']
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}

With this configuration, only pages with the above extensions will be taken into account. So you could have the following pages folder structure, with co-located test files.
pages/
├─ api/
│   ├─ path.page.ts
│   └─ path.test.ts
├─ _app.page.ts
├─ _document.page.ts
├─ index.page.ts
└─ index.test.ts

Both path.test.ts and index.test.ts would be ignored.


text:
Q: Facebook SDK Unity Invite I'm developping an android  game in witch  I connect to facebook . If the user is connected  , he can invite 5 of his facebook to the application.  I used this code. The problem that in the script InteractiveConsole.cs  I want when  the user click on button of invite  , he can invite only 5 of his friends, when he choose 5 friends ,  he can't invite more than 5.
Here is my code:
#region FB.AppRequest() Friend Selector

public string FriendSelectorTitle = "";
public string FriendSelectorMessage = "Derp";
public string FriendSelectorFilters = "[\"all\",\"app_users\",\"app_non_users\"]";
public string FriendSelectorData = "{}";
public string FriendSelectorExcludeIds = "";
public string FriendSelectorMax = "";

private void CallAppRequestAsFriendSelector()
{
    // If there's a Max Recipients specified, include it
    int? maxRecipients = null;
    if (FriendSelectorMax != "")
    {
        try
        {
            maxRecipients = Int32.Parse(FriendSelectorMax);
        }
        catch (Exception e)
        {
            status = e.Message;
        }
    }

    // include the exclude ids
    string[] excludeIds = (FriendSelectorExcludeIds == "") ? null : FriendSelectorExcludeIds.Split(',');

    FB.AppRequest(
        FriendSelectorMessage,
        null,
        FriendSelectorFilters,
        excludeIds,
        maxRecipients,
        FriendSelectorData,
        FriendSelectorTitle,
        Callback
    );
}
#endregion

Thanks for your help.

A: I Found out why it's not working.
First to limit the numbers of friends invited to 5 in my application , i should change this:
public string FriendSelectorMax = "5";

i cheked again the documententation and it say this.
"maxRecipients : Platform-dependent The maximum number of recipients the user should be able to choose in the platform multi-friend selector dialog. Only guaranteed to work in Unity Web Player applications."
Here is the link : https://developers.facebook.com/docs/unity/reference/current/FB.Apprequest
the think is that maxRecipients is working in WebPlayer and not for android until now.
I tested the code in unity web player and i can invite only 5 friends and when i switch the platform to android, it's not working as they said in the documentation.


text:
Q: Microsoft SAPI Sub-language issue My problem is this: My SAPI inproc recognizer refuses to load my grammar file when the windows 10 Display language is set to English(UK).
System Display language set to UK. Speech Recognition language is UK. System Locale is UK. SAPI xml-format Grammar even specifies LANGID=809 - as far as I can tell, EVERYTHING is set to EN-GB, and yet the grammar still won't load.
But it loads and works just fine when display language and is set to English(US).
Does anyone know what's up with this? It's extremely frustrating... Hopefully I'm just missing something simple.
SAPI Initialization code:
    //////////////INITIALIZE SAPI ENGINE AND GRAMMAR//////////////////////////////
HRESULT SpeechObject::Initialize(){
    //INITIALIZE SR ENGINE
    if (FAILED(test=::CoInitialize(NULL)))
        SRError(L"COM Initialization Fail");

    //Create recognizer instance
    if (FAILED(test=cpEngine.CoCreateInstance(CLSID_SpInprocRecognizer))){
        SRError(L"Can't Load Reco Engine");
            return test;
    }

    //Load the audio Input (in seperate function to facilitate reload)
    LoadAudio(); //should I check this?

    //load Default recognizer settings
    cpEngine->SetRecognizer(NULL);

    //get and load default reco profile
    if (FAILED(SpGetDefaultTokenFromCategoryId(SPCAT_RECOPROFILES, &cpObjectToken)))
        SRError(L"Can't Find Recognition Profile");
    if (FAILED(cpEngine->SetRecoProfile(cpObjectToken)))
        SRError(L"Can't Load Recognition Profile");

    //create reco context
    if (FAILED(test=cpEngine->CreateRecoContext(&cpContext))){
        SRError(L"Can't Create Reco Context");
        return test;
    }

    //send pSpeechObject to global callback function
    cpContext->SetNotifyCallbackFunction(
        (SPNOTIFYCALLBACK*)SpeechCallBack,
        NULL, (LPARAM)this);

    if(FAILED(cpContext->CreateGrammar(NULL, &cpGrammar)))
        SRError(L"Can't Create context");

    char str[80]; ////TEST
    sprintf(str, "LANGID: %X", GetUserDefaultUILanguage());
    MessageBoxA(GetActiveWindow(), str,0,0);

    //load grammar from compiled grammar resource
    if (FAILED(test = cpGrammar->LoadCmdFromResource(
        hModule, MAKEINTRESOURCE(GRAMMARCFG),
        L"FILE", GetUserDefaultUILanguage(), SPLO_STATIC))){
        SRError(L"Can't Load Grammar. Please check language settings");
        return test;
    }

    //(comment above and uncomment following to load from raw xml file for testing)
    //cpGrammar->LoadCmdFromFile(L"Grammar.xml", SPLO_STATIC);

    //Enable Engine and Reco Context
    cpEngine->SetRecoState(SPRST_ACTIVE);
    cpContext->SetContextState(SPCS_ENABLED);

    //enable ALWAYS ACTIVE and GROUND ENGINES ON commands
    return(cpGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE));

}

////////////LOAD (AND RELOAD) AUDIO INPUT//////////////////////
HRESULT SpeechObject::LoadAudio(bool dlgFlag){
    if (FAILED(test = SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOIN, &cpAudioIn))){
        SRError(L"Can't Find Default Audio Input");
        return test;
    }

    if (FAILED(test = cpEngine->SetInput(cpAudioIn, TRUE))){
        if (!dlgFlag)
            SRError(L"Can't Set Audio Input");
        return test;
    }

    if (pSRDisplay)
        pSRDisplay->DisplayText("Audio Reloaded");
    if (pDLog)
        pDLog->LogEvent("Audio Reloaded");
    //RecoState must be reenabled after audio reset
    cpEngine->SetRecoState(SPRST_ACTIVE);
    if (pDLog)
        pDLog->LogEvent("SR ENABLED");
    return test;
}

I get the "Can't Load Grammar. Please check language settings" error any time the display language is not English(US), even if I confirm that ALL SETTINGS match...
Would really appreciate any sort of insight from persons more knowledgeable than I.
Farley

A: You need to explicitly load the recognizer for your preferred language. In particular, this:
//load Default recognizer settings
cpEngine->SetRecognizer(NULL);

always loads the recognizer specified in the speech control panel.  You likely want something like this:
CComPtr<ISpObjectToken> cpEngineToken;
hr = SpFindBestToken(SPCAT_RECOGNIZERS, L"Language=<hex language id>", NULL, &cpEngineToken);
// check hr
hr = cpEngine->SetRecognizer(cpEngineToken);

where you'll need to convert the LCID from GetUserDefaultUILanguage to a hex number.

A: The issue was that I had misinterpreted the meaning of the "language" parameter in LoadCmdFromResource(). I'll blame it on the ambiguous SAPI documentation, though if I had experience loading some other types of resources before I might have been tipped off to this. ;) I had thought it was somehow used by SAPI and should match the language of the system and recognizer (that's what it sounded like in the documentation). Turns out, it actually just specifies the language used to compile the .RC file the grammar is included in (presumably to allow multiple translations to be included in separate .rc's).
The code works perfectly as originally posted, so long as I replace "GetUserDefaultUI()" with an explicit "0x409" (the language specified in the resource compiler) in the call to LoadCmdFromResource(). Now it works with US English, UK English and presumably all English recognizers, and loads the recognizer selected in the speech control panel regardless of the Display language setting (which can even be non-English).
Many, many thanks to Eric Brown for tipping me off to this, I was starting to lose my mind.
Farley


text:
Q: How Update table if ... else I want update table, but something goes wrong. How can I update my table if something is TRUE or NOT. For example if it is true I want set value 0, if not increase +1. Here my code:
$fp = @fsockopen($host, $port, $errno, $errstr, 30);
            if ($fp) {
                print "
$idt	$nameOK	$quantity
\n";
            } else {
             print "
$idt	$nameError	$quantity
\n";
                }

if ($conn->query($fp) == TRUE) {
    $resetsql = "UPDATE addresses SET count=0";
} else {
   $updatesql = "UPDATE addresses SET count=count+1";
}

A: You seem to be looking for CASE:
UPDATE addresses SET cnt = CASE WHEN :param = 1 THEN 0 ELSE cnt + 1 END

If :param is 1, then 0 will be assigned to cnt. Else, cnt is incremented.
In MysQL this can shortened as:
UPDATE addresses SET cnt = CASE WHEN :param THEN 0 ELSE cnt + 1 END


text:
Q: Why can't i check Formik checkboxes? I'm trying to create a simple Formik form. First time working with checkboxes. I can render the checkboxes, but am unable to check any of them. What's the problem?
export default function App() {

 var lights = [{id:1, name:"a"}, {id:2, name:"a"}]
  return (

Select Lights

    <Formik
        initialValues={{
            checked: [],
        }}
        onSubmit={(eve) => this.submit(eve)}
    >
        {({values}) => (
            <form>

Checked

                    {lights.map((light) =>

                                <Field type="checkbox" key={light.id} name="checked" value={light.id}/>
                                {light.name}

                    )}

                <button type="submit" onClick={(event => this.submit(event))}>Submit</button>
            </form>
        )}
    </Formik>

)
}

A: Checkbox value being a number seems to be the problem. Because you initialise it as a number but internally it's converted to a string when formik is tracking the checkbox value. Change
<Field type="checkbox" key={light.id} name="checked" value={light.id}/>

to:
<Field type="checkbox" key={light.id} name="checked" value={light.id.toString()}/>


text:
Q: More examples for the event profiler in pyalgotrade I'm trying to learn how to implement custom strategies into the event profiler for pyalgotrade. This is the default example they give.
from pyalgotrade           import eventprofiler
from pyalgotrade.technical import stats
from pyalgotrade.technical import roc
from pyalgotrade.technical import ma
from pyalgotrade.tools     import yahoofinance

#     Event inspired on an example from Ernie Chan's book:
#    'Algorithmic Trading: Winning Strategies and Their Rationale'

class BuyOnGap(eventprofiler.Predicate):
    def __init__(self, feed):
        stdDevPeriod = 90
        smaPeriod = 20
        self.__returns = {}
        self.__stdDev = {}
        self.__ma = {}
        for instrument in feed.getRegisteredInstruments():
            priceDS = feed[instrument].getAdjCloseDataSeries()
            #      Returns over the adjusted close values.
            self.__returns[instrument] = roc.RateOfChange(priceDS, 1)
            #      StdDev over those returns.
            self.__stdDev[instrument] = stats.StdDev(self.__returns[instrument], stdDevPeriod)
            #      MA over the adjusted close values.
            self.__ma[instrument] = ma.SMA(priceDS, smaPeriod)

    def __gappedDown(self, instrument, bards):
        ret = False
        if self.__stdDev[instrument][-1] != None:
            prevBar = bards[-2]
            currBar = bards[-1]
            low2OpenRet = (currBar.getAdjOpen() - prevBar.getAdjLow()) / float(prevBar.getAdjLow())
            if low2OpenRet < (self.__returns[instrument][-1] - self.__stdDev[instrument][-1]):
                ret = True
        return ret

    def __aboveSMA(self, instrument, bards):
        ret = False
        if self.__ma[instrument][-1] != None and bards[-1].getAdjOpen() > self.__ma[instrument][-1]:
            ret = True
        return ret

    def eventOccurred(self, instrument, bards):
        ret = False
        if self.__gappedDown(instrument, bards) and self.__aboveSMA(instrument, bards):
            ret = True
        return ret

def main(plot):
    instruments = ["AA", "AES", "AIG"]
    feed = yahoofinance.build_feed(instruments, 2008, 2009, ".")

    predicate = BuyOnGap(feed)
    eventProfiler = eventprofiler.Profiler(predicate, 5, 5)
    eventProfiler.run(feed, True)

    results = eventProfiler.getResults()
    print "%d events found" % (results.getEventCount())
    if plot:
        eventprofiler.plot(results)

if __name__ == "__main__":
    main(True)

Does any one have a source of some more examples ?
I'm trying to figure out how the eventprofiler takes in and uses data, there's quite a few class methods that are called though and I'm finding it a little tricky to dissect it.
I want to start off simple and just use price and volume. It is, one strategy would beif volume > 1000 and close < 50: event == True
Any help would be appreciated.
P.s.: bonus question: is there a similar event profiler for zipline ?
EDIT: Thanks to user3666197 I was able to make the changes I wanted to however i'm getting this error:
Traceback (most recent call last):
  File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 43, in <module>
    main(True)
  File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 35, in main
    eventProfiler.run(feed, True)
  File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 215, in run
    disp.run()
  File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 102, in run
    eof, eventsDispatched = self.__dispatch()
  File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 90, in __dispatch
    if self.__dispatchSubject(subject, smallestDateTime):
  File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 68, in __dispatchSubject
    ret = subject.dispatch() is True
  File "C:\Python27\lib\site-packages\pyalgotrade\feed\__init__.py", line 105, in dispatch
    self.__event.emit(dateTime, values)
  File "C:\Python27\lib\site-packages\pyalgotrade\observer.py", line 59, in emit
    handler(*args, **kwargs)
  File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 172, in __onBars
    eventOccurred = self.__predicate.eventOccurred(instrument, self.__feed[instrument])
  File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 89, in eventOccurred
    raise NotImplementedError()
NotImplementedError
[Finished in 1.9s]

I've had a look at the source 'eventprofiler.py' and can't figure out what it is. Here's the code
from pyalgotrade import eventprofiler
from pyalgotrade.technical import stats
from pyalgotrade.technical import roc
from pyalgotrade.technical import ma
from pyalgotrade.barfeed import csvfeed

# Event inspired on an example from Ernie Chan's book:
# 'Algorithmic Trading: Winning Strategies and Their Rationale'

class single_event_strat( eventprofiler.Predicate ):
    def __init__(self,feed):
        self.__returns = {} # CLASS ATTR
        for inst in feed.getRegisteredInstruments():

            priceDS = feed[inst].getAdjCloseDataSeries() # STORE: priceDS ( a temporary representation )

            self.__returns[inst] = roc.RateOfChange( priceDS, 1 )
            # CALC:  ATTR <- Returns over the adjusted close values, consumed priceDS
            #( could be expressed as self.__returns[inst] = roc.RateOfChange( ( feed[inst].getAdjCloseDataSeries() ), 1 ),
            #but would be less readable

    def eventOccoured( self, instrument, aBarDS):
        if (aBarDS[-1].getVolume() > 1000 and aBarDS[-1].getClose() > 50 ):
            return True
        else:
            return False

def main(plot):
    feed = csvfeed.GenericBarFeed(0)

    feed.addBarsFromCSV('FCT', "FCT_daily_converted.csv")

    predicate = single_event_strat(feed)
    eventProfiler = eventprofiler.Profiler(predicate, 5, 5)
    eventProfiler.run(feed, True)

    results = eventProfiler.getResults()
    print "%d events found" % (results.getEventCount())
    if plot:
        eventprofiler.plot(results)

if __name__ == "__main__":
    main(True)

A: Quant Prologue:

Many thanks to prof. Tucker BALCH, GA-TECH [GA], and his team, for QSTK-initiative and the innovative approaches to Quantitative Finance Modelling.

How the eventprofiler takes in data?

Simply, it receives access to the full feed both in eventprofiler.run( feed , ... ) and also as an eventprofiler.Predicate-wrapped feed, where it gets the all feed-details' access right into the .Predicate instance by a Class-parameter, so as to be able to calculate there implemented all details the strategy calculus requires. Smart, isn't it?
The rest is done by a re-use of their class-methods.

How to build one's own?
It is quite enough to declare an appropriately equipped eventprofiler.Predicate, that will be injected into the evenprofiler instantiation:
class DavidsSTRATEGY( eventprofiler.Predicate ):
      def __init__( self, feed ):                         # mandatory .__init__
          """                                               no need for this code
                                                            left here for didactic
                                                            purposes only
                                                            to show the principle

          self.__returns = {}                                         # CLASS ATTR

          for                inst in feed.getRegisteredInstruments():
              priceDS = feed[inst].getAdjCloseDataSeries()            # STORE: priceDS ( a temporary representation )
              self.__returns[inst] = roc.RateOfChange( priceDS, 1 )   # CALC:  ATTR <- Returns over the adjusted close values, consumed priceDS ( could be expressed as self.__returns[inst] = roc.RateOfChange( ( feed[inst].getAdjCloseDataSeries() ), 1 ), but would be less readable
          """

      def eventOccurred( self, instrument, aBarDS ):       # mandatory .eventOccured
          if (   aBarDS[-1].getVolume() > 1000             # "last" Bar's Volume >
             and aBarDS[-1].getClose()  <   50             # "last" Bar's Close  <
             ):
                 return True
          else:
                 return False

The rest would be as simple as always:
eventProfiler = eventprofiler.Profiler( predicate = DavidsSTRATEGY( feed ), 5, 5 )
eventProfiler.run( feed, True )

Quant Epilogue:
A carefull reader has noted, that the proposed code does not call .getAdjClose() method. The reasoning is, that deep-backtesting may get skewed by the very Close adjustments, on making decisions in times, when adjustments are not yet known. It is a fair duty of every professional Quantitative Analyst to avoid any means of peeking into the future and carefully decide, where adjustments are needed, with respect to portfolio valuation, if an instrument holding time has exprienced an adjustment, within it's respective lifecycle, or not.

A: Bonus answer
While the motivation of the question is clear, there are a few reasons, why the answer is not so straightforward, as it might look.
First, how the things work:
The eventprofiler in QSTK and pyalgotrade is built on top of the DataSeries representation of the Market, where external data is input (not stored) via a feed-mechanism.
The zipline approach is different and states, the core functionality is focused on its event-based simulation engine, which operates on the level of an atomic role of each price-QUOTE-tick (asynchronous external-event arrival and local responsive-processing).
The sequential nature of the stream-of-events processing has some attractivity for emulated in-vitro backtesting.
The strengths of QSTK-originated eventprofiler are on the contrary based on processing the full-length DataSeries-representations at once (or some smart iterator re-verbated or efficient numpy stride-tricks&magics).
This vast conceptual difference makes it hard to get a similarly smart + fast + efficient + easy-to-re-use tool, as the QSTK eventprofiler out of question is, in an event-processing environment.


text: Q: what would be the best way to migrate a DB from RDS to Bigquery I'm currently trying to migrate a PostgresDB on RDS to BigQuery through HEVO ETL but i'm having troubles with SSH. The connection get lost all the time. i want to know if exist a better way to make the migration.


text:
Q: Unused parameter only greyed out but not reported I use VS Code and the unused parameters of functions are only greyed out, but never reported.
How to report those greyed out warning in the problem explorer?
currently, thanks to the parameter reportUnusedVariable in pyright, we can report unused variables, but we cannot report unused parameters.
Thanks

A: If you're using Pylance or Pyright, seems like you can't mark unused parameters as errors. They're not always errors - sometimes you need them to conform to some interface.
If you want to prohibit unused parameters anyway, there are other tools such as the flake8-unused-arguments plugin for flake8.


text:
Q: using a conditional type in a .cpp file I have a templated class and a type that depends on the template. How can I use this type in my .cpp file?
object.hpp:
using pair_d = std::pair<double, double>;
using pair_f = std::pair<float, float>;

template <typename T>
class Object {
    public:
        static_assert(std::is_same<T, float>::value ||
                      std::is_same<T, double>::value, "Type not allowed");

        using pair = typename std::conditional<std::is_same<T, float>::value,
                     pair_f, pair_d>::type;

        // function using the conditional type
        const pair doSomething(T, T) const;
}

object.cpp
#include "object.hpp"

template <typename T>
const pair Object<T>::doSomething(T t1, T t2) const {
    // ....
}

But the I get:

error: unknown type name 'pair'

How can I use the type 'pair' in my .cpp file?

A: You'll need to qualify the name if you use it before the Object<T> part.
template <typename T>
typename Object<T>::pair Object<T>::doSomething(T t, T t) const {
    // ....
}

A: There are four issues in your snippet:

*

*The arguments are named with the same name (T t, T t), make those names different.

*You have split the template declaration/definition into a cpp and a header file, don't do that.

*You forgot about a const qualifier on a return type in the definition (which is in the declaration).

*You are missing a typename keyword for a dependent name.
Your definition should be:
template <typename T>
const typename Object<T>::pair Object<T>::doSomething(T t1, T t2) const {
    // stuff
}

or (to avoid a dependent name):
template <typename T>
auto Object<T>::doSomething(T t1, T t2) const -> const pair {
    // stuff
}

A: Why do you need this?
using pair = typename std::conditional<std::is_same<T, float>::value,
                     pair_f, pair_d>::type;

Why not just:
typedef std::pair<T,T> pair;

Unless you need two template type arguments. Even if you need two type arguments, use them directly.
I didn't say don't use static_assert!


text:
Q: Can ejabberd be installed on Google Compute Engine? Can ejabberd be installed on Google Compute Engine?  Will there be any issues with using ejabberd on Compute Engine?  I have looked but cannot find any references to anyone trying this before.  Grateful for any help.

A: Yes. Compute Engine gives you VMs. You can put whatever you want on them, such as Erlang and ejabberd.

A: Yes you can.
You can use the Vm with Debian Image and follow this intructions.
http://www.howtoforge.com/virtual-mail-jabber-server-xmpp-with-iredmail-and-ejabberd-on-ubuntu-9.10
dont forget open the ports in the firewall.

A: Sorry I didn't have much time to put together a cleaner "how to". I just copied and pasted from my personal archive.
Here's what you'd have to do to compile the source code on a Compute Engine. Please let me know if you have any questions.
Image: debian-7-wheezy-v20140408
sudo apt-get update
sudo apt-get install build-essential
sudo apt-get install libncurses5-dev
sudo apt-get install openssl libssl-dev
sudo apt-get install libexpat1-dev
sudo apt-get install unixodbc-dev
wget http://pyyaml.org/download/libyaml/yaml-0.1.5.tar.gz
tar tar -xvzf yaml-0.1.5.tar.gz
cd yaml-0.1.5
./configure
sudo make
sudo make install
sudo apt-get install xsltproc
sudo apt-get install fop
cd ..
wget http://www.erlang.org/download/otp_src_R16B03-1.tar.gz
gunzip -c otp_src_R16B03-1.tar.gz | tar -xf -
cd o....
./configure --with-odbc=/usr/lib/odbc
sudo make
sudo make install

[.. Install git and clone repo here.. ]
git clone git@github.com:processone/ejabberd.git

cd ejabberd
./configure --enable-odbc --enable-mysql
sudo make
sudo make install


text:
Q: Users Characteristics I'm really battling an issue where I have a Users table that has a growing number of user characteristics (regligion, smoking preferences, etc). The strategy I've used thus far has been to add a column for each preference that keys off onto another table.
For example, if User XYZ has a RelgionId of 3, that could mean they're Christian. At runtime, if I need their religion, I join onto another table.
This strategy has worked so far. However, I'm getting concerned about the number of columns in the tables as the number of preferences is increasing. Also, this strategy leads to many joins if I need to get all values for a single user.
I'd like to find out the most normalized way of representing this data. Anybody have any ideas?

A: You can do this sort of thing by creating what are essentially property bags of these values.   This is not an approach that I am a huge fan of, but as with everything in SQL Server it has its place and your scenario might well be that case.
This is essentially the EAV approach, and Aaron Bertrand has a great writeup on this here to describe the pros and cons in more detail
CREATE TABLE Users
(
    UserID int identity(1, 1) primary key clustered
    ,UserName varchar(200)
);

CREATE TABLE PreferenceType
(
    PreferenceTypeID int identity(1, 1) primary key clustered
    ,PreferenceName varchar(200)
);

CREATE TABLE PreferenceValue
(
    PreferenceValueID int identity(1, 1) primary key clustered
    ,PreferenceValueName varchar(200)
    ,PreferenceTypeID int
);

CREATE TABLE UserPreference
(
    UserPreferenceID int identity(1, 1) primary key clustered
    ,UserID int
    ,PreferenceValueID int
);

ALTER TABLE PreferenceValue
ADD CONSTRAINT  FKValue_Type FOREIGN KEY (PreferenceTypeID) REFERENCES PreferenceType(PreferenceTypeID);

ALTER TABLE UserPreference
ADD CONSTRAINT  FK_UserPreference_User FOREIGN KEY (UserID) REFERENCES Users(UserID);

ALTER TABLE UserPreference
ADD CONSTRAINT  FK_UserPreference_Value FOREIGN KEY (PreferenceValueID) REFERENCES PreferenceValue(PreferenceValueID);

insert into Users (UserName)
Values ('User1' ) --tblUserID = 1
, ('User2' );   --tblUserID = 2

Insert into PreferenceType  (PreferenceName)
Values ('Religion') --Type1
, ('Smoker'); --Type 2

Insert into PreferenceValue (PreferenceValueName, PreferenceTypeID)
Values ('Christian', 1) --Value 1
, ('Muslim', 1) --Value 2
, ('Non Smoker', 2)  --Value 3
, ('Smoker' , 2); -- Value 4

--User 1 is a Christian Smoker
--User 2 is a Muslim Non-Smoker
Insert into UserPreference (UserID, PreferenceValueID)
Values (1, 1)
, (1, 4)
, (2, 2)
, (2, 3);

Visually:

So that when you want to get the information for User 1 you would run this select:
select u.UserID, u.UserName, pv.PreferenceValueName, pt.PreferenceName
From Users u
join UserPreference up on u.UserID = up.UserID
join PreferenceValue pv on up.PreferenceValueID = pv.PreferenceValueID
join PreferenceType pt on pv.PreferenceTypeID = pt.PreferenceTypeID
Where u.UserName = 'User1';

You would get the following results in the format of
UserID, UserName, PreferenceValue, PreferenceType
1, User1, Christian, Religion
1, User1, Smoker, Smoker
To include Date values within a schema similar to this, playing off of the tables that were already created but adding two new ones, you could do something like the following:
CREATE TABLE DateType
(
    DateTypeID int identity(1, 1) primary key clustered
    ,DateTypeName varchar(200)
);

CREATE TABLE UserDateType
(
    UserDateTypeID int identity(1, 1) primary key clustered
    ,UserID int
    ,DateTypeID int
    ,DateValue datetime
);

CREATE UNIQUE NONCLUSTERED INDEX
    uq_UserDateType on UserDateType (UserID, DateTypeID);  --Optional. To only allow one row per type.

ALTER TABLE UserDateType
ADD CONSTRAINT  FKDateType FOREIGN KEY (DateTypeID) REFERENCES DateType(DateTypeID);

ALTER TABLE UserDateType
ADD CONSTRAINT  FKUserDate_UserID FOREIGN KEY (UserID) REFERENCES Users(UserID);

Insert into DateType (DateTypeName)
Values ('BirthDate') --Type1
, ('Anniversary'); --Type 2

Insert into UserDateType (UserID, DateTypeID, DateValue)
Values (1, 1, '01/01/1980') --User 1 has a Birthday of 01/01/1980
, (1, 2, '01/01/2000')  --User 1 has an Anniversary of 01/01/2000
, (2, 1, '02/01/1995');  --User 2 has an Birthday of 01/01/2000

By having these kinds of tables you can dynamically add the new date types and relate them to a user in this way.
As mentioned above, I am not sure that this is the ideal approach, as it certainly has its flaws, but this is a way that you can do this sort of thing with Date values.

A: Normalization is a great concept and essential for well performing relational database.  However it can become counter productive.  For example you almost never see addresses broken up like this:
StateRegionTable    CityTable        ZipTable
   StateId             CityId           ZipId
   StateDesc           CityDesc         ZipDesc

AddressTable
   AddressId
   Address1
   Address2
   CityId
   StateId
   ZipId

It's just not all that useful and slows things down with extra joins.  In your case I would recommend removing extra tables where the table only has an Id/Description pair.
So instead of having a ReligionTable and a SmokingTable and a GenderTable etc just have description columns with CHECK constraints.  That does mean that if you want to add an extra value to the list you will have to modify the check constraint but with these types of tables it shouldn't happen all of that often.  Where you do NOT want to do this is when your lookup table requires extra information.  For example if your SmokingTable had an "Additional Insurance Cost" column or something like that then you want a separate lookup table.
Your table would look something like this:
CREATE TABLE #Users (
    UserId INT,
    Religion VARCHAR(50) CONSTRAINT ck_Users_Religion CHECK (Religion IN ('Christian','Jew','Budist')),
    SmokingPreference CHAR(3) CONSTRAINT ck_Users_Smoking CHECK (SmokingPreference IN ('YES','NO'))
    )