Q:

mongoose can't store double types?

I am trying to store double BSON type inside mongodb. I am using mongoose. I have tried every possible way but still it's stored as int.
I have tried @mongoosejs/double and mongoose-float but none of them work.
await Variant.insertOne(

    {
          price: 345,
          discount: 10,
     },
)

product model
import { Schema } from "mongoose"
const Double = require("@mongoosejs/double")

// const Float = require("mongoose-float").loadType(mongoose)
export const ProductVariantEmbeddedSchema = new Schema({
  price: Double,
  discount: Double,
})

here is a custom type that I have created by the help of @mongoosejs/double.
import mongoose from "mongoose"

export default function mongooseDouble(mongoose) {
  class DoubleType extends Number {
    constructor(v) {
      super(v)
      this.value = v
    }

    toBSON() {
      return this.value
    }
  }

  class Double extends mongoose.SchemaType {
    constructor(key, options) {
      super(key, options, "Double")

      Object.assign(this.$conditionalHandlers, {
        $lt: (val) => this.castForQuery(val),
        $lte: (val) => this.castForQuery(val),
        $gt: (val) => this.castForQuery(val),
        $gte: (val) => this.castForQuery(val),
      })
    }

    cast(val) {
      if (val == null) {
        return val
      }

      const _val = Number(val)
      if (isNaN(_val)) {
        throw new mongoose.SchemaType.CastError(
          "Double",
          val + " is not a valid double"
        )
      }
      return new DoubleType(_val)
    }
  }

  mongoose.Schema.Types.Double = Double
  mongoose.Types.Double = DoubleType

  return mongoose
}

// export default Double

A:

ok it seems that if mongoose custom types not worked I can use raw mongodb queries.
import mongoose, {mongo} from 'mongoose'

const result = await mongoose.connection.collection('Variant').insertMany([{price: new mongo.Double(34)}, {price: new mongo.Double(45)}])

const storedValues = result.opt


Q:

Regex for matching different URL

I am trying to write a regex for a URL match and it's not working.
The subject URL is...
var subject = "http://encore.lsbu.ac.uk/iii/encore/search/C%257CSab%257COrightresult%257CU1?lang=eng&suite=pearl";

The regex is...
var regex = /http:\/\/encore.lsbu.ac.uk\/iii\/encore\/search\/C%257CS[a-z][A-Z][0-9]%257COrightresult%257CU1?lang=eng&suite=pearl/i;

And I am using JavaScript to test it.
var answer = regex.test(subject);
// answer is false

The goal is to match any URL with the regex which has keyword changed in the middle of the string but whole string matches the URL. In other words, both string should be matched except the part of keyword shouldn't be checked. Am I doing anything wrong?

A:

Here is the fixed regex:
/http:\/\/encore\.lsbu\.ac\.uk\/iii\/encore\/search\/C%257CS[a-z0-9]*%257COrightresult%257CU1\?lang=eng&suite=pearl/i
I made the following changes to it:

Escaped the dots in the URL with a backslash.
Changed [a-z][A-Z][0-9] to [a-z0-9]* to match any of those characters repeated zero or more times.

You can also use + instead of * to match the characters once or more, or {2} to match them exactly twice (this is the case in your example string, but may not be in all cases).

Escaped the question mark in the URL with a backslash.

Edit: Removed the A-Z since it isn't needed (the regex is case insensitive).


Q:

Python - JSON to CSV converter explanation

I am doing a data analysis project and I need to convert the files from JSON to CSV. I have discovered this code but as I have not studied Python yet I'm unsure what to do. I'm not sure where I put the file directory or the column names.
If someone would be able to explain where I do this I'd appreciate it!
import argparse
import collections
import csv
import simplejson as json

def read_and_write_file(json_file_path, csv_file_path, column_names):
    """Read in the json dataset file and write it out to a csv file,given the column names."""
    with open(csv_file_path, 'wb+') as fout:
    csv_file = csv.writer(fout)
    csv_file.writerow(list(column_names))
    with open(json_file_path) as fin:
        for line in fin:
            line_contents = json.loads(line)
            csv_file.writerow(get_row(line_contents, column_names))

 def get_superset_of_column_names_from_file(json_file_path):
"""Read in the json dataset file and return the superset of column  names."""
column_names = set()
with open(json_file_path) as fin:
    for line in fin:
        line_contents = json.loads(line)
        column_names.update(
                set(get_column_names(line_contents).keys())
                )
return column_names

 def get_column_names(line_contents, parent_key=''):
"""Return a list of flattened key names given a dict.
Example:
    line_contents = {
        'a': {
            'b': 2,
            'c': 3,
            },
    }
    will return: ['a.b', 'a.c']
These will be the column names for the eventual csv file.
"""
column_names = []
for k, v in line_contents.iteritems():
    column_name = "{0}.{1}".format(parent_key, k) if parent_key else k
    if isinstance(v, collections.MutableMapping):
        column_names.extend(
                get_column_names(v, column_name).items()
                )
    else:
        column_names.append((column_name, v))
return dict(column_names)

def get_nested_value(d, key):
"""Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`.

Example:
    d = {
        'a': {
            'b': 2,
            'c': 3,
            },
    }
    key = 'a.b'
    will return: 2

"""
if '.' not in key:
    if key not in d:
        return None
    return d[key]
base_key, sub_key = key.split('.', 1)
if base_key not in d:
    return None
sub_dict = d[base_key]
return get_nested_value(sub_dict, sub_key)

def get_row(line_contents, column_names):
"""Return a csv compatible row given column names and a dict."""
row = []
for column_name in column_names:
    line_value = get_nested_value(
                    line_contents,
                    column_name,
                    )
    if isinstance(line_value, unicode):
        row.append('{0}'.format(line_value.encode('utf-8')))
    elif line_value is not None:
        row.append('{0}'.format(line_value))
    else:
        row.append('')
return row

if __name__ == '__main__':
"""Convert a yelp dataset file from json to csv."""

parser = argparse.ArgumentParser(
        description='Convert Yelp Dataset Challenge data from JSON format to CSV.',
        )

parser.add_argument(
        'json_file',
        type=str,
        help='The json file to convert.',
        )

args = parser.parse_args()

json_file = args.json_file
csv_file = '{0}.csv'.format(json_file.split('.json')[0])

column_names = get_superset_of_column_names_from_file(json_file)
read_and_write_file(json_file, csv_file, column_names)

A:

As far as I can see, the json file is one of the arguments when you run the script and the column names are mapped from the json file.
So it should work if you run this script like this:
python script.py json_file.json


Q:

better way store friends and retrieve friends of a particular user

Which of these mysql storage methods would be faster to query (to retrieve friends of a particular user say @anyid):
Table: Friends

Columns: friend1 friend2

insert only one row per friendship and query as
select friend1
from FRIENDS
where friend2=@anyid
UNION ALL
select friend2
from FRIENDS
where friend1=@anyid

OR
insert two rows per friendship (insert as friend1 friend2 and then insert swapped entries eg, 1,2 and 2,1) and then simply query as
select friend2 from FRIENDS where friend1=@anyid

to me it seems the second method will perform better since it requires indexing on only a single column friend1 and a single query. The first method may require both columns to be indexed and requires running two sub queries. But in some posts i see people claiming the first method may perform better.
On the plus side the first method will take half the storage when compared to the second method, would that make a huge difference for say million records.
Also one other thing, is it required to even store a seperate relationship_id and creation_date for any of the two methods above. what could be the exceptional benefit i would get other than giving me the relationship creation time or sequence, i think most people should be able to live without it or not?
Thanks for any answers!

A:

To me, the fundamental question is:  "How many friendships are in the database?"  If only A and B are friends, is the number "1" or "2".  This answer dictates how you understand the friendship entity and hence how it should be implemented.
There is definitely a difference in the two approaches.  To count the number of friends in the first way:
select count(*)
from friends
where USERID in (friend1, friend2);

versus:
select count(*)
from friends
where USERID = friend1;

The second can more easily take advantage of an index on friend1 and can be optimized to be faster than the first.
On the other hand, inserting a record takes twice as long.  And finding friends of friends (and so on) requires handling more data and hence more processing time.
The friendship relationship does have additional characteristics, such as who initiated the request (this would often be friend1 in the first approach).  Or the times the friendship was requested and accepted. Such additional information suggests the first approach to eliminate the duplication of data.
In other words, the question about the data structure -- as with almost all such questions -- is answered by how you understand the entities and how they are going to be used.


Q:

How to select first element in array in Polymer

<user-avatar mode="plain" name="[[item.from]]"></user-avatar>

item.from is Array. I want to select first element of item.name array
<user-avatar mode="plain" name="[[item.from[0].name]]"></user-avatar>

instead of using filter function. How can I do that? Thanks

A:

You can directly add the index to the path (docs).
<user-avatar mode="plain" name="[[item.from.0.name]]"></user-avatar>


Q:

Converting a string constant to char

I have a class named Player but when building a constructor like the one below, I got a warning that read: ISO C++ forbids converting a string constant to 'char'. Can anyone tell me what this means and how I can fix it?
class Player
{
public:
    Player(char * firstN = "", char * lastN = "");
};

A:

ISO C++ forbids converting a string constant to 'char'

I doubt the compiler said that. It probably said "ISO C++ forbids conversion from string constant to char*" instead. There is a difference.

Can anyone tell me what this means

It means that you're trying to initialise a pointer to char using a string constant. As the error message explains, this is something that cannot be done because a string constant is not implicitly convertible to such type.

how I can fix it?

You can change the argument type to be const char*. A string constant implicitly converts to that type.


Q:

Is there any evidence that a specific type of writing is more beneficial than others for learning?

Have there been any studies done on if certain types of writing (fiction, personal/diary type, scientific, etc.) benefit a second language learner more than others? To be clear, this would be the learner themselves writing, and not reading someone else's.
I added the reference-request tag as I'm primarily looking for research, but in the case that none comes up, informative answers that don't cite studies are also welcome.

A:

Creative writing as an important tool in second language acquisition and practice:

However, creative writing,
in particular poetry, provides a means of combining meaning-focused
and form-focused tasks. With the exception of free formverse, poetry
involves paying attention to meter, form, repetition and shape. Holmes
and Moulton (2001) have shown how the use of pattern poetry allows
students to perform tasks that, by having a prescribed format, allow
for meaningful, authentic use of teacher-specifed forms. The students
are given a stable vehicle through which they can express themselves.
Through poetry, creative writing can also help with pronunciation.

The paper focuses mostly on poetry, but I'd say the benefits of creative writing far outweigh the benefits of nonfiction writing, which tends to deal with fairly simple grammar and sentence structure, albeit complex vocabulary.


Q:

Unable to post array in JSON to WebAPI method

This is my method:
[HttpPut("*myUri}")]
    public Task<IActionResult> DoSomething(string myString, [FromBody]string[] myIDs)
{
// DO stuff
}

I am sending the following JSON in the body of my request:
{
   "myIDs": ["1","2","3"]
}

Why is myIDs null when the API gets called?

A:

Your controller is expecting a string array, but you're sending an object that looks like
{
    myIDs: ["1", "2", "3"]
}

Try posting just JSON.stringify(["1", "2", "3"]), and sure you're sending the Content-Type as application/json


Q:

Can I get a virus by using "sudo apt-get install"?

I would like to make sure it's safe to download software using sudo apt-get install. Are the packages scanned somewhere? Are all packages downloaded using this command virus free?
If there is no guarantee that they are not virus free, after installing a package that contains virus, would the attacker be fully able to control my machine? Is there any way I can check all the packages that were installed on my computer by me? (not by the system automatically. I would like to filter them to see all the packages that were installed by me manually, not by the system.)

A:

apt on a default Ubuntu system will be very unlikely to get viruses. However, it doesn't mean it isn't possible:

Malicious PPA
One of the features of APT is the ability for admins to add Personal Package Archives (PPAs) or other software sources to the APT cache. These third-party APT sources are not necessarily trusted, and may carry viruses. However, it would take an intentional action of the machine's admin to add one of these infected sources, making it rather hard for one to add itself.
Hacked Repository
In theory, a software repository may be hacked by a malicious party, causing downloaded .deb files to potentially carry malicious payloads. However, official software repositories are very carefully watched and security for these repositories is pretty tight. A hacker would be hard-pressed to take down one of the official Ubuntu software sources, but third-party software sources (see above) may be compromised a lot easier.
Active MITM/Network Attacks
If a network is compromised higher up (by, say, your ISP), it is possible to get a virus from official software sources. However, an attack of this caliber would require an extreme amount of effort and the ability to Man-In-The-Middle many sites, including GPG key distribution servers and the official repos.
Poorly Written/Malicious Code
Vulnerabilities do exist in open source, peer-reviewed, and maintained code. While these things aren't technically considered "viruses" by definition, certain exploits hidden or never revealed in the code could allow a malicious attacker to place a virus on or pwn your system. One example of this type of issue would be Heartbleed from OpenSSL, or the much-more-recent Dirty CoW. Note that programs from the universe or multiverse repos are potential threats of this caliber, as explained here.

apt (due to its importance on Linux systems) is pretty heavily guarded against almost all of these types of attacks on both the client and server side. While they are possible, an admin who knows what they're doing and knows how to read error logs will be able to prevent any of these attacks from taking place.
Additionally, apt also enforces signature verification to ensure that the files downloaded are legitimate (and are downloaded correctly), making it even harder to sneak malware through apt, as these digital signatures cannot be faked.

As for responding to a malware infection incident, the absolute easiest path is to burn the system to the ground and start again from a recent (and known-clean) backup. Due to the nature of Linux, it can be very easy for malware to manifest itself so deep in the system that it can never be found or extracted. However, packages like clamav and rkhunter can be used to scan a system for infections.

A:

apt-get will only install from the official Ubuntu repositories which are checked or from repositories you've added to your sources. If you add every repository you come across, you might end up installing something nasty. Don't do that.

A:

Files downloaded by sudo apt-get are compared to a check sum / hash sum for that file to ensure it hasn't been tampered with and is virus free.
Indeed the problems people have encountered when you google "sudo apt get hash sum" is too much security against viruses.
Linux is not completely virus free by any means however incidents are probably 1000 times less than windows.
Then again judging by my screen name I might be biased :)
Comment on November 28, 2017 mentions how Windows has 1,000 more workstations than Linux so why bother hacking Linux. It brings up the fact Linux is running on all 500 of the faster Super-Computers now and most Webservers are running Linux which makes it the best way to hack all the Windows workstations that attach to the internet.
Google Chrome, Android and Windows 10 gives users ample opportunity to give away their privacy and probably some security at the same time.


Q:

Generating Javascript Code with Rails

I'm currently developing a web app which can generate JS code that can attached to another page. Just like email subscription form which generated from the form builder below:

Instead of generating subscription form, I want the JS code to render image or text and I want to put the image or text inputted to the file storage such as AWS instead within my app.
I'm running on Rails 4.2.5.
The above JS code is generating a form, the form must be saved somewhere in the file storage (CMIIW). I want to make an app which can generate that kind of JS code.
P.S. I'm new to Rails, anyone can please explain the process or is there any gem that can help achieve this task. Thank you.

A:

So what you want is a widget.

Public
The underpin of this is that you need a public JS file to "pull" data from your app & show the appropriate HTML on someone else's site.
This file will be included on the other person's site; it will populate HTML elements on the site with data from your server (through an API). It may use an iframe, but more often than not will just decorate an HTML element with assets from your own server.
All of the widgets / badges / buttons you can put on your site are just embedded JS from someone else's. These JS files need to work with public data from your app (IE you cannot use ANY server-side tech with it)...
# public/your_widget.js
// put new element on page
// populate with form data

--
JS
The only way you can make a JS file public is by placing it in your public folder, or at least a publicly-accessible part of your app (subdomain).
You cannot use the asset pipeline for it.
Of course, there are version control mechanisms you can use etc, but the fact is that you need a public "link" other sites can include:

--
HTML
In order to populate a widget on your site, you can look at the various JS adaptations which exist. I've not had massive experience of this; bootstrap's JS implementation would be a good place to start, and Google's analytics JS.
In short, your JS needs to generate HTML & output it on your site.
The standard pattern for this is to include the script on your site, place an HTML "element" (with appropriate id) on your page, to which the JS will populate with HTML (pre-cooked with data from your server):
// site

// JS

--
Data
To populate the data on your site, you'll need to use an API - publicly accessible:
#config/routes.rb
scope constraints: { subdomain: "api" } do
   resources :images, module: :api #-> api.url.com/images/x
end

This would have to be backed up with authentication similar to your app (my API authentication integration is a little hazy):
#app/models/user.rb
class User < ActiveRecord::Base
   has_secure_token #-> native to Rails 5; gem for Rails 4
end

#app/controllers/api/images_controller.rb
class Api::ImagesController
   before_filter :authenticate

   def show
       user  = User.find_by token: request.headers["Auth_Key"]
       image = user.images.find params[:id]
       render json: image.to_json if image
   end

   private

   def authenticate
      if request.headers.include? "Auth_Key"
         render :unprocessable_entity unless User.exists? token: request.headers["Auth_Key"]
      end
   end
end

Ref
The above code is just a general example.
It will allow you to send...
var image_url = $.ajax({
   url:     "http://api.url.com/images/x",
   headers: "Auth-Key": "x"
});

CORS
Finally, the last consideration is CORS - Cross Origin Resource Sharing:

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts & javascript) on a web page to be requested from another domain outside the domain from which the resource originated

In other words, you cannot just let anyone pull your JS files from your server. HTTP won't allow it unless you give them permission with a correct CORS policy.
What you need to do is make your public.js accessible to anyone, along with your API. It might - therefore - be recommended to put both into a subdomain. I can give you more info on this if required.

is there any gem that can help achieve this task

Not that I know of.
This is somewhat advanced functionality. You have to know the underlying authentication pattern for an HTTP web service, and match that with a JS implementation for use on third parties.
In its simplest form, you're making a tiny app ("widget") which pulls API data. You just have to know which parts of your app to allow access to, in order to make the functionality work.


Q:

How can I redirect from an action creator after a fech using the response as a param?

I'm working with an API that returns the id of the last insert. On the other hand, I have an action creator on Redux that makes the fetch post request. How can I take the response from the fetch and redirect based on the response?
In my action creator, I have:
export const newPostRequest = (userid, title, body, history) => {
    return async (dispatch) => {
        await fetch('/posts', {
            method: 'POST',
            headers: {
                'Accept': 'Application/json',
                'Content-Type': 'Application/json'
            },
            body: JSON.stringify({post: {user_id: userid, title: title, body: body}})
        })
        .then(response => response.json())
        // I want to redirect from here to '/posts/:id' where id comes from the response
    }
}

And in my component, I have:
const mapDispatchToProps = dispatch => {
    return {newPost: (user, title, body) => dispatch(newPostRequest(user, title, body)) }
}

[...]

const handleSubmit = async event => {
  event.preventDefault();
  await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
  // I know I should redirect from here, but how can I get the response from the fetch?
}

A:

// I know I should redirect from here, but how can I get the response from the fetch?

You can assign the result of an async function and use it like any other assignment.
const handleSubmit = async event => {
  event.preventDefault();
  const newPostResponse = await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
  redirect(newPostResponse.id); // or whatever you need to do to redirect
}


Q:

Unmanaged to managed interop performance in x86 and x64

In my tests I'm seeing the performance cost of unmanaged to managed interop double when compiling for x64 instead of x86. What is causing this slowdown?
I'm testing release builds not running under the debugger. The loop is 100,000,000 iterations.
In x86 I'm measuring an average of 8ns per interop call, which seems to match what I've seen in other places. Unity's x86 interop is 8.2ns. A Microsoft article and Hans Passant both mention 7ns. 8ns is 28 clock cycles on my machine which seems at least reasonable, though I do wonder if it's possible to go faster.
In x64 I'm measuring an average of 17ns per interop call. I can't find anyone mentioning a difference between x86 and x64, or even mentioning which they are referring to when giving times. Unity's x64 interop clocks in around 5.9ns.
Regular function calls (including into an unmanaged C++ DLL) cost an average of 1.3ns. This doesn't change significantly between x86 and x64.
Below is my minimal C++/CLI code for measuring this, though I'm seeing the same numbers in my actual project that consists of a native C++ project calling into the managed side of a C++/CLI DLL.
#pragma managed
void
ManagedUpdate()
{
}

#pragma unmanaged
#include <wtypes.h>
#include <cstdint>
#include <cwchar>

struct ProfileSample
{
    static uint64_t frequency;
    uint64_t startTick;
    wchar_t* name;
    int count;

    ProfileSample(wchar_t* name_, int count_)
    {
        name = name_;
        count = count_;

        LARGE_INTEGER win32_startTick;
        QueryPerformanceCounter(&win32_startTick);
        startTick = win32_startTick.QuadPart;
    }

    ~ProfileSample()
    {
        LARGE_INTEGER win32_endTick;
        QueryPerformanceCounter(&win32_endTick);
        uint64_t endTick = win32_endTick.QuadPart;

        uint64_t deltaTicks = endTick - startTick;
        double nanoseconds = (double) deltaTicks / (double) frequency * 1000000000.0 / count;

        wchar_t buffer[128];
        swprintf(buffer, _countof(buffer), L"%s - %.4f ns\n", name, nanoseconds);
        OutputDebugStringW(buffer);

        if (!IsDebuggerPresent())
            MessageBoxW(nullptr, buffer, nullptr, 0);
    }
};

uint64_t ProfileSample::frequency = 0;

int CALLBACK
WinMain(HINSTANCE, HINSTANCE, PSTR, INT)
{
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    ProfileSample::frequency = frequency.QuadPart;

    //Warm stuff up
    for ( size_t i = 0; i < 100; i++ )
        ManagedUpdate();

    const int num = 100000000;
    {
        ProfileSample p(L"ManagedUpdate", num);

        for ( size_t i = 0; i < num; i++ )
            ManagedUpdate();
    }

    return 0;
}

1) Why does x64 interop cost 17ns when x86 interop costs 8ns
2) Is 8ns the fastest I can reasonably expect to go?
Edit 1
Additional information
CPU i7-4770k @ 3.5 GHz
Test case is a single C++/CLI project in VS2017.
Default Release configuration
Full optimization /O2
I've randomly played with settings like Favor Size or Speed, Omit Frame Pointers, Enable C++ Exceptions, and Security Check and none appear to change the x86/x64 discrepancy.
Edit 2
I've stepped through the disassembly (not something I'm very familiar with at this point).
In x86 is seem something along the lines of
call    ManagedUpdate
jmp     ptr [__mep@?ManagedUpdate@@$$FYAXXZ]
jmp     _IJWNOADThunkJumpTarget@0

In x64 I see
call    ManagedUpdate
jmp     ptr [__mep@?ManagedUpdate@@$$FYAXXZ]
        //Some jumping around that quickly leads to IJWNOADThunk::MakeCall:
call    IJWNOADThunk::FindThunkTarget
        //MakeCall uses the result from FindThunkTarget to jump into UMThunkStub:

FindThunkTarget is pretty heavy and it looks like most of the time is being spent there. So my working theory is that in x86 the thunk target is known and execution can more or less jump straight to it. But in x64 the thunk target is not known and a search process takes place to find it before being able to jump to it. I wonder why that is?

A:

I have no recollection of ever giving a perf guarantee on code like this.  7 nanoseconds is the kind of perf you can expect on C++ Interop code, managed code calling native code.  This is going the other way around, native code calling managed code, aka "reverse pinvoke".
You are definitely getting the slow flavor of this kind of interop.  The "No AD" in IJWNOADThunk is the nasty little detail as far as I can see.  This code did not get the micro-optimization love that is common in interop stubs.  It is also highly specific to C++/CLI code.  Nasty because it cannot assume anything about the AppDomain in which the managed code needs to run.  In fact, it cannot even assume that the CLR is loaded and initialized.

Is 8ns the fastest I can reasonably expect to go?

Yes.  You are in fact on the very low end with this measurement.  Your hardware is a lot beefier than mine, I'm testing this on a mobile Haswell.  I'm seeing between ~26 and 43 nanosec for x86, between ~40 and 46 nanosec for x64.  So you are getting x3 better times, pretty impressive.  Frankly, a bit too impressive but you are seeing the same code that I do so we must be measuring the same scenario.

Why does x64 interop cost 17ns when x86 interop costs 8ns?

This is not optimal code, the Microsoft programmer was very pessimistic about what corners he could cut.  I have no real insight whether that was warranted, the comments in UMThunkStub.asm don't explain anything about choices.
There is not anything particularly special about reverse pinvoke.  Happens all the time in, say, a GUI program that processes Windows messages.  But that is done very differently, such code uses a delegate.  Which is the way to get ahead and make this faster.  Using Marshal::GetFunctionPointerForDelegate() is the key.  I tried this approach:
using namespace System;
using namespace System::Runtime::InteropServices;

void* GetManagedUpdateFunctionPointer() {
    auto dlg = gcnew Action(&ManagedUpdate);
    auto tobereleased = GCHandle::Alloc(dlg);
    return Marshal::GetFunctionPointerForDelegate(dlg).ToPointer();
}

And used like this in the WinMain() function:
typedef void(__stdcall * testfuncPtr)();
testfuncPtr fptr = (testfuncPtr)GetManagedUpdateFunctionPointer();
//Warm stuff up
for (size_t i = 0; i < 100; i++) fptr();

    //...
    for ( size_t i = 0; i < num; i++ ) fptr();

Which made the x86 version a little faster.  And the x64 version just as fast.
If you are going to use this approach then keep in mind that an instance method as the delegate target is faster than a static method in x64 code, the call stub has less work to do to rearrange the function arguments.  And do beware I took a shortcut on the tobereleased variable, there is a possible memory management detail here and a GCHandle::Free() call might be preferred or necessary in a plug-in scenario.


Q:

How many bits are reserved for Webkit (Google Chrome) timestamps?

I know that Google Chrome uses an integer timestamp, properly called the Webkit timestamp, that is calculated by the number of microseconds since 01/01/1601 00:00:00 UTC. What I'm not sure is whether this is a 64-bit signed integer (which would make the most sense) or a 56-bit integer?
Here's an example timestamp: 12883423549317375. This decodes as Sun, 05 April 2009 16:45:49 UTC. Any good reference out there for how this works? I searched the Webkit website and found no documentation of this timestamp.

A:

Time in Chromium is generally represented internally as an int64. Take a look at base::Time and the various platform-specific implementations for details about how the conversions take place.


Q:

Changin IRC default client on Mavericks

I installed Colloquy and then LimeChat IRC clients. I realized Colloquy opens automatically when clicking on a link like irc://irc.freenode.net/kolab
How can I changed these links to open in LimeChat?

A:

You can set defaults using something like RCDefaultApp (old but free & still functional)
Use the URLS header & set your default app by finding the protocol in the URLs list & selecting the default in the drop menu on the right.


Q:

Which are the ways we can display the content of a collection beyond h:dataTable or rich:dataGrid?

I wish to write the content of a list, but not the "table way".
<h:dataTable value="#{pessoaAction.pessoas}" var="pessoaItem">
    <h:column>
        <h:outputText value="#{pessoaItem.nome}" />
    </h:column>
</h:dataTable>

And
<rich:dataGrid value="#{pessoaAction.pessoas}" var="pessoa" columns="1">
    <h:outputText value="#{pessoa.nome}"></h:outputText>
</rich:dataGrid>

That solutions bring me what I want this way:

Danielson
Melissa
Carlos

But I want to have them this way (inline)

Danielson; Melissa; Carlos.

Some ideas?

A:

You could do it with simple JSF iteration component like this :
<ui:repeat value="#{pessoaAction.pessoas}" var="pessoa" varStatus="status">
    <h:outputText value="#{pessoa}" />
    <h:outputText value="#{status.last ? '.' : '; '}" />
</ui:repeat>


Q:

A star c++, what is wrong

Here it is, I have no idea why it doesnt work. Sometimes its ok, sometimes it crashes and sometimes it returns the wrong way...
//apath.h
#ifndef APATH_H
#define APATH_H
#include <vector>
#include <cmath>
#include <memory>
#include <allegro.h>

using namespace std;

double len(int x1, int y1, int x2, int y2);

class GameMap;

class point
{
public:
      int x,y;
      double f,g;
      point *parent;
      point(int _x=0, int _y=0, point *par=NULL) {x=_x; y=_y; parent=par; f=0; g=0;};
      void countF(int sx, int sy, int tx, int ty)
      {
      g=len(x,y,tx,ty);
      f=g+len(sx,sy,x,y);
      };
};

struct point2d
{
      int x,y;
};

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const point2d directions[]=
{
      {1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1},
};

class path
{
public:
      vector<point2d> way;
      int step;
      bool findPath(int x, int y, int fx, int fy, GameMap& map, BITMAP* out);
private:
      vector<point> open;
      vector<point> closed;
};

#endif

and apath.cpp:
//apath.cpp
#include "apath.h"
#include <vector>
#include <cmath>

double len(int x1, int y1, int x2, int y2)
{
       return (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
       //return max(abs(x1-x2), abs(y1-y2));

      /*int mx=max(x1,x2)-min(x1,x2);
      int my=max(y1,y2)-min(y1,y2);
      return (min(mx,my)*14+max(mx,my)-min(mx,my)*10);*/
};

bool findPoint(vector<point> arr, point pt, point &ret)
{
     for (int i=0; i<arr.size(); i++) if (arr[i].x==pt.x && arr[i].y==pt.y) { ret=arr[i]; return true;}
     return '\0';
};

//GameMap holds the map...
bool path::findPath(int x, int y, int fx, int fy, GameMap& map, BITMAP* out)
{
     while(!open.empty()) open.pop_back();
     while(!closed.empty()) closed.pop_back();
     while(!way.empty()) way.pop_back();

     point start(x,y);
     start.countF(x,y,fx,fy);
     open.push_back(start);

     point finish(fx,fy);

     double min=999999999;
     int index;
     point tmp;
     point *tmp2;
     point comparer;

     while (!findPoint(closed,finish,comparer))
     {
           min=999999999;
           for (int i=0; i<open.size(); i++)
           {
               if(open[i].f<min)
                   {
                       min=open[i].f;
                       index=i;
                   }
           }

           tmp=open[index];
           closed.push_back(open[index]);
           open.erase(open.begin()+index);

           for (int i=0; i<8; i++)
               {
                    tmp2=new point(tmp.x+directions[i].x,tmp.y+directions[i].y);
                    if (map.getCollisionXY(tmp2->x,tmp2->y)==1 // map.getCollision returns 1 when you cant pass through the tile and 0 otherwise...
                    || findPoint(closed,*tmp2,comparer)) continue;
                    if (!findPoint(open,*tmp2,comparer))
                    {
                        point newP(tmp.x+directions[i].x,tmp.y+directions[i].y,&closed[closed.size()-1]);
                        newP.countF(x,y,fx,fy);
                        open.push_back(newP);
                    }
                    else
                    {
                        if (comparer.g>tmp.g)
                        {
                             comparer.parent=&closed[closed.size()-1];
                             comparer.countF(x,y,fx,fy);
                        }
                    }
                    delete tmp2;
               }
/*     for (int i=0; i<open.size(); i++)
        if (open[i].parent!=0)circlefill(out,open[i].x*16+4,open[i].y*16+4,3,0xff0000);
           if (open.empty()) return false;
     for (int i=0; i<closed.size(); i++)
        if (closed[i].parent!=0)circlefill(out,closed[i].x*16+12,closed[i].y*16+12,3,0xffff00);*/ //debug draw

     }
     point2d pt;
     pt.x=finish.x;
     pt.y=finish.y;
     way.push_back(pt);
     point wayer;
     wayer=closed[closed.size()-1];
     while(wayer.parent!=0) //CRASH from here
     {
         wayer=*wayer.parent;
         pt.x=wayer.x;
         pt.y=wayer.y;
         way.push_back(pt);
//         circlefill(out,pt.x*16+12,pt.y*16+12,3,0xffffff); //debug draw
     }    //CRASH to here, i dont exacly know where it is, but when trying to recreate path.
     return true;
};

Some explaination:
GameMap is class with map
and its getCollisionXY returns 1 you cant pass throught tile and 0 otherwise.
Thanx for any help.

A:

One main source I see that could cause access violation is that your points contain parents as pointers and they are members of a vector. If the vector is reallocated these pointers could become invalidated.
Other than that it is hard to immediately see what causes the crash.
You really should run your code through a debugger. I have just pointed out one thing I immediately see.


Q:

How to space out trailing return type of lambda with clang-format

There are a few things blocking me from switching to clang-format.  When I have a trailing return type on a lambda that should wrap to the next line there is no space between the arrow and the trailing return type.  How can I fix this?
For example this is the output from clang-format for the unformatted version of the same code below
auto func() {
    return [.......](auto one, auto long_parameter_list, auto another)
        ->SomeLongReturnType;
//      ^^^^^^^^^^^^^^^^^^^^^ How can I add a space in between those?
}

A:

TL;TR: Upgrade to clang-format 7.0 or later.
The clang-format 7.0 comes with fixes related to the trailing return, so you should be able to achieve the desired formatting:
Before
template <int K, typename E, typename L, int N>
auto ccccccccccccccccccccccc(detail::base<E, L, N>& p) -> std::add_lvalue_reference<E>::type;

After:
template <int K, typename E, typename L, int N>
auto ccccccccccccccccccccccc(detail::base<E, L, N> &p)
    -> std::add_lvalue_reference<E>::type;

Related is a subtle issue that clang-format 7 still suffers from https://bugs.llvm.org/show_bug.cgi?id=42835 and it does not indent the breaking of the trailing return if there is typename used:
Before:
template <int K, typename E, typename L, int N>
auto bbbbbbbbbbbbbbbbbbbbbbb(detail::base<E, L, N>& p) -> typename std::add_lvalue_reference<E>::type;

After:
template <int K, typename E, typename L, int N>
auto bbbbbbbbbbbbbbbbbbbbbbb(detail::base<E, L, N> &p) ->
    typename std::add_lvalue_reference<E>::type;

Related mailing list thread: [cfe-users] [clang-format] Trailing return type


Q:

How do I make .app from Python include image files

I want to make a .app file from my Python source. My Python source is wxPython and has 11 image files (.png , size is 32x32)
Making the .app is a success, but it does not include my image files, it just shows the error message
no bitmap handler for types 50 defined.
Details...
Can't load image from file...
Even in the same directory it is still showing this error message.
I'm using py2app, python 2.7, and wxPython on MacOSX 10.6.7
How can I make a .app with my image files?

A:

The easiest way to include resources is to specify them as data_files in your setup.py
from setuptools import setup

APP = ['app.py']
DATA_FILES = [('', ['images'])]
OPTIONS = {'argv_emulation': True}

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

<app.app>/Contents/Resources will be the current directory and resource root for all data. This will place the images/ directory of your project within the resource root.
If you only wanted to include specific files from your images/ directory you can tell it how to map:
DATA_FILES = [
    ('images', ['images/picture.jpg', 'images/picture2.png']),
    ('images/icons', ['images/icons/ico1.ico'])
]

Or you can get fancier and say "only include all jpegs from my image dir":
from glob import glob
...
DATA_FILES = [
    ('images', glob('images/*.jpg')),
]


Q:

nginx 301'ing limit_req rate limited requests instead of error page

I have a bulk search form on apache servers behind nginx.  I'd like to protect that location so that the second request in a 10 minute period gets 301'd to a "Would you like to use our API" page instead with something like:
http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    server {
       location = /search/bulk {
                limit_req zone=one burst=2;
                 ...  SOME CONFIG HERE...
       }
    }
}

How would I 301 the end client when they hit my limit_req instead of showing a ngnix error page?  Also, secondarily, I don't want to throttle traffic to the whole http clause.  Can I set up a limit_req_zone without a rate, but have them in my location stanzas?
Thanks,
M.

A:

By default, nginx will return a 503 service temporarily unavailable error code.
The limit_req_status directive exists to change the error code in case they hit the limit_req :
location = /search/bulk {
          limit_req zone=one burst=2;
          limit_req_status 404;
}

The problem is that this directive only allows a range from 400 to 599, so you cannot specify a 301 :
[emerg] 3130#0: value must be between 400 and 599 in /etc/nginx/nginx.conf:72

So, if your main issue is to display a custom error message instead of the default 503 one, you could proceed like this :
http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    server {
       location = /search/bulk {
                limit_req zone=one burst=2;
                error_page  503  /503.html;
       }
       location  /503.html {
            internal;
       }
    }
}

Then your custom 503.html file :
Would you like to use our API ?

The rate argument is mandatory. You have to specify a rate for limit_req_zone


Q:

What's the use for an offline version of Delicious?

previous.delicious.com:

This version of the Delicious website will be shutdown by April 2014.
  We encourage users to switch to the new Delicious site at
  http://delicious.com, which features a responsive design for mobile
  and tablet users, offline access, faster loading, and more.

Delicious is mainly a collection of links. What's the use for an offline version of Delicious?

A:

You can bookmark more than just pages that are live on the World Wide Web.

Intranet pages
Email addresses
Local files

I also expect offline access would be useful if you can reach the Web but can't reach Delicious.


Q:

Compare Multiple tags of XML files using Windows Batch

I'm trying to create a Batch file which compares two copies of a single XML file stored at two different locations and checks whether their versions are same or not.
Currently I'm using fc & findstr command to check only the build tag in the 2 files but i want to add the functionality in which the code 1st checks the major tag, if it is different then the code stops executing and prints "files different".
If the values are same then it proceeds to checking the minor tags in the 2 files.if the values are different then the code stops executing and prints "files different". if values are same then it proceeds to checking the build tag.If the build values are different then it prints "Files different" else "files same"..
So the flow of checking tags is  ->  ->
The file stored at 2 different locations is
TData.xml
<?xml version="1.0" encoding="UTF-8"?>
<CDMDataXML xmlns="http://www.avocent.org/trellis/CDMLoaderXMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.avocent.org/trellis/CDMLoaderXMLSchema CDMLoaderXMLSchema.xsd">
<CDMDataVersion>
    <Major>3</Major>
    <Minor>0</Minor>
    <Build>19</Build>
    <Delimiter>.</Delimiter>
</CDMDataVersion>

The batch code I'm using is..
    @echo off
  fc D:\SVN\TData\TData.xml Z:\TDataGDDFolders\TData.xml /A > nul

if errorlevel 1 (
    echo.
    echo in SVN
    findstr "<Build>" D:\SVN\TData\TData.xml
    echo.
    echo  in DropBox
    findstr "<Build>" Z:\TDataGDDFolders\TData.xml
    echo.
    echo.
    echo TData files are different.
) else (
    echo.
    echo in SVN
    findstr "<Build>" D:\SVN\TData\TData.xml
    echo.
    echo  in DropBox
    findstr "<Build>" Z:\TDataGDDFolders\TData.xml
    echo.
    echo.
    echo TData files matches.
)

I'm trying to add the above mentioned functionality in the batch code but can't seem to understand how to do it...Please Help..

A:

Just reuse the code from previous answer
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "file1=%cd%\tdata_1.xml"
    set "file2=%cd%\tdata_2.xml"

    call :compareXML "%file1%" "%file2%" "Major" || ( echo files different & goto :eof )
    call :compareXML "%file1%" "%file2%" "Minor" || ( echo files different & goto :eof )
    call :compareXML "%file1%" "%file2%" "Build" || ( echo files different & goto :eof )

    echo files same

    exit /b

:compareXML file1 file2 taglist
    setlocal enableextensions disabledelayedexpansion

    setlocal enableextensions enabledelayedexpansion
    set "match=" & for %%a in (%~3) do set "match=!match! /c:"^<%%a^>""
    endlocal & set match=%match%

    for /f "tokens=1,2 delims=<> " %%a in ('
        type "%~1" "%~2" 2^> nul ^| findstr /i /l %match%
    ') do if not defined _F1_%%a ( set "_F1_%%a=%%b" ) else (
        setlocal enabledelayedexpansion
        for %%c in ("!_F1_%%a!.") do (
            endlocal
            if /i not "%%b."=="%%~c" ( endlocal & exit /b 1 )
            set "_F1_%%a="
        )
    )
    set _F1_ 2>nul && ( endlocal & exit /b 1 ) || ( endlocal & exit /b 0 )


Q:

symfony2: index in individual form field for collection type

After hours of searching, I found a solution how to apply themes to individual fields for collection types here: symfony2: Applying theme to individual field for collection type (thanks @TroodoN-Mike).
So a custom theme for a collection type could be:
{% block _author_tags_entry_label %}
    {# ... #}
{% endblock %}

The word "entry" replaces the row index, which works fine, but I need the Row index inside the custom block, something like {{ entry }}. Any hints?
Thanks
Chris

A:

Ok, I found the solution. I wasn't aware of the fact, that you can pass custom variables to the form theme like this:
{{ form_row(form.field, {'customVariable': 'anyValue'}) }}


Q:

https.listen ignores hostname

I tried to bind the https server to my subdomain (cdn.somedomain.com). But https.listen(443, 'cdn.somedomain.com') ignores the hostname. He trys to bind the ip and thus all adresses.

var fs = require('fs');
var https = require('https');
var express = require('express');
var app = express();
var subdomain = require('express-subdomain');
var router = express.Router();
var options = {
   key  : fs.readFileSync('/path/to/privkey.pem'),
   cert : fs.readFileSync('/path/to/cert.pem'),
   hostname: 'cdn.somedomain.com'
};

router.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});
router.use(express.static('somefiles'));
app.use(subdomain('cdn', router));

https.createServer(options, app).listen(443, 'cdn.somedomain.com');

I already tried to use 'express-subdomain', how you can see in my code.
I hope you can help me.
Nils

A:

Sounds like you want virtual hosting, where your server will only pass requests matching a particular hostname (cdn.somedomain.com) to the router.
You can use the vhost module for that:
var vhost = require('vhost');
...
app.use(vhost('cdn.somedomain.com', router));


Q:

String not being returned

I'm trying to access a parent class to pass information from it to its child and then echo that information to the page, but i cannot seem to get the $flavor to echo out from the Soda class i created. What gets echo'd out to the screen is; Product Name: Space Juice Soda Flavor: - obviously something is wrong with my __construct (i think)  in the Soda class but cannot figure out what.
class Product {

public $name = 'default_name';
public $price = 0;
public $desc = "default description";

function __construct($name, $price, $desc) {
    $this->name = $name;
    $this->price = $price;
    $this->desc = $desc;
}

public function getInfo() {
    return "Product Name: " . $this->name;
}
}

class Soda extends Product {

public $flavor;

function __construct($name, $price, $desc, $flavor) {
    parent::__construct($name, $price, $desc);
}

public function getInfo() {
    return "Product Name: " . $this->name . " Flavor: " . $this->flavor;
}
}

$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Soda("Space Juice Soda", 2, "Thirst mutilator", "Grape");

echo $soda->getInfo();

A:

You are not initializing flavor in your Soda class.
class Soda extends Product {

       public $flavor;

       function __construct($name, $price, $desc, $flavor) {
           parent::__construct($name, $price, $desc);
           $this->flavor = $flavor; // add this line here <<<<<<<<<<<<<
       }
       ...


Q:

Displaying raster images using Leaflet?

The purpose is to create a small web application using an open source product, preferred Leaflet (but I will Switch the product if it works within another Framework than leaflet), simply showing a base map and with the possibility that the user can load (through a search on the computer system) raster images that only have to be displayed.
What is the basic conceputal Approach to solve this problem?

A:

Start by reading the reference for L.ImageOverlay, and browse plugins such as L.ImageOverlay.Rotated and L.DistortableImage.


Q:

Does Windows Server Backup include GPOs?

All of the documentation I can find on backing up Group Policy discusses using the Group Policy Management Editor to back up the GPOs separately from the rest of the domain.  Any scheduled or automated backup procedure relies on a custom PowerShell script.  Are GPOs backed up via Windows Server Backup like the rest of the domain?

A:

If you're backing up a Domain Controller and you're performing a Full/Bare Metal Recovery backup then Group Policy will be backed up as part of the backup.


Q:

Optimal iPad video settings?

I'm converting some video to put on an iPad, and recently MPEGStreamclip has been producing unsatisfactory results when I try and load it onto the device.  What are the optimal video settings for an iPad in terms of resolution, bitrate, codec, etc.?

A:

iPad playable media formats:
Video files MP4, M4V, MOV file formats. H.264 video up to 720p, 30fps, main profile level 3.1 with AAC-LC audio up to 160Kbps, 48kHz, stereo audio; MPEG-4 video up to 2.5 Mbps, 640 by 480 pixels, 30fps, simple profile with AAC-LC audio up to 48kHz, 160Kbps, stereo audio.
Music and audio files in AAC, MP3, MP3 VBR, Audible, WAV, AIFF, Apple Lossless.
Video/DVD to iPad Conversion Guide (Four ways)
Remember that the end result depends a lot on the quality of the video you started with.


Q:

Getting uploaded shapefile into geometry field on PostGIS table?

I am working with a PHP web application where we have a user submitting a ShapeFile.
I am able to convert that ShapeFile then to a format of geojson.
What I am wondering now is how I can best get that geojson into a PostGIS table as a geometry column?

A:

It might be easier to use shp2pgsl to directly load the shapefile into a PostGIS table, for example:
shp2pgsql -d -I shapefile.shp table | psql -U user database

If you prefer to use GeoJSON directly, there is ST_GeomFromGeoJSON, but for this (as I understand), you'll need to parse and insert individual features from the GeoJSON file. See this answer for additional details.
You can always keep the GeoJSON file on the server for transfer to the client, or export individual features from PostGIS as GeoJSON, using ST_AsGeoJSON
If going directly from shape to PostGIS doesn't fit your use case, perhaps include some additional information.


Q:

How to return data using await function in C# windows phone 8?

I'm new to C#. I
I've a problem related to async methods and await function in C#  windows phone 8.0.
I've this http request and can get response. This is working fine and There is no issue...
public async static Task<List<MyAccountData>> GetBalance()
{
       HttpClient = new HttpClient();
       string response = await client.GetStringAsync("http://xxxx/xxx/xxx");

       List<MyAccountData> data = JsonConvert.DeserializeObject<List<MyAccountData>>(response);

       return data;
}

I've another class call MainModel
public class MainModel
{
       public void LoadData()
       {

       }
}

So My problem is, I want to call that GetBalance method with in MainModel class and parse data to LoadData method(simply want 2 access Data with in LoadData method). LoadData method can't change return type or can't use async. So how is this possible?

A:

If you want a responsive UI - i.e., one that has a chance of being accepted in the store - then blocking on the async operation is not an option.
Instead, you have to think a bit about how you want your UI to look while the operation is in progress. And while you're thinking about that, also think about how you would want your UI to respond if the operation errors out.
Then you can code up a solution. It's possible to do this with async void, if you catch all exceptions and handle them cleanly:
public async void LoadData()
{
  try
  {
    ... // Set up "loading" UI state.
    var balance = await GetBalanceAsync();

    ... // Set up "normal" UI state.
    Balance = balance;
  }
  catch
  {
    ... // Set up "error" UI state.
  }
}

However, I prefer to use a type I created called NotifyTaskCompletion, which is a data-bindable wrapper for Task<T> (described in my MSDN article). Using NotifyTaskCompletion, the LoadData becomes much simpler:
public void LoadData()
{
  GetBalanceOperation = new NotifyTaskCompletion<Balance>(GetBalanceAsync());
}

public NotifyTaskCompletion<Balance> GetBalanceOperation // Raises INotifyPropertyChanged when set

Then your UI can data-bind to properties on NotifyTaskCompletion<T>, such as IsNotCompleted (for the "loading" state), IsSuccessfullyCompleted and Result (for the "normal" state), and IsFaulted and ErrorMessage (for the "error" state).


Q:

Can you launch a telnet window from Javascript?

I currently have a link that launches a telnet link like this
<h:outputLink value="telnet://1.2.3.4">
    <h:outputText value="1.2.3.4" />
</h:outputLink>

All the users have their browsers configured correctly to launch some telnet client or other when they click this link.
I want to change the link, which currently appears on the page, to a link in a context menu (rich:menuItem).
Menu items apparently do not play well with JSF outputLinks (or any other kind of links). You need to implement it as the value of an onclick event:
<rich:menuItem value="View Details" onclick="window.location='http://ond.ba.ssa.gov" />

I tried implement the telnet this same way:
<rich:menuItem value="1.2.3.4" onclick="window.location='telnet://1.2.3.4'" />

But it doesn't work. Should it? Is there a simple way to do this?  If so, I haven't been able to find it.
Thanks in advance.

A:

IIRC older IEs have some kind of exec method you could invoke/exploit, but almost everything else will treat this as a security violation.


Q:

Format all elements of a list

I want to print a list of numbers, but I want to format each member of the list before it is printed.
For example,
theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

I want the following output printed given the above list as an input:
[1.34, 7.42, 6.97, 4.55]

For any one member of the list, I know I can format it by using
print "%.2f" % member

Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.

A:

If you just want to print the numbers you can use a simple loop:
for member in theList:
    print "%.2f" % member

If you want to store the result for later you can use a list comprehension:
formattedList = ["%.2f" % member for member in theList]

You can then print this list to get the output as in your question:
print formattedList

Note also that % is being deprecated. If you are using Python 2.6 or newer prefer to use format.

A:

For Python 3.5.1, you can use:
>>> theList = [1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> strFormat = len(theList) * '{:10f} '
>>> formattedList = strFormat.format(*theList)
>>> print(formattedList)

The result is:
'  1.343465   7.423334   6.967998   4.552258 '

A:

You can use list comprehension, join and some string manipulation, as follows:
>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> def format(l):
...     return "["+", ".join(["%.2f" % x for x in l])+"]"
...
>>> format(theList)
'[1.34, 7.42, 6.97, 4.55]'


Q:

pip build . similar to python setup.py build

Instead of doing
python setup.py install

we can do
pip install .

But, it does not build the library rather installs the egg without building.
Is there any command to build from pip which works similar to
python setup.py build

?

A:

pip install -e .

It builds and then installs.


Q:

dynamically populate div from js array in html form

I am basically a newbie with javascript. I want to populate a div in my webpage from a select form found on the same page, when the user selects the book and chapter he wants to view and presses the submit button. Here the code:
<script type="text/javascript" charset="utf-8">
          var setArray = newArray(
                 bk1, 001, "this is my chapter content for the <div>",
                 bk1, 002, "this is my chapter content for the <div>",
                 bk1, 003, "this is my chapter content for the <div>",
                 bk2, 001, "this is my chapter content for the <div>",
                 bk2, 002, "this is my chapter content for the <div>"
                 etc....
          );
</script>

<form>
<select id="book">
  <option value="">Select Book</option>
  <option value="bk1">Book 1</option>
  <option value="bk2">Book 2</option>
  <option value="bk3">Book 3</option>
</select>
<select id="chapter">
  <option value="">Select Chapter</option>
  <option value="001">1</option>
  <option value="002">2</option>
  <option value="003">3</option>
</select>
<button id="button" type="submit">View</button>
</form>

<div id="content">
I want the content from the js array for the selected book and chapter to be placed here without reloading the page.
</div>

Note: I have simplified the code to make it a little easier to follow. I am sure my js array is incorrect and needs fixing for my purpose. Also, I don't want the page to refresh, only the div to update. Thanks for any help.

A:

As has been suggested, you should seriously consider using ajax to retrieve this data, it would not make the page refresh, and would allow you to keep this data semi-private, and more easily manageable on the backend.
If/when you do this with ajax, you'll still need something like the following:
var booksData = {
    book1: [
        "chapter 1 content",
        "chapter 2 content",
        "..."
    ],
    book2: [
        "chapter 1 content",
        "chapter 2 content",
        "..."
    ]
}

function whenButtonClicked() {
    var book = "book1" // get the actual book name from the select input
    var chapter = 0 // get the selectedIndex of chapter input
    var content = booksData[book][chapter];
    var div = document.getElementById("content");
    div.innerHTML = content;
}

And use an onclick handler on the button.  Something like
<button id="button" onclick="whenButtonClicked()">

I'd recommend looking at a library like jQuery that would make life easier, and clean a lot of this up.


Q:

Listbox item change on click WP7

I have got a binded listbox in WP7 containing a set of items in each portion, i want to change the icon's path when clicked so that the clicked icon is changed.
This is my XAML data and the Stackpanel which is in Italic and Bold needs to be changed on the click button.
   <ListBox Height="768" HorizontalAlignment="Left" Name="listBox1" Margin="0,0,0,0"
            VerticalAlignment="Top" Width="480" Grid.RowSpan="2" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button BorderBrush="Black" Width="460" Height="100">
                    <Button.Content>
                        <StackPanel Orientation="Horizontal" Height="80" Width="400">
                            <Image Source="{Binding Image}" Width="80" Height="50"/>
                            <StackPanel Orientation="Vertical" Height="80">
                                <StackPanel Orientation="Horizontal" Height="40">
                                    <TextBlock Width="200" FontSize="28" Text="{Binding Name}" Height="50"/>
                                    <StackPanel Orientation="Horizontal">
                                        ***<Image Source="{Binding OnOff}" Width="100" Height="40" Tap="Image_Tap"/>***
                                        </StackPanel>
                                </StackPanel>
                            </StackPanel>
                        </StackPanel>
                    </Button.Content>
                </Button>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

I have filled this listbox in this way
     void MainPage_Loaded(object sender, RoutedEventArgs e)
     {
        List<settings> settingsData = new List<settings>();

        settingsData.Add(new settings("Administrator","Images/ad.png",""));
        settingsData.Add(new settings("Wi-Fi","Images/wifi.png","Images/off.png"));
        settingsData.Add(new settings("Bluetooth", "Images/BlueTooth.png", "Images/On.png"));
        settingsData.Add(new settings("Airplane Mode", "Images/747.png", "Images/off.png"));
        settingsData.Add(new settings("VPN", "", ""));
        settingsData.Add(new settings("Hotspot", "", "Images/unchecked.png"));
        settingsData.Add(new settings("NFC", "", "Images/checked.png"));
        settingsData.Add(new settings("Sound","Images/sound.png",""));
        settingsData.Add(new settings("Display","Images/display.png",""));

        listBox1.ItemsSource = settingsData;
    }

Help please..!!

A:

A quick solution is,
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        var imageSource = ((sender as Image).Source as BitmapImage).UriSource.OriginalString;
        if (imageSource.Contains("On"))
        {
            (sender as Image).Source = new BitmapImage(new Uri("Images/Off.png", UriKind.Relative));
        }
        else
        {
            (sender as Image).Source = new BitmapImage(new Uri("Images/On.png", UriKind.Relative));
        }
    }


Q:

Stopwatch that counts down in C#

I've seen variations of this by googling it but I have a windows form with a timer control, three textboxes (hour, minute, second) and based on a button being clicked, I want to count down from 2 hours.  So right after clicking textbox1 (hour) will be 1, textBox2 (minute) will be 59, textBox3 (second) will be 59 and they will all continue to count down until all read 0.
Does anyone have some code to share for that?
Many thanks.

A:

You can use the TimeSpan class. Initialize of to 2 hours. If you start the Timer get the current timer. Then with a Timer object refresh your display every second. Simply get the current Time. So the remaining time is:
TimeSpan remaining = twoHoursTimespan - (CurrentTime - StartTime);

A:

Extract the components from a TimeSpan. Record the current time and date as soon as the button is clicked, and store that in a variable. Then, every second your timer should calculate the duration since the start time.
IE: DateTime result = DateTime.Now.Subtract(StartingTime);
Then, use the parts of the resulting TimeSpan to populate the fields.
IE: int Hour = result.Hour; (or something like that).
Addendum: Don't count down manually every second, because this is likely to cause the countdown to be inaccurate.


Q:

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
    {
        "id": 1,
        "name": "name1",
        "email": "email1",
        "phone": "1234567890"
    },
    {
        "id": 2,
        ETC...

I need to process another JSON file but it has a different structure:
{
    "contacts": {
        "1": {
            "id": 1,
            "name": "name1",
            "email": "email1",
            "phone": "1234567890",
            "level1": {
                "level2": {
                    "level3": 3,
                }
            },
            "last_updated": 20180712
        },
        "2": {
            ETC...

How do I process this second JSON file by adjusting the below code?
    if (jsonSource != null) {
        try {
            JSONObject jsonObject = new JSONObject(jsonSource);
            JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");

            for (int i = 0; i < jsonArrayData.length(); i++) {
                JSONObject contacts = jsonArrayData.getJSONObject(i);
                String id = contacts.getString("id");
                String name = contacts.getString("name");
                String email = contacts.getString("email");
                String phone = contacts.getString("phone");

                HashMap<String, String> values = new HashMap<>();
                values.put("id", id);
                values.put("name", name);
                values.put("email, email);
                values.put("phone, phone);
                contactList.add(values);
            }
        } catch (final JSONException e) {
            Log.e(TAG, "JSON parsing error: " + e.getMessage());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
                }
            });
        }
    } else {
        Log.e(TAG, "Unable to retrieve JSON file from URL");
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
            }
        });
    }
    return null;

Any help is much appreciated!

A:

It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
    {...},
    {...},
    {...}
]
"contacts": {
    "1": {...},
    "2": {...},
    "3": {...}
}

So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
    JSONObject contactsJson = jsonObject.getJSONObject("contacts");
    for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
        String key = it.next();
        JSONObject contactJson = contactsJson.getJSONObject(key);
        // your code to process contact item
    }
} else {
    // Your code to process every contact item
}


Q:

A Combinatorics Question: Why Is My Solution Wrong, And The Given Solution Correct?

I have encountered this problem: "A circular table has 60 chairs around it. There are N people seated at this table so that the next person seated must sit next to someone. Find the smallest possible value of N". I'm struggling to understand why my solution is wrong, and why the given solution is correct.
My proof is, given N people, if we leave 1 seat to the left of each person blank, then no one has to sit next to each other, however the next person who sits has to sit next to someone. We then proceed to find the number of people this arrangement will need. Since the number of occupied and unoccupied seats must add up to 60, 2N=60. Therefore, N = 30 people can be seated.
However, the solution given is 20. The explanation is "If every third seat is occupied, filling 20 seats, then every unoccupied seat has a person sitting next to it, so N could be 20. To see that N must be at least 20, note that any seating which satisfies the conditions cannot contain a gap of more than 2 unoccupied seats between any occupied seats. If we regard adjacent
occupied seats as having a gap of 0 between them, every seating of N people contains N gaps, all of which must be less than 2. Thus N+2N = 3N is at least as big as the sum of N and all the which is 60, therefore 3N ≥ 60 and N ≥ 20.Note that there are simpler arguments that work when there are 60 seats around the table, but this proof has the advantage of working just as well when the number of seats is not a multiple of 3 (e.g. for 59 seats N must still be at least 20
since 3N ≥ 59, and for 61 seats 3N ≥ 61 implies N ≥ 21)."
I don't understand why my reasoning is false, and why their reasoning is correct. Could someone explain this to me?
Thanks in advance.

A:

I think it is evidently clear how the maximum gap must be less than 3. If the gap exceeds 2, then there will have to be at least one gap of 3 which will allow the next person to sit in the middle.
As we increase the no. of gaps, the value of N will consequently decrease. Thus to find the least value of N for the given conditions to satisfy, we must consider the case where maximum permitted gaps are present.
This is in the case of every third seat being occupied (as this allows a gap of 2 between each person, which is max. permitted gap)
Thus the least value of N turns out to be 20.
The problem with your answer is that, even though it satisfies the given conditions, it's not the best possible arrangement. As in, it isn't the least value of N (which is asked). It is easy to see how increasing the gap will decrease N. So in your case you haven't allocated the maximum gaps, that is the reason your answer came to be incorrect.


Q:

Java - Error trying to access a class from another class

I've been trying to make a programm called QuadraticTester, which calculates quadratic function by using another class called Quadratic. To do that, I ask the user to write three coefficients (A, B and C). Everything works fine when a try to compile them, the problem starts when I want to execute them. This is the error that the CMD shows me when I use the java QuadraticTester command:
C:\Users\Pedro\Desktop>java QuadraticTester.java
Exception in thread "main" java.lang.IllegalAccessError: failed to access class Quadratic from class QuadraticTester (Quadratic is in unnamed module of loader 'app'; QuadraticTester is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @11c20519)
        at QuadraticTester.main(QuadraticTester.java:4)

This is the Quadratic.java :
class Quadratic{

    double a;
    double b;
    double c;

    String buildEcuation(double a, double b, double c){
        String ecuation =(a + "x2 + " + b +"x  + " + c + " = 0");
        return ecuation;
    }
}

This is the QuadraticTester.java :
class QuadraticTester{
    public static void main(String[] args){

        Quadratic cuad1 = new Quadratic();

        double a = Scanner.getDouble("Ingrese un valor para el coeficiente A: \n");
        double b = Scanner.getDouble("Ingrese un valor para el coeficiente B: \n");
        double c = Scanner.getDouble("Ingrese un valor para el coeficiente C: \n");

        System.out.println(cuad1.buildEcuation(a, b, c));

    }
}

I don't know the meaning of this errors or how to fix them. I hope you can understand my problem and thanks in advance!
PD: I'm not very good at speaking English, so sorry if there is something grammatically wrong in this question ;)

A:

This is kind of embarrasing, but I was writing the execute command in a wrong way:
I was executing like this:
C:\Users\Pedro\Desktop>java QuadraticTester.java

But the correct way is:
C:\Users\Pedro\Desktop>java QuadraticTester

(Without '.java')
Thanks to everybody for your answers and kindness! ;)


Q:

A game with a combat system based on standard playing cards?

I am searching for a combat system based on standard playing cards (aka the French 52-card deck) instead of dice. The system should include melee combat and modern firearms, so that it can be used for a post-apocalyptic scenario.
To be more precise, this system should use standard playing cards for these game features:

Using firearms
Using melee weapons
Unarmed combat
Performing Maneuvers, in the event a PC possesses knowledge of particular fighting style
Determining the hit location and the damage suffered

The game should also include:

A range of firearms, from simple pistols to sniper rifles
Modifiers that increase or decrease the chance to hit:

based on the PC's skill with the weapon
environmental conditions
the physical condition of the attacker (injury, hunger, radiation poisoning, etc.)

Injury should have significant effects on those who suffer them

The system need not include all of these features, but must be able to handle at least the fighting with firearms.

A:

A Playing Card Based RPG
The No Dice system uses playing cards as it's core randomiser. To be specific, it uses a standard 52-card deck with one added joker.
The core system is a 'universal' one, meaning that it can easily handle most of the bullet-points you mention, however you would have to come up with the specifics for the crunchier of your items.
To be Specific:

Fire arms and close combat options; trivial to implement with base
rules
Fighting styles; simple-to-moderate, you'll have to invent them,
though the core rule book has some interesting examples that may help (page 164)
Combat modifiers; trivial with base rules
Significant damage; simple to implement, you may want to come up with
wounding/crippling rules that work with the combat modifiers and hit
locations (below)
Hit locations; simple; the system introduces using different card
suits to create extra flavor for draw results that should fit (page 79).
Here's a hit location example off the top of my head:

Set each suit to represent a body location, such as: Spades — Head, Hearts & Diamonds — Torso, Clubs — Limbs. For regular attacks these can be used to determine where the attack hits on a success. Called shots would require the player to draw the correct suit. If it's right the player does extra damage or other special effect, if it isn't the attack simply missed. Queens could mean hitting a vital area in the location (heart/eyes) or crippling a limb. Salt to taste.

The core rules are free and can be found on the No Dice RPG website (very hard to find with Google). It's a quick read, but in particular check out page 79 on randomisers to see if you like it.
Thanks for asking something I can answer! :]

A:

Cards and Quests is a standard 52 playing card based table top RPG.  No dice needed!
C&Q is a fantasy setting.  Magic and melee combat is detailed out.  While there are no firearms in the ruleset, you could easily substitute in the firearms you would like to add using the same rules for bow/crossbow/ranged magic blasts. (you can either use the typical ranges or adjust them for sniper rifle vs handgun).
C&Q does have "fighting styles" based on a character's class based on one of 8 "elements" in the game.  Each of the elements are assigned one of the 4 suits (Spades, hearts, clubs, or diamonds) and each of the cards of the assigned suit has a special combat action associated with it.
It does not have specific damage zones (like arm damage or torso damage) but it does have a few status type attacks that make a PC discard cards from their hand or their deck.  This is important because each PC has their own deck and if a PC runs out of cards in their deck, the PC passes out from exhaustion.  By tying the deck of cards to a PC's "energy level", a GM can impose hunger or weakness by making the PC discard cards in their hand or deck to simulate an arduous climb or long journey through poison swamp, etc.


Q:

Cannot install Matplotlib on Mac

I cannot install Matplotlib on Mavericks 10.9.  I have the following error message telling me freetype cannot be built:
    ============================================================================
    Edit setup.cfg to change the build options

    BUILDING MATPLOTLIB
                matplotlib: yes [1.3.1]
                    python: yes [2.7.6 (default, Apr  9 2014, 11:48:52)  [GCC
                            4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)]]
                  platform: yes [darwin]

    REQUIRED DEPENDENCIES AND EXTENSIONS
                     numpy: yes [version 1.8.1]
                  dateutil: yes [dateutil was not found. It is required for date
                            axis support. pip/easy_install may attempt to
                            install it after matplotlib.]
                   tornado: yes [tornado was not found. It is required for the
                            WebAgg backend. pip/easy_install may attempt to
                            install it after matplotlib.]
                 pyparsing: yes [pyparsing was not found. It is required for
                            mathtext support. pip/easy_install may attempt to
                            install it after matplotlib.]
                     pycxx: yes [Couldn't import.  Using local copy.]
                    libagg: yes [pkg-config information for 'libagg' could not
                            be found. Using local copy.]
                  freetype: no  [The C/C++ header for freetype2 (ft2build.h)
                            could not be found.  You may need to install the
                            development package.]
                       png: yes [pkg-config information for 'libpng' could not
                            be found. Using unknown version.]

    OPTIONAL SUBPACKAGES
               sample_data: yes [installing]
                  toolkits: yes [installing]
                     tests: yes [nose 0.11.1 or later is required to run the
                            matplotlib test suite]

    OPTIONAL BACKEND EXTENSIONS
                    macosx: yes [installing, darwin]
                    qt4agg: no  [PyQt4 not found]
                   gtk3agg: no  [Requires pygobject to be installed.]
                 gtk3cairo: no  [Requires cairo to be installed.]
                    gtkagg: no  [Requires pygtk]
                     tkagg: yes [installing, version 81008]
                     wxagg: no  [requires wxPython]
                       gtk: no  [Requires pygtk]
                       agg: yes [installing]
                     cairo: no  [cairo not found]
                 windowing: no  [Microsoft Windows only]

    OPTIONAL LATEX DEPENDENCIES
                    dvipng: no
               ghostscript: no
                     latex: no
                   pdftops: no

    ============================================================================
                            * The following required packages can not be built:
                            * freetype
    Complete output from command python setup.py egg_info:
    ============================================================================

Edit setup.cfg to change the build options

BUILDING MATPLOTLIB

            matplotlib: yes [1.3.1]

                python: yes [2.7.6 (default, Apr  9 2014, 11:48:52)  [GCC

                        4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)]]

              platform: yes [darwin]

REQUIRED DEPENDENCIES AND EXTENSIONS

                 numpy: yes [version 1.8.1]

              dateutil: yes [dateutil was not found. It is required for date

                        axis support. pip/easy_install may attempt to

                        install it after matplotlib.]

               tornado: yes [tornado was not found. It is required for the

                        WebAgg backend. pip/easy_install may attempt to

                        install it after matplotlib.]

             pyparsing: yes [pyparsing was not found. It is required for

                        mathtext support. pip/easy_install may attempt to

                        install it after matplotlib.]

                 pycxx: yes [Couldn't import.  Using local copy.]

                libagg: yes [pkg-config information for 'libagg' could not

                        be found. Using local copy.]

              freetype: no  [The C/C++ header for freetype2 (ft2build.h)

                        could not be found.  You may need to install the

                        development package.]

                   png: yes [pkg-config information for 'libpng' could not

                        be found. Using unknown version.]

OPTIONAL SUBPACKAGES

           sample_data: yes [installing]

              toolkits: yes [installing]

                 tests: yes [nose 0.11.1 or later is required to run the

                        matplotlib test suite]

OPTIONAL BACKEND EXTENSIONS

                macosx: yes [installing, darwin]

                qt4agg: no  [PyQt4 not found]

               gtk3agg: no  [Requires pygobject to be installed.]

             gtk3cairo: no  [Requires cairo to be installed.]

                gtkagg: no  [Requires pygtk]

                 tkagg: yes [installing, version 81008]

                 wxagg: no  [requires wxPython]

                   gtk: no  [Requires pygtk]

                   agg: yes [installing]

                 cairo: no  [cairo not found]

             windowing: no  [Microsoft Windows only]

OPTIONAL LATEX DEPENDENCIES

                dvipng: no

           ghostscript: no

                 latex: no

               pdftops: no

============================================================================

                        * The following required packages can not be built:

                        * freetype

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /private/var/folders/jj/0w0dd3n16jq4g5579g6c7h040000gn/T/pip_build_mc/matplotlib
Storing debug log for failure in /Users/mc/.pip/pip.log

I have followed the instructions here and here but it still doesn't work.  This is a clean system install and I just installed Python with brew as well.

A:

I had to install pkg-config with brew to fix it
    brew install freetype
    brew install pkg-config

'brew list' now reports:
    freetype    libpng      pkg-config

A:

Use home-brew python to install Matplotlib.  That finally fixed it for me:
brew tap Homebrew/python  # installs the Homebrew/python "tap"
brew install matplotlib   # install matplotlib with homebrew

More info here: https://github.com/Homebrew/homebrew-python


Q:

SQL show selected rows from multi tables if some columns data missing

I have this query:
SELECT bills.date as bills_date
     , bills.bill_nr as bill_nr
     , bills.amount as amount
     , cheques.cheque_nr as cheque_nr
     , cheques.date as cheque_date
     , cheques.amount as cheque_amount
FROM bills
INNER JOIN cheques ON bills.bill_nr = cheques.cheque_nr
LEFT JOIN companys ON bills.company = companys.id
WHERE companys.name='';

The problem that this query didn't return bill if it didn't have any cheque. Maybe someone knows how to fix it? Thank you!

A:

SELECT bills.date as bills_date
     , bills.bill_nr as bill_nr
     , bills.amount as amount
     , cheques.cheque_nr as cheque_nr
     , cheques.date as cheque_date
     , cheques.amount as cheque_amount
FROM  bills
LEFT JOIN cheques   ON bills.bill_nr = cheques.cheque_nr   --<-- LEFT JOIN here
LEFT JOIN companys  ON bills.company = companys.id
WHERE companys.name='';


Q:

Derive the Black– Scholes formula for the European call option.

Consider the standard Black–Scholes model. Derive the Black–
Scholes formula for the European call option.
thanks for help.

A:

The equation $dS(t)=rS(t)dt+\sigma S(t)dW(t)$ is not the Black-Scholes formula.  It is a stochastic differential equation for geometric Brownian motion, which is one of the assumptions made in the derivation of the Black-Scholes-Merton pricing formula for an option.
The stock price, $S(t)$, at any future time, is a lognormal random variable -- under the assumption of geometric Brownian motion.
For a call option with strike $K$ that expires at time $T$, the option price at some earlier time $t$ is the expected payoff under the risk-neutral measure (where a more general drift $\mu$ can be replaced by a risk-free rate $r$ as you have already shown.)  This takes the form
$$C[S(t),t] = E_t \{\max[S(T)-K,0]\},$$
where the expectation is conditioned on the information known at time $t$.
Using a dynamic hedging argument, it can be shown that the option price satisfies the Black_Scholes partial differential equation
$$\frac{\partial C}{\partial t} +rS\frac{\partial C}{\partial S} + \frac{1}{2}\sigma^2S^2\frac{\partial^2 C}{\partial S^2}-rC=0,$$
which can be solved in closed form (under suitable assumpions such as constant volatility) for the Black-Scholes option pricing formula.


Q:

How to loop a list of item in 1 column and make a second column when it reach a limit

Ok, im sorry if this is a dumb question, i have spent many hours in google, but i can't find anything maybe because i dont know the correct keyword.
Si i need to ceate a list like this :
Some Title:
item 1            item 6
item 2            item 7
item 3            item 8
item 4
item 5
I need to looping a array of data then make it 2 column when it has reach it's limit, so that would be the same result as the template.
i would love to show a detail image, but i dont have enough reputation to do it. So hope you can understand.
plese help me if you know the solution.
thank you very much.

A:

array_chunk() & possibly array_map() (depending on how your really want it) can be your friends:
php > $array = range(1,8);
php > $chunked = array_chunk($array,5);
php > var_dump($chunked);
array(2) {
  [0] =>
  array(5) {
    [0] =>
    int(1)
    [1] =>
    int(2)
    [2] =>
    int(3)
    [3] =>
    int(4)
    [4] =>
    int(5)
  }
  [1] =>
  array(3) {
    [0] =>
    int(6)
    [1] =>
    int(7)
    [2] =>
    int(8)
  }
}
php > array_unshift($chunked,NULL);
php > var_dump(call_user_func_array('array_map',$chunked));
array(5) {
  [0] =>
  array(2) {
    [0] =>
    int(1)
    [1] =>
    int(6)
  }
  [1] =>
  array(2) {
    [0] =>
    int(2)
    [1] =>
    int(7)
  }
  [2] =>
  array(2) {
    [0] =>
    int(3)
    [1] =>
    int(8)
  }
  [3] =>
  array(2) {
    [0] =>
    int(4)
    [1] =>
    NULL
  }
  [4] =>
  array(2) {
    [0] =>
    int(5)
    [1] =>
    NULL
  }
}


Q:

How to make the damage inflicted to the enemy and the main character more unpredictable

I am developing a small mobile game. The enemy can damage my player by throwing objects at his side, and the player can damage the enemy by hitting him with a bat.
For the moment, I am calculating the damage that was caused by the player or the enemy in a very simple way. For example, my enemy has 100% of health. When the player hits him with a bat, the enemy is losing 10% of his health. So after 10 hits the enemy is "dead".
But this is not interesting. The game process is very simple and predictable: you are moving, see the enemy, hit him 10 times, and the move to the next enemy. When the enemy hits the player,the player loses 10% of his  health. That is not cool (the game process is very static).
An alternative, is to use random integer values to calculate damage values. Can anyone give an idea, how to make damage process more interactive and unpredictable, and how to make proportional link between player health and enemy health and the damage.

A:

These are entirely design considerations and there's many ways to go about this. For starters:

Instead of strict damage, give it a range. ie. the bat doesn't do "10 damage", instead make it do 8-12 and randomize it between those values.
Give the enemy a chance to dodge or the player a chance to miss based upon some small percentage. This must be reflected visually (and audibly?) somehow.
Give the enemy/player a chance to crit for 2x or 3x damage.

If desired (and fitting within your design) the player may be given the ability to "upgrade" any of these through the actual weapon or skill.
For the second part of your question regarding linking the player's health that would entirely need to make sense within your design. One example would be that as a character's health is reduced their attacks get weaker. The other side to that coin could be that as a character's health is reduced adrenaline kicks in and their attacks get stronger. It all depends on how you want to spin it and that the mechanic makes some sense as opposed to being arbitrary.


Q:

Set custom headers for websocket handshake in .NET 4.5

I'm trying to set a WebSocket connection of C# client with third-party server. When I connect with JS client to the same server, it establishes connection and everything goes fine. C# client connects to the server, but for some unknown reason server responds with 500 code. Debugging with WireShark has shown that HTTP handshake phase of WebSocket connection differs between client implementation in a set of headers. I would like to tweak the headers default System.Net.WebSockets.ClientWebSocket class sends to the server to check that the issue is there. Though, I couldn't find a way to do that.
How do I instruct ClientWebSocket of some other class in that namespace to send additional given headers in handshake phase?

A:

It looks like this is exposed by ClientWebSocketOptions.SetRequestHeader, so:
obj.Options.SetRequestHeader("foo", "bar");

should work. This also provides access to AddSubProtocol(...).


Q:

Instr from ubound array range

For search in one column (column B) i use this code
Private Sub TextBox1_Change()

txt = TextBox1.Text
lt = Len(TextBox1.Text)
If lt = 0 Then Exit Sub

x = Range("b1", Cells(Rows.Count, 1).End(xlUp)).Value

For i = 1 To UBound(x, 1)
    If InStr(x(i, 2), txt) Then
            s = s & "~" & x(i, 1) & "         >>>>" & x(i, 2)

    Else
    End If
Next i

ListBox1.List = Split(Mid(s, 2), "~")
End Sub

But how to change this code to look for txt in some column (Column B and Column A) or (Column B and Column A and Column C) at once?
so if i have
in column A
first
second
thirdFirst

in column B
notfirst
secondFirst
third

with this code i look only in column B and get
if txt= first
result
first notfirst
second secondFirst

but i cant find thirdFist values from column A
 so i need get result like
if txt= first
result
first notfirst
second secondFirst
thirdFirst third

A:

Ok, so I hope I understood your question right. Here example of code and the result for sample data on the picture. HTH.
Option Explicit

Private Sub CommandButton1_Click()
    Dim txt, values, valuesFiltered, r, c, rowsCount, columnsCount, check

    txt = "first"
    If Len(txt) = 0 Then _
        Exit Sub

    ' get all values from last used cell in column 'A' to upperRightCell
    ' e.g. "B1', 'C1' etc.
    Dim lastUsedCellInColumn_A As Range
    Set lastUsedCellInColumn_A = Cells(Rows.Count, 1).End(xlUp)

    Dim upperRightCell As Range
    Set upperRightCell = Range("C1")

    values = Range(lastUsedCellInColumn_A, upperRightCell).Value
    rowsCount = UBound(values, 1)
    columnsCount = UBound(values, 2)

    If columnsCount <= 1 Then _
        Err.Raise 12345, , "At least two columns must be used."

    For r = 1 To rowsCount
        For c = 1 To columnsCount

            If InStr(values(r, c), txt) = 0 Then _
                GoTo next_column

            If c > 1 Then
                ' columns B, C, D and so on: take value from neighbour cell on the left
                check = values(r, c) & ">>>>" & values(r, c - 1)
            Else
                ' column A: take value from neighbour cell on the right
                check = values(r, c + 1) & ">>>>" & values(r, c)
            End If

            ' do not add duplicate values
            If IsArray(valuesFiltered) = False Then
                ReDim valuesFiltered(0)
                valuesFiltered(0) = check
            Else
                If UBound(Filter(valuesFiltered, check)) = -1 Then
                    ReDim Preserve valuesFiltered(UBound(valuesFiltered) + 1)
                    valuesFiltered(UBound(valuesFiltered)) = check
                End If
            End If

next_column:
        Next c
    Next r

    If Not IsEmpty(valuesFiltered) Then _
        ListBox1.List = valuesFiltered
End Sub


Q:

Reconnecting on MySQL Server Has Gone Away

How can I modify this class to catch exception where MySQL Server Goes Away, and reconnect?
<?php
class DBConn
{
private $conn;

public function __construct( $persistent = false )
{
    try
    {
        $this->conn = new PDO( "mysql:host=localhost;dbname=test", 'test', "hoollaahaoo" );
        $this->conn->exec( "SET CHARACTER SET utf8" );
        $this->conn->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
        if ( $persistent )
            $this->conn->setAttribute( PDO::ATTR_PERSISTENT, true );
    }
    catch( PDOException $e )
    {
        return $e->getMessage();
    }
}

public function getConn()
{
    return $this->conn;
}
}

A:

you probably will need to make your own class like this one

remove try/except from __construct
then connect to you db like this:

$conn = null;
$limit = 10;
$counter = 0;
while (true) {
  try {
    $conn = DBConn();
    break;
  }
  catch (Exception $e) {
    $conn = null;
    $counter++;
    if ($counter == $limit)
      throw $e;
  }

}
EDIT 1:
but if you say that your server goes away.... then may be smth like this
protected function _connect( $persistent = false ) {
$conn = null;
$limit = 10;
$counter = 0;
while (true) {
  try {
        $this->conn = new PDO( "mysql:host=localhost;dbname=test", 'test', "hoollaahaoo" );
        $this->conn->exec( "SET CHARACTER SET utf8" );
        $this->conn->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
        if ( $persistent )
            $this->conn->setAttribute( PDO::ATTR_PERSISTENT, true );
}
  catch (Exception $e) {
    $conn = null;
    $counter++;
    if ($counter == $limit)
      throw $e;
  }
}

public function __construct( $persistent = false )
{
    $this->_connect($persistent);
}


Q:

Business layer in an asp.net application

Suppose you have a web application where based on some numbers the user has entered you give him another number (over simplified) when he/she clicks a button. All the data is stored in SQL server. Now I can get all the required data to the Business access layer and do the calculation there. Or do the calculation in the database stored proc and send the result to the application. I strongly prefer the latter,because I find it much easier. But some people may argue all the business logic must lie in business layer in the app. I feel if there is any business logic in the app, it belongs in business layer. But you don't have to have the data related business logic in the app.
What would the experts recommend?

A:

If I might rephrase your question, I think you're asking, "Should I put my business logic in tsql or c#?"
Personally, I would strongly recommend c# (or vb.net if that's what you're using). As a programming tool, it gives you so much more power than tsql. And when I say power, I mean power to write easy to understand, logical, well organized self documenting code, that, more importantly, is easy to maintain. Object oriented techniques like abstract classes and interfaces allow you to create not only reusable pieces of code, but allow you to enforce business logic that is easily traceable. This can be simulated with stored procs, but you end up jumping through hoops to implement it, and then trace it when there are issues.
Code repositories are also built to integrate with VS much more easily than SQLserver, and change management, or even local dev environment upkeep becomes more difficult when things are centered on a database that is too large to run locally as opposed to updating a developers local working copy of c# code.
Of course, in a single developer scenario, when no one else will ever work on this app, collaboration and change management considerations pale in comparison to the developer's comfort with tsql vs any other tool.
And finally, just because c# provides rich language features, not everyone uses them. I can (and have!!) write a 1000 line c# method just as easily as I can write a 1000 line stored proc.
Hope this helps,
Lawrence