Q:

Selenium WDS executeScript()

I have a strange problem, which I'm unable to solve for sometime. I have a selenium WDS for Firefox browser. I tried to execute the code in JMeter UI, everything works fine. But when I try to execute the same in a server (using XVFB driver), I get the error:
rm="sun.org.mozilla.javascript.EvaluatorException: Can't find method org.openqa.selenium.remote.RemoteWebDriver.executeScript(string,org.openqa.selenium.remote.RemoteWebElement). (<Unknown source>#17) in <Unknown source> at line number 17"
All the required drivers are the same as the one I locally try. Yet, I get the error only when I run in the server but not locally.  Please help

A:

Most probably you have different versions of either WebDriver Sampler or dependency libraries, I don't see any other ways for the same script to work on one machine and don't work on another.

Install the same version of JMeter onto both machines (use JMeter 3.2 or later, whatever is available at JMeter Downloads Page)
Install latest version of the WebDriver Sampler plugin using JMeter Plugins Manager
Your test should now be running fine.


Q:

php replace regular expression instead of string replace

I'm trying to give my client the ability to call a function that has various code snippets by inserted a short code in their WYSIWYG editor.
For example, they will write something like...
[getSnippet(1)]

This will call my getSnippet($id) php function and output the appropriate 'chunk'.
It works when I hard code the $id like this...
echo str_replace('[getSnippet(1)]',getSnippet(1),$rowPage['sidebar_details']);

However, I really want to make the '1' dynamic.  I'm sort of on the right track with something like...
function getSnippet($id) {
 if ($id == 1) {
  echo "car";
 }
}

$string = "This [getSnippet(1)] is a sentence.This is the next one.";
$regex = '#([getSnippet(\w)])#';
$string = preg_replace($regex, '. \1', $string);

//If you want to capture more than just periods, you can do:
echo preg_replace('#(\.|,|\?|!)(\w)#', '\1 \2', $string);

Not quite working :(

A:

Firstly in your regex you need to add literal parentheses (the ones you have just capture \w but that will not match the parentheses themselves):
$regex = '#(\[getSnippet\((\w)\)\])#';

I also escaped the square brackets, otherwise they will open a character class. Also be aware that this captures only one character for the parameter!
But I recommend you use preg_replace_callback, with a regex like this:
function getSnippet($id) {
    if ($id == 1) {
        return "car";
    }
}

function replaceCallback($matches) {
    return getSnippet($matches[1]);
}

$string = preg_replace_callback(
    '#\[getSnippet\((\w+)\)\]#',
    'replaceCallback',
    $string
);

Note that I changed the echo in your getSnippet to a return.
Within the callback $matches[1] will contain the first captured group, which in this case is your parameter (which now allows for multiple characters). Of course, you could also adjust you getSnippet function to read the id from the $matches array instead of redirecting through the replaceCallback.
But this approach here is slightly more flexible, as it allows you to redirect to multiple functions. Just as an example, if you changed the regex to #\[(getSnippet|otherFunction)\((\w+)\)\]# then you could find two different functions, and replaceCallback could find out the name of the function in $matches[1] and call the function with the parameter $matches[2]. Like this:
function getSnippet($id) {
   ...
}

function otherFunction($parameter) {
   ...
}

function replaceCallback($matches) {
    return $matches[1]($matches[2]);
}

$string = preg_replace_callback(
    '#\[(getSnippet|otherFunction)\((\w+)\)\]#',
    'replaceCallback',
    $string
);

It really depends on where you want to go with this. The important thing is, there is no way of processing an arbitrary parameter in a replacement without using preg_replace_callback.


Q:

What's the difference between Observable and UrlTree?

I'm implementing a canActivate guard for one of my app components.
Based on the documentation, both UrlTree and Observable<UrlTree> are valid return types.
I understand that by wrapping 'a thing' into an observable would make the thing asynchronous, but I don't understand the difference in the router/routing context.
What are the differences between UrlTree and Observable<UrlTree> in terms of how router handles them?
When do you use one over the other?
I assume the same reasonings could also apply to <boolean> and Observable<boolean>
UrlTree version:
export class myGuard implements CanActivate {
  constructor(private router: Router) {}
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.router.parseUrl('newRoute');
  }
}

Observable version:
import { of } from 'rxjs';
export class myGuard implements CanActivate {
  constructor(private router: Router) {}
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return of(this.router.parseUrl('newRoute'));
  }
}

I've tried both versions, and both work fine in dev environment.

A:

The difference is just how the guard treats the response type... if it’s an observable, it subscribes and uses the value of the subscription to make a routing decision. If it’s not an observable, it just uses the value returned to make the decision. It’s for facilitate but not force an async function for your guard.
Use an observable when your decision is made based on something async... like a subject value or an http request or something.  Use a non observable when your decision made based upon something synchronous, like a localStorage value or something.


Q:

Why is 10 considered the default value for k-fold cross-validation?

I understand very well what k-fold cross-validation is. In my studies, and at work, I've always heard something along the lines of:

We most often use k=10 because evidence shows it's the best value for k. Smaller values don't give as good estimates, and larger values don't provide much better results either.

I intuitively can wrap my head around this. However, I cannot seem to find any research that went into declaring k=10 as the default. How would one go on to prove that 10 is the best value?
I understand the effects of using a smaller k versus a larger k in terms of bias. But why is it 10? And no 5 or 20? How could one end up on the number 10?

A:

The statement:

We most often use k=10 because evidence shows it's the best value for k. Smaller values don't give as good estimates, and larger values don't provide much better results either.

Is just categorically false. The reason people default to K=10 is because they don't know how changing K effects their estimates of the generalization error and they (like you) heard somewhere along the line that K=10 was good.
To understand what makes a good value of K (and whether or not K=10 is in fact better than say K=9 or K=11) you need to understand what changing this value has on your estimate.
As K decrease the bias in your estimate increases. This is because with lower values of K you are training on less data. For example K = 2 trains on only half the data, thus you will have a pessimistic bias in your estimate since you've decreased the amount of data available for your model to learn from. K = 3 trains on two thirds of your data, more data available to train on, better performance.
It used to be thought that there was a bias/variance trade-off in that a decrease in K would cause a decrease in variance (to go along with your increased bias) and while this is partially true it does not always hold. Lower values of K will have lower variance due to the fact that your training sets are less correlated. Think of the extreme example where K = N (leave one out). All of the training sets will look extremely similar, meaning that the estimate you receive is highly dependent on the sample you have to train on. If you were to draw many samples from the population and estimate error using leave one out you would have large variance in your estimates because of the variance between samples. This was the original reasoning for believing there existed a bias/variance trade-off with the choice of K.
However, this post outlines that this is not the case and that there is no universal truth as to what happens to the variance as K increases or decreases. Some studies show the variance increases with K, some show it decreases with K.
https://stats.stackexchange.com/questions/61783/bias-and-variance-in-leave-one-out-vs-k-fold-cross-validation/357749#357749
The other thing to consider is computational complexity. If you are dealing with datasets with millions of records it may be infeasible to use a very large value of K, especially if you are doing nested and/or repeated cross validation. So many people make their choice of K based simply on time to compute.

A:

Excerpt from ESL -

Ideally, if we had enough data, we would set aside a validation set and use
  it to assess the performance of our prediction model. Since data are often
  scarce, this is usually not possible. To finesse the problem, K-fold cross-validation uses part of the available data to fit the model

So, key goal is to get the variance of full data and at the same time get the validation set.
What it means -
K should be chosen in such a way that the training data has sufficient variance to enable the learning.So should be the variance in Validation data
Let's see this table for two cases. % is the portion of validation data in each case -
\begin{array} {|r|r|}
\hline
 &k=5 &k=10 &k=15 &k=20\\
\hline
I\ have\ Enough\ data &\color{green}{20\%}  &\color{red}{10\%} &\color{red}{6.5\%} &\color{red}{5\%}\\
\hline
Not\ Enough\ Data &\color{red}{20\%}  &\color{green}{10\%} &\color{red}{6.5\%} &\color{red}{5\%}\\
\hline
\end{array}
Enough data case - 10% or less might not provide enough variance into the Training set.
Not Enough data - 20% Validation set might reduce the size of the Training set below the desired level.
So, I think both 20% and 10% will work for respective cases. But generally, K-Fold doesn't have much use when we have enough data. So, what remains is 10%.
Needless to say -
The best value will always a hyper-parm. But we humans prefer is to deal in a multiple of 5, 10, Or 8,16, etc. Otherwise 9,11,10,22 can be equally good.
Reference -
7.10.1 K-Fold Cross-Validation from ESL


Q:

what does this mean in C int (*ptr[2])[4];

I want to know what is the meaning of the definition
int (*ptr[2])[4];

If i print the size of "ptr", it displays 16.
Also on my machine size of integer pointer is giving 8, where as size of integer is 4.
If i redifine ptr as ,
int (*ptr[2]); then also, size of ptr is 16.

so questions are

what is the meaning of definition int (*ptr[2])[4];
How do i initialize ptr?

A:

Use the right-left rule to read such declarations.
int (*ptr[2])[4] is an array of 2 pointers to arrays of 4 integers.

If i print the size of "ptr", it displays 16. Also on my machine size of integer pointer is giving 8

This is because ptr is an array of 2 pointers.


Q:

why is or not working for me in python?

this is my code:
for count in range(NOI):
        ig=input("enter a GTIN code: ")
        while ig!=("21356797"):
                print("incorrect")
                ig=input("enter a GTIN code: ")
                count =count+1

and this is the output:
21356797

13246785

31325974

45689413

34512340

56756777

how many items do you want to buy?: 1
enter a GTIN code: 21356797
>>>

which is what i want. However once i put in OR in my while loop, i can't get it to work like the first part:
while ig!=("21356797" or "13246785"):
            print("incorrect")
            ig=input("enter a GTIN code: ")
            count =count+1

and this is the output:
how many items do you want to buy?: 1
enter a GTIN code: 13246785
incorrect
enter a GTIN code: 21356797
>>>

A:

Your test:
ig!=("21356797" or "13246785")

evaluates the or condition first, returning the first "truthy" value. As such, it's exactly equivalent to:
ig!= "21356797"

since "21356797" is truthy.
You want a containment test:
ig not in ("21356797", "13246785")

or two sequential != tests and-ed together:
ig != "21356797" and ig != "13246785"
# Equivalent to:
not (ig == "21356797" or ig == "13246785")

The containment test scales to a larger set of values more cleanly, and as long as all the values are string literals, will be equally efficient (CPython caches the constant tuple of literals).


Q:

phar exclude directories when creating tar archive

I want to create a tar archive in a PHP script using the built-in PharData class.
I want the tar archive to represent a directory so I thought of using PharData::buildFromDirectory() to do that. Unfortunately the directory also is a git repository and has a .git folder in it which is much bigger than the directory itself.
So I need to remove that .git directory (ideally also the .idea directory...) from the archive because it would bloat it unnecessarily.
What I tried so far:

Using a regular expression to filter the directory out:
$archive->buildFromDirectory("..", "@^(?!.git).+@");

Which didn't work.
Using PharData::delete(), but unfortunately that seems to only delete a file and not a directory.

So, what is the best way to do what I want?

A:

The problem with your regex is that the full path of the file gets matched, not only the directory (basename). Thus you cannot filter out the .git directory itself.
Using a character class negation ([^.][^g][^i][^t]) does also not help because there are parts of the path that do match this regex, so the path matches anyway.
This means you can use positive matches only.

You could use Phar::buildFromIterator and then use  RecursiveFilterIterator to filter out the files.
There you can define your own matching method that filters correctly.


Q:

Details about what the As<>() method does in AutoMapper

I have done a fair amount of Googling and I have looked through the AutoMapper wiki and I cannot find a definition of what the As<> method does in AutoMapper.
I have some guesses.  I have played with it a bit.  But I feel like I need to see some documentation.
I think that the name of the method is too commonplace a word for effective googling.
If anyone knows where the docs are on this method (or knows the ins-and-outs of it) please post it.

A:

It is mapping redirection. The following test demonstrates it:
[TestFixture]
public class DestinationTypePolymorphismTest
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class CustomerStubDTO
    {
        public int Id { get; set; }
    }

    public class CustomerDTO : CustomerStubDTO
    {
        public string Name { get; set; }
    }

    public class Order
    {
        public Customer Customer { get; set; }
    }

    public class OrderDTO
    {
        public CustomerStubDTO Customer { get; set; }
    }

    [Test]
    public void Mapper_Should_Allow_Overriding_Of_Destination_Type()
    {
        var order = new Order() { Customer = new Customer() { Id = 1, Name = "A" } };
        Mapper.CreateMap<Order, OrderDTO>();
        Mapper.CreateMap<Customer, CustomerDTO>();
        Mapper.CreateMap<Customer, CustomerStubDTO>().As<CustomerDTO>();
        var orderDto = Mapper.Map<Order, OrderDTO>(order);

        var customerDto = (CustomerDTO)orderDto.Customer;
        Assert.AreEqual("A", customerDto.Name);
        Assert.AreEqual(1, customerDto.Id);

    }

}


Q:

ASP.NET MVC Mapping Route Config Issue

I realize there are plenty of questions like this on SO but none of the solutions seem to work for me, which is probably because I'm missing something simple that I don't know of. In my application, I added a controller called ErrorController with a view called Error.cshtml. The controller looks like this:
public class ErrorController : Controller
{
    public ActionResult Index(string errorMessage)
    {
        ViewBag.Error = errorMessage;
        return View();
    }
}

Now let's say I want to redirect to this action from a different controller. I was able to achieve that using
public ActionResult DoStuff(MyModel model)
{
    return RedirectToAction("", "Error", new { errorMessage = "SomeError" });
}

When redirect is called, I notice that the parameter is being passed as a query string:
/Error?errorMessage=SomeError

I would like to be able to pass the parameter as a route value, so my URL looks like
/Error/SomeError

So I added the following mapping to my RouteConfig.cs file:
routes.MapRoute(
  name: "Test",
  url: "{controller}/{action}/{errorMessage}",
  defaults: new { controller = "Error", action = "Index", errorMessage = "defaultErrorMessageTest" }
);

But it doesn't work. When I try to invoke the method with a URL like /Error/HelloWorld I get a yellow-screen error that says the resource cannot be found. Am I missing something here?

A:

Change
return RedirectToAction("", "Error", new { errorMessage = "SomeError" });

to
return RedirectToAction("Index", "Error", new { errorMessage = "SomeError" });

And then change your route to:
routes.MapRoute(
    name: "Test",
    url: "error/{errorMessage}",
    defaults: new { controller = "Error", action = "Index", errorMessage = "defaultErrorMessageTest" }
);

Also, make sure this route comes above your default route.


Q:

Different behavior for unique_ptr with move?

I have code as following
std::vector<std::unique_ptr<int>> v;
std::unique_ptr<int> a(new int(0));
std::unique_ptr<int>& b = a;
v.insert(v.begin(), std::move(b)); //ok

However if I add const in the third statement
const std::unique_ptr<int>& b = a;
v.insert(v.begin(), std::move(b)); //Compiler error, cannot access ptr private member

Why does the compiler show it cannot access private member of the unique pointer other than cannot convert const to non-const?  Thanks.

A:

You cannot move a const object. Moving means altering the state of the object you moved from (of whatever type that object is), and declaring it as const makes a promise that you won't alter that state. Thus, moving a const object is a contradiction in terms.
Although the expectation of being able to move a const object may indeed have some kind of justification (for instance, you may want the object to be const as long as you use it, and then get rid of it when you're done and transfer its guts rather than copying it - which is btw impossible with a unique_ptr), actually allowing this would have a number of very impractical semantic consequences (for instance, it would allow swapping two const objects).
Thus, even though the language does technically allow moving from a const object (move constructors accepting a const RRef are legal), no type of the Standard Library actually gives you that possibility, including unique_ptr, and you should not write any UDT that does.
Conceptually, it is really important to think of moving as a state-altering operation, which is not compatible with the const modifier.


Q:

SQL Query to get column result conditionally based on column value

Below is my SQL Table,

how do i get the result from this table as pack_cd and date which is not null. e.g.

from SQL Table i want to get PACK_CD and date as

ETDT if its NOT NULL
PPDT if ETDT IS NULL and PPDT is NOT NULL
PDT if ETDT IS NULL and PPDT is NULL and PDT is NOT
NULL

A:

Use COALESCE:
SELECT
    PACK_CD,
    DATE = COALESCE(ETDT, PPDT, PDT)
FROM [YourTable]

If you want to show only those rows with NULL column, just add a WHERE clause:
WHERE
    ETDT IS NULL
    OR PPDT IS NULL
    OR PDT IS NULL


Q:

Installing Ubuntu on External Hard Drive - UEFI

I want to install Ubuntu on a 1TB External Hard Drive, while the internal hard drive already has Windows 10 (OEM) pre-installed on it. So, that I could use both the OS's, by deciding which one to use from the boot menu.
I did some research and found two way of doing this.

Method 1:  (How do I install Ubuntu to a USB key?)

Remove the Internal Hard Drive and connect the External Hard Drive via USB
Disable Secure Boot in UEFI Firmware
Use bootable Ubuntu USB and install the normal way
Then reconnect the internal hard drive

Method 2: (How to install Ubuntu on portable external Hard Drive?)

Disable Secure Boot in UEFI Firmware and Fast Startup in Windows
Connect External Hard Drive via USB
Use bootable Ubuntu USB and choose "Something Else" in setup
Point the "Boot Loader Installation" to the external hard drive (sdb)
Create / and swap area (some people also create /boot) on external hard drive (sdb)
Once Ubuntu is installed, I'll be able to choose which OS to boot into from the Boot Menu

Problems are:

Would disabling secure boot render my Windows installation unusable?

Trying to disable Secure Boot, from UEFI Firmware settings, throws the following warning: Attention! Changing this setting may prevent your operating system from booting or require a reinstall. Are you sure you would like to continue?
Microsoft Secure Boot documentation highlights this warning too.

Would following Method 2 entail further complications like manually creating an EFI partition and manipulating grubx64.efi and shimx64.efi, EDIT: but wouldn't this manipulation cause problems when Secure Boot is turned back on (signature of boot loader might change)?

See this: Installing Ubuntu onto an external hard drive

Which Method should I go with then?

A:

I believe the installer now works with secure boot on. If not, the installed Ububtu will. So, turn secure boot back on after installing.
If you want the external to be bootable in any computer, then you have to make an EFI partition on it. Select something else for install to be sure the installer uses the external ESP not the internal. The EFI partition should be 500 MB, formated FAT, and flagged ESP.
If it will only be used on this computer, then using the internal drives EFI partition is preferable. Grub will require that the drive be connected so it can find it's config file. Though if you use the previous setup, it can be made so the computer automatically boots linux when the drive is connected or windows when not by setting boot order.
a separate /boot partition is unnecessary, and can cause problems if made too small
Edit:

as per Microsoft Secure Boot Documentation --- After disabling Secure Boot and installing other software and hardware, it may be difficult to re-activate Secure Boot without restoring your PC to the factory state

What this means is:
If you turn off secure boot in order to install low level software (such as drivers) in Windows, then turn secure boot on, Windows may not boot if the software is not signed by Microsoft.


Q:

What is app.config for?

Settings.settings generates Settings.Designer.cs which presumably generates app.config which then is copied to output directory as Foo.exe.config. When I distribute the application without the config file, nothing bad seems to happen. So, what is that file for?

A:

If you don't have the config file, it uses the default values from the designer. However, the config file allows users/administrators to easily change settings - such as the server you talk to, themes, etc. If you don't have the file, where would you expect those settings to be stored?
You can have per-user settings as well as per-application settings, which are stored in different locations.

A:

Application configuration files contain settings specific to an application. This file contains configuration settings that the common language runtime reads (such as assembly binding policy, remoting objects, and so on), and settings that the application can read.

A:

The config file is optional, if it does not exist environments such as ASP.NET will fall back to the machine.config file stored in the .NET system directories to get machine wide defaults.
If you actually add code to your app to retrieve settings from the config file (say using the ConfigurationManager class) and it does not exist, you will receive null values.
That is why it is important to check for this siutation and have your application make it's own decision on how/if to continue.


Q:

How to debug SEGV_ACCERR

I have an app that streams video using Kickflip and ButterflyTV libRTMP
Now for 99% percent of the time the app is working ok, but from time to time I get a native segmentation fault that I am not able to debug, since messages are too cryptic:
01-24 10:52:25.576 199-199/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
01-24 10:52:25.576 199-199/? A/DEBUG: Build fingerprint: 'google/hammerhead/hammerhead:6.0.1/M4B30Z/3437181:user/release-keys'
01-24 10:52:25.576 199-199/? A/DEBUG: Revision: '11'
01-24 10:52:25.576 199-199/? A/DEBUG: ABI: 'arm'
01-24 10:52:25.576 199-199/? A/DEBUG: pid: 14302, tid: 14382, name: MuxerThread  >>> tv.myapp.broadcast.dev <<<
01-24 10:52:25.576 199-199/? A/DEBUG: signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x9fef1000
01-24 10:52:25.636 199-199/? A/DEBUG: Abort message: 'Setting to ready!'
01-24 10:52:25.636 199-199/? A/DEBUG:     r0 9c6f9500  r1 9c6f94fc  r2 9fee900c  r3 00007ff4
01-24 10:52:25.636 199-199/? A/DEBUG:     r4 9fee9010  r5 9fef0ffd  r6 00007ff1  r7 9fef0d88
01-24 10:52:25.636 199-199/? A/DEBUG:     r8 cfe40980  r9 9e0a6900  sl 00007ff4  fp 9c6f94fc
01-24 10:52:25.636 199-199/? A/DEBUG:     ip 9c6f9058  sp 9c6f94dc  lr 000000e9  pc b3a33cb6  cpsr 800f0030
01-24 10:52:25.650 199-199/? A/DEBUG: backtrace:
01-24 10:52:25.651 199-199/? A/DEBUG:     #00 pc 00004cb6  /data/app/tv.myapp.broadcast.dev-2/lib/arm/librtmp-jni.so
01-24 10:52:25.651 199-199/? A/DEBUG:     #01 pc 00005189  /data/app/tv.myapp.broadcast.dev-2/lib/arm/librtmp-jni.so (rtmp_sender_write_video_frame+28)
01-24 10:52:25.651 199-199/? A/DEBUG:     #02 pc 00005599  /data/app/tv.myapp.broadcast.dev-2/lib/arm/librtmp-jni.so (Java_net_butterflytv_rtmp_1client_RTMPMuxer_writeVideo+60)
01-24 10:52:25.651 199-199/? A/DEBUG:     #03 pc 014e84e7  /data/app/tv.myapp.broadcast.dev-2/oat/arm/base.odex (offset 0xa66000) (int net.butterflytv.rtmp_client.RTMPMuxer.writeVideo(byte[], int, int, int)+122)
01-24 10:52:25.651 199-199/? A/DEBUG:     #04 pc 014dbd55  /data/app/tv.myapp.broadcast.dev-2/oat/arm/base.odex (offset 0xa66000) (void io.kickflip.sdk.av.muxer.RtmpMuxerMix.writeThread()+2240)
01-24 10:52:25.651 199-199/? A/DEBUG:     #05 pc 014d8c41  /data/app/tv.myapp.broadcast.dev-2/oat/arm/base.odex (offset 0xa66000) (void io.kickflip.sdk.av.muxer.RtmpMuxerMix.access$000(io.kickflip.sdk.av.muxer.RtmpMuxerMix)+60)
01-24 10:52:25.651 199-199/? A/DEBUG:     #06 pc 014d819f  /data/app/tv.myapp.broadcast.dev-2/oat/arm/base.odex (offset 0xa66000) (void io.kickflip.sdk.av.muxer.RtmpMuxerMix$1.run()+98)
01-24 10:52:25.651 199-199/? A/DEBUG:     #07 pc 721e78d1  /data/dalvik-cache/arm/system@framework@boot.oat (offset 0x1ed6000)

Again, in a 2 hour stream this might not ever happen or it might happen 10 minutes into the stream. It is super hard to debug because I cannot force the bug to happen.
Is there any way to improve the debugging information I get? What exactly does SEGV_ACCER mean? I've read that this "means you tried to access an address that you don't have permission to access." but I am unsure as what that means, as I can stream for hours without the bug happening.
Is there any way to catch the signal and just continue?
EDIT: to add more information, this is the part of the native library where the app crashes (found using ndk-stack):
JNIEXPORT jint JNICALL
Java_net_butterflytv_rtmp_1client_RTMPMuxer_writeVideo(JNIEnv *env, jobject instance,
                                                       jbyteArray data_, jint offset, jint length,
                                                       jint timestamp) {
    jbyte *data = (*env)->GetByteArrayElements(env, data_, NULL);
    jint result = rtmp_sender_write_video_frame(data, length, timestamp, 0, 0);
    (*env)->ReleaseByteArrayElements(env, data_, data, 0);

    return result;
}

int rtmp_sender_write_video_frame(uint8_t *data,
                                  int size,
                                  uint64_t dts_us,
                                  int key,
                                  uint32_t abs_ts)
{

    uint8_t * buf;
    uint8_t * buf_offset;
    int val = 0;
    int total;
    uint32_t ts;
    uint32_t nal_len;
    uint32_t nal_len_n;
    uint8_t *nal;
    uint8_t *nal_n;
    char *output ;
    uint32_t offset = 0;
    uint32_t body_len;
    uint32_t output_len;

    buf = data;
    buf_offset = data;
    total = size;
    ts = (uint32_t)dts_us;

    //ts = RTMP_GetTime() - start_time;
    offset = 0;

    nal = get_nal(&nal_len, &buf_offset, buf, total);

(...)

}

static uint8_t * get_nal(uint32_t *len, uint8_t **offset, uint8_t *start, uint32_t total)
{
    uint32_t info;
    uint8_t *q ;
    uint8_t *p  =  *offset;
    *len = 0;

    if ((p - start) >= total)
        return NULL;

    while(1) {
        info =  find_start_code(p, 3);

        if (info == 1)
            break;
        p++;
        if ((p - start) >= total)
            return NULL;
    }
    q = p + 4;
    p = q;

    while(1) {
        info =  find_start_code(p, 3);

        if (info == 1)
            break;
        p++;
        if ((p - start) >= total)
            //return NULL;
            break;
    }

    *len = (p - q);
    *offset = p;
    return q;
}

static uint32_t find_start_code(uint8_t *buf, uint32_t zeros_in_startcode)
{
    uint32_t info;
    uint32_t i;

    info = 1;
    if ((info = (buf[zeros_in_startcode] != 1)? 0: 1) == 0)
        return 0;

    for (i = 0; i < zeros_in_startcode; i++)
        if (buf[i] != 0)
        {
            info = 0;
            break;
        };

    return info;
}

Crash happens at buf[zeros_in_startcode] in find_start_code. I have removed a few android_log lines as well (dont think this matters?).
To my understanding, this buffer should be accessible, it makes no sense that it crashes only "sometimes".
PS. this is where I call the native code from Java:
private void writeThread() {

       while (true) {

           Frame frame = null;
           synchronized (mBufferLock) {
              if (!mConfigBuffer.isEmpty()) {
                   frame = mConfigBuffer.peek();
               } else if (!mBuffer.isEmpty()) {
                   frame = mBuffer.remove();
               }
               if (frame == null) {
                   try {
                       mBufferLock.wait();
                   } catch (InterruptedException e) {
                   }
               }
           }

           if (frame == null) {
               continue;
           } else if (frame instanceof Sentinel) {
               break;
           }

           int writeResult = 0;

           synchronized (mWriteFence) {
               if (!mConnected) {
                   debug(WARN, "Skipping frame due to disconnection");
                   continue;
               }

               if (frame.getFrameType() == Frame.VIDEO_FRAME) {
                   writeResult = mRTMPMuxer.writeVideo(frame.getData(), frame.getOffset(), frame.getSize(), frame.getTime());
               } else if (frame.getFrameType() == Frame.AUDIO_FRAME) {
                   writeResult = mRTMPMuxer.writeAudio(frame.getData(), frame.getOffset(), frame.getSize(), frame.getTime());

               }

               if (writeResult < 0) {
                       mRtmpListener.onDisconnected();
                       mConnected = false;
               } else {
                   //Now we remove the config frame, only if sending was successful!
                   if (frame.isConfig()) {
                       synchronized (mBufferLock) {
                           mConfigBuffer.remove();
                       }
                   }
               }
           }

       }

   }

Note that the crash happens even when I dont send audio at all.

A:

"You can store the data in a byte[]. This allows very fast access from
  managed code. On the native side, however, you're not guaranteed to be
  able to access the data without having to copy it."

See https://developer.android.com/training/articles/perf-jni.html
Analysis
Some musings and things to try:

The code where it falls over is very generic, so probably no bug there
It must be the frame data has been removed/damaged/locked/moved
Has the Java garbage collector removed OR relocated the data ?
You could write detailed debug to a file, overwriting it on every
frame, so you only have a small log with the last debug info.
send a local copy of the frame variable info (using ByteBuffer) to mRTMPMuxer.writeVideo
Unlike regular byte buffers,in ByteBuffer the storage is not allocated on the managed heap, and can always be accessed directly from native code.

Implementation

//allocates memory from the native heap
ByteBuffer data = ByteBuffer.allocateDirect(frame.getData().length);
data.clear();
//System.gc();
//copy data
data.get(frame.getData(), 0, frame.getData().length);
//data = (frame.getData() == null) ? null : frame.getData().clone();
int offset  = frame.getOffset();
int size    = frame.getSize();
int time    = frame.getTime();
writeResult = mRTMPMuxer.writeVideo(data , offset, size, time);

JNIEXPORT jint JNICALL
Java_net_butterflytv_rtmp_1client_RTMPMuxer_writeVideo(
    JNIEnv *env,
    jobject instance,
    jobject data_, //NOT jbyteArray data_,
    jint offset,
    jint length,
    jint timestamp)
{
    jbyte *data = env->GetDirectBufferAddress(env, data);//GetDirectBufferAddress NOT GetByteArrayElements
    jint result = rtmp_sender_write_video_frame(data, length, timestamp, 0, 0);
    //(*env)->ReleaseByteArrayElements(env, data_, data, 0);//????
    return result;
}

Debugging

Some code from SO Catching exceptions thrown from native code:
    static uint32_t find_start_code(uint8_t *buf, uint32_t zeros_in_startcode){
    //...
    try {
        if ((info = (buf[zeros_in_startcode] != 1)? 0: 1) == 0) return 0;//your code
    }
    // You can catch std::exception for more generic error handling
    catch (std::exception e){
        throwJavaException (env, e.what());//see method below
    }
    //...

Then a new method:
    void throwJavaException(JNIEnv *env, const char *msg)
    {
     // You can put your own exception here
     jclass c = env->FindClass("java/lang/RuntimeException");
     if (NULL == c)
     {
         //B plan: null pointer ...
         c = env->FindClass("java/lang/NullPointerException");
     }
     env->ThrowNew(c, msg);
    }
}

Don't get too hung up on SEGV_ACCERR, you have a segmentation fault,SIGSEGV (caused by a program trying to read or write an illegal memory location, read in your case).
From siginfo.h:
SEGV_MAPERR means you tried to access an address that doesn't map to anything.
SEGV_ACCERR means you tried to access an address that you don't have permission to access.
Other
This may be of interest:

Q: I noticed that there was RTMP support. But a patch which remove
  RTMP had been merged. Q: Could you tell me why ? A: We don't
  think RTMP serves the mobile broadcasting use case as well as HLS,
  A: and so we don't want to dedicate our limited resources towards
  supporting it.

 see: https://github.com/Kickflip/kickflip-android-sdk/issues/33
I suggest you register an issue with:
https://github.com/Kickflip/kickflip-android-sdk/issues
https://github.com/ButterflyTV/LibRtmp-Client-for-Android/issues


Q:

How to add blank records for grouping based on formula in Crystal Reports

I have one table and group the records using formula, based on a string field which is formed as time (HH:mm:ss)
Formula is as followings:
select Minute (TimeValue ({MASTER.Saat}))
case 0 to 14: ReplicateString ("0", 2-len(TOTEXT(Hour (TimeValue ({MASTER.Saat})),0))) & TOTEXT(Hour (TimeValue ({MASTER.Saat})),0) & ":00:00"
case 15 to 29: ReplicateString ("0", 2-len(TOTEXT(Hour (TimeValue ({MASTER.Saat})),0))) & TOTEXT(Hour (TimeValue ({MASTER.Saat})),0) & ":15:00"
case 30 to 44: ReplicateString ("0", 2-len(TOTEXT(Hour (TimeValue ({MASTER.Saat})),0))) & TOTEXT(Hour (TimeValue ({MASTER.Saat})),0) & ":30:00"
case 45 to 59: ReplicateString ("0", 2-len(TOTEXT(Hour (TimeValue ({MASTER.Saat})),0))) & TOTEXT(Hour (TimeValue ({MASTER.Saat})),0) & ":45:00"

Actually, grouping works fine but my problem is that if there is no data in the table for a period, I can not show that in the report.
As an example;
Let my data has 5 records as following:

11:01:03
11:16:07
11:28:16
12:18:47
12:22:34

My report gives the result as following:

Period | Total Records
11:00:00 | 1
11:15:00 | 2
12:15:00 | 2

In this situation, I can not show the periods (which are missing in the table) as 0 for Total Records. I have to show as follows:

Period | Total Records
11:00:00 | 1
11:15:00 | 2
11:30:00 | 0
11:45:00 | 0
12:00:00 | 0
12:15:00 | 2

Thanks for all suggestions.

A:

You can't group something that's not there. One way to solve this is to use a table that provides all of your intervals you want to look at (called a date, time or number table).
For your case create a table that contains all your period values (24x4). join the records you want to count to this table. In Crystal Reports group by the period values - your result set will contain the periods without any joined records - you can detect this and output a 0.
You may want to look a this question, it is similar to yours.


Q:

Text (command line) based Java IDE

Probably question title might looks strange for you, but I'll try to explain.
I do looking alternative of desktop eclipse, ideally what I need is to edit sources directly on my linux dev-server. On dev server I don't have any xwindows just command line. So I would like to login to server using Putty, develop, build, run, commit changes to source control system.
From text editor I would need:

syntax highlight
autocomletion (at least basic)
quick navigation trough project files
basic refactoring: change class name? move class to other
package,change method signature
run build without need to leave editor window
run svc/git commands without need to leave editor window

From the first glance emancs seems to be what I need, but I don't sure.
Thanks.

A:

I think that you approach is not good. Developing directly on your devel server is not a good practice. But it's not the question...
Personally, my favorite text editor for programming is emacs. I'm also a Java developer. I'm using Eclim. According to the Eclim Website :

The primary goal of eclim is to bring Eclipse functionality to the Vim editor. The initial goal was to provide Eclipse’s java functionality in vim, but support for various other languages (c/c++, php, python, ruby, css, html, xml, etc.) have been added and several more are planned.

As I said, I use mainly Emacs. So, I'm using emacs-eclim (the Vim plugin is very cool  and advanced) :

Eclim is an Eclipse plugin which exposes Eclipse features through a server interface. When this server is started, the command line utility eclim can be used to issue requests to that server.
Emacs-eclim uses the eclim server to integrate eclipse with emacs. This project wants to bring some of the invaluable features from eclipse to emacs.

If you use Emacs, you can also use the JDEE mode. Personally, I don't like this mode : too complicated, not enough maintained.

A:

Sandro's answer is a good one for a true command-line tool. On unix, emacs and vim are really the only games in town when it comes to sophisticated command-line editors, so a good Java mode for one of those is what you want.
However, i want to point out that even if the server doesn't have an X server, you can still run graphical programs on it - they just have to connect to an X server on another machine, such as your desktop. Sounds weird, but that is actually the whole point of X windows: it was originally developed so that people could run programs on powerful time-shared machines, and access them from cheap, dumb graphical terminals (this was back in the early 80s when people thought that was a good idea).
These days, the easiest way to do this is to use SSH to connect to the remote machine, telling it to enable X11 forwarding. With the OpenSSH command-line SSH, this is as simple as adding the -X flag; i'm not sure how you do it with PuTTY, but i'm sure it's possible. Once you've logged in with X11 forwarding enabled, you can simply run X clients (such as Eclipse or IDEA), and they will connect to your local X server.
Oh - you will need a local X server. On Windows, you can install Xming
All of this takes a bit of work (although not a lot!), so if you just want to do occasional hacking, my all means go with Eclim. But if you are planning on doing a lot of remote development, and you don't have a lot of affection for curses interfaces, this might be the most comfortable route.


Q:

How Do I Configure ProFTP for Website Update?

I am running Ubuntu Server 9.10 with ProFTPD, and I also have Webmin.
I have DNS setup for 3 domains, mail setup for 3 domains, as well as Apache2 setup for those domains. They work great.
Now I want to give FTP access for an incoming user, but point them to /var/www/[domain] and have them come in as something like user "ftpuser" but want this to translate to user "www-data" so that web permissions will be correct.
What is the technique to do this?

A:

Groups and SGID.  user1 would have group membership in www-data and you would set everything group writable under [domain].  Set user1's home directory to /var/www/[domain].  You would also want to set the SGID on [domain] and all directories under it, which would cause permissions to be inherited. (g+s)
Be aware, user1 would have access to all Web content.  You could use a different group to limit the scope of the access.
SSH (SFTP/scp) is recommended for user authentication as opposed to FTP, as the authentication credentials will be transmitted in plaintext with FTP.


Q:

What does "I called him mine" mean?

In a popular song, "My Baby Shot Me Down", the text contains this expression:

When I grew up I called him mine

What does it mean?

A:

Remember when we were kids?

The lyrics of the song Bang Bang, by Nancy Sinatra, suggest that she became the steady girlfriend of her childhood friend and eventually married him, but the pattern of their relationship never changed from their childish game:

I was five and he was six
  We rode on horses made of sticks
  He wore
  black and I wore white
  He would always win the fight
Chorus:
  Bang bang, he shot me down
  Bang bang, I hit the ground
  Bang bang, that
  awful sound
  Bang bang, my baby shot me down
Seasons came and changed the time
When I grew up, I called him mine
  He
  would always laugh and say
  "Remember when we used to play?"
Chorus:
Music played and people sang
  Just for me the church bells rang
Now
  he's gone, I don't know why
  And 'till this day, sometimes I cry
  He
  didn't even say goodbye
  He didn't take the time to lie
Chorus:


Q:

Are engine casings expected to contain turbofan blade fragments?

On Southwest 1380, initial indications are that a fragment of the engine blade pierced the engine casing, which then hit the airplane window (or perhaps a part of the casing did). According to the BBC,

Mr Sumwalt also said a casing on the engine was meant to contain any parts that come loose but, due to the speed at impact, the metal was able to penetrate the shell.

Is this an reasonably expected containment failure?  Or is the failure to contain surprising to industry experts?

A:

We don't yet know how or why the engine casing failed to contain the fan blade on Southwest 1380.
But yes: Not only are the engines designed to contain blade failures at fan red-line speeds, but they are also required by 14 CFR 33.94 to confirm they do, typically via destructive "blade-off testing."
(There are a number of good videos of this testing online: Search "turbine blade fail test" or "blade-out engine test.")
As noted here "fan blade-out" failures in the real world are virtually unseen.  (Turbine blade failures are relatively common and can even go unnoticed until major service teardowns.)


Q:

Java Game using Random Numbers

I have a java program where the computer will decide which player goes first and pick random number to remove from an array. As the player remove the number, the array will decrease. All of this will be done using random. But when I run my  code, its not what I expect it to be. May I know where did I went wrong?
This is my code:
[The Class]
public class StickBag {

    private int numOfSticks;

    public StickBag(int numOfSticks)
    {
        this.numOfSticks = numOfSticks;
    }

    public int getNumOfSticks() {
        return numOfSticks;
    }

    public void setNumOfSticks(int numOfSticks) {
        this.numOfSticks = numOfSticks;
    }

    public int remove(int n)
    {
        numOfSticks = numOfSticks - n;
        return numOfSticks;
    }
}

[The Main]
public class StickGameApp {

    public static void main(String[] args) {

        StickBag s1 = new StickBag(25);

        System.out.println("Welcome to the game of sticks!");
        System.out.println("There are initially " + s1.getNumOfSticks() + " sticks on the board.");

        int minP = 1;
        int maxP = 2;
        int randP;

        int minN = 1;
        int maxN = 10;
        int randNum;

        randP = minP + (int)(Math.random()*(maxP));
        randNum = minN + (int)(Math.random()*(maxN));

        for (int i=0; i<10; i++)
        {
            if(s1.getNumOfSticks() > randNum)
            {
            System.out.println("Computer player " + randP + " choose " + randNum + " sticks ");
            s1.remove(randNum);
            }
            else
            {
                System.out.println("Computer player " + randP + " wants to choose " + randNum + " sticks but is unable to.");
                System.out.println("Computer player " + randP + " loses ");
            }
        }

    }
}

When I run the code, it display as follows:

Welcome to the game of sticks!
There are initially 25 sticks on the board.
Computer player 2 choose 6 sticks
Computer player 2 choose 6 sticks
Computer player 2 choose 6 sticks
Computer player 2 choose 6 sticks
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses
Computer player 2 wants to choose 6 sticks but is unable to.
Computer player 2 loses

But I want it to display like this:

Welcome to the game of sticks!
There are initially 25 sticks on the board.
Computer Player 1 chooses 5 sticks.
Computer Player 2 chooses 7 sticks.
Computer Player 1 chooses 7 sticks.
Computer Player 2 wants to choose 7 sticks but is unable to.
Computer Player 2, you lose.

May I know where did I went wrong?

A:

your mistake is simply you put the random number generator of player and computer randP and randNum before the for loop that running the game so the random number choosing will be executed only once.
your code should be :
for (int i=0; i<10; i++)
    {
     randP = minP + (int)(Math.random()*(maxP));
     randNum = minN + (int)(Math.random()*(maxN));
        if(s1.getNumOfSticks() > randNum)
        {
        System.out.println("Computer player " + randP + " choose " + randNum + " sticks ");
        s1.remove(randNum);
        }
        else
        {
            System.out.println("Computer player " + randP + " wants to choose " + randNum + " sticks but is unable to.");
            System.out.println("Computer player " + randP + " loses ");
        }
    }

}


Q:

How can I define in clojure a java class during runtime and instantiate it

I have tried to use gen-and-load-class from clojure.core and then use custom class loader to call defineClass with generated bytecode, but when I call
(foo.bar.MyClass.)

I'm getting
CompilerExceptionjava.lang.NoClassDefFoundError: Could not initialize class foo.bar.MyClass

UPDATE:
So I used deftype as suggested by @Elogent :
(defprotocol Struct
  (getX [this path] "Get value")
  (setX [this ^long value path] "Get value"))
(deftype Foo
  [
  ^{:tag long :unsynchronized-mutable true} a
  ^{:tag long :unsynchronized-mutable true} b
  ^{:tag long :unsynchronized-mutable true} c]
  Struct
  (getX
    [this [head & tail]]
    (let [field (condp = head
          'a a
          'b b
          'c c)]
      (if (empty? tail)
        field
        (getX field tail))))
  (setX
    [this value [head & tail]]

    (if (empty? tail)
        (condp = head
          (set! a (long value))
          (set! b (long value))
          (set! c (long value)))
        (condp = head
          (setX a value tail)
          (setX b value tail)
          (setX c value tail)))))

After AOT when I do javap Foo.class I got:
public final class struct.core.Foo implements struct.core.Struct,clojure.lang.IType {
  public static final clojure.lang.Var const__0;
  public static final java.lang.Object const__1;
  public static final clojure.lang.Var const__2;
  public static final java.lang.Object const__3;
  public static final clojure.lang.Var const__4;
  public static final clojure.lang.AFn const__5;
  public static final clojure.lang.AFn const__6;
  public static final clojure.lang.AFn const__7;
  public static final clojure.lang.Var const__8;
  public static final clojure.lang.Var const__9;
  public static final clojure.lang.Var const__10;
  public static final clojure.lang.Var const__11;
  public static final clojure.lang.Var const__12;
  long a;
  long b;
  long c;
  public static {};
  public struct.core.Foo(long, long, long);
  public static clojure.lang.IPersistentVector getBasis();
  public java.lang.Object setX(java.lang.Object, java.lang.Object);
  public java.lang.Object getX(java.lang.Object);
}

This is exactly what I need. Thank you @Elogent!

A:

Unless you absolutely need all the flexibility of a Java class, I would advise that you use deftype instead. As explained here, deftype gives you access to lower-level constructs such as primitive types and mutability in an idiomatic way.


Q:

Phrases to acknowledge being corrected in Mandarin

When I lived in China, I was often corrected for using grammar improperly or translating too literally. I don't think I ever learned a good response to this. I usually wanted to be courteous and convey that I understood and would use the correction in the future.
My response was usually "喔，知道了!" which I think of as "Got it!" but I think this feels a little brisk and unappreciative of what the person is saying. If I interpreted it literally, I would definitely think saying something like “I know!" is a little rude in English and might even indicate I'm disinterested in learning how to speak Mandarin properly. Does that phrase have any of that connotation for native speakers or is that just English?
I've also thought about saying "是这样吗?" or “是那样吗?" but I actually have no basis in knowing whether Chinese people say anything like this other than people in my family's dialect (Taishanese) saying this to roughly express "Oh really? That's how it is, huh?" Thinking back to my time in China, I almost feel that "是这样吗?" is a little skeptical and would be taking the person's correction for granted. On a grammatical basis, I am also not sure if the 吗 is needed or if I should even add "这样的" to the phrase.
Then later, I saw a video on the internet that used "原来如此" but the context was a comedy video so I don't even know if this is something people actually say in normal situations. It was translated as "So that's how it is" which is actually rather perfect for what I want to convey. Can anybody tell me how that phrase is usually used? I have learned 原来 before but I'ven ever seen 如此 and I have a hunch that it's derived from classical words/definitions, but I really don't know.
Basically I'm looking for a phrase that conveys these feelings:
1. "Thanks for correcting me, I appreciate it"
2. "Oh, I didn't know that before, I'll try to use it like that from now on"
3. Emphasizing the recent REALIZATION aspect of it, so that I might continue to mess up because I may not grasp their correction instantly -- again, I got the feeling people thought I was not at all conscientious about correcting myself, but I basically had a hard time showing people that I was still TRYING -- which is why 知道了！doesn't sound good to me because that sounds like I'm declaring INSTANT grasp of a correction.

A:

I would simply add 謝謝你 at the end to soften the tone.
我明白了，謝謝你。 I understand now, thank you.
原來如此，謝謝你。 Ah, so that's how it is, thank you.
"喔，知道了" can sound a little brisk and abrupt depending on your tone of voice. Adding 謝謝你 helps, but I would altogether use a different verb 明白, which is closer in meaning to "I understand now".

A:

You shouldn't worry about the 知道了 sounding rude as the English equivalent "I know! (you don't need to tell me that)".
That 了 there indicates a change of situation, so it's not quite "I know", but "I know now".
To soften the tone, you could add a 才 before it. 我才知道了! (Just now I got to know it!)
But I really tend to hear Chinese using 原来 to express that idea more often:
原来是这样！
原来如此 sound a bit too formal.


Q:

Capturing specific data from Twitch info?

So I have twitch follower data in the format:
20Hour Stream w/ @summit1g.
19,075 viewers on summit1g

Untitled Broadcast
6,392 viewers on Trick2g

Vinny || Metal Gear Solid 3: Snake Meeter + More
2,948 viewers on Vinesauce

Isaac Mastery - http://bit.ly/1JwGmnn - #1147
2,862 viewers on Lethalfrag

VIDYA GAEMZ STREAM???
1,554 viewers on Boogie2988

DREAM TEAM ~ 0/10 wins in a row! ~ 230 BR Wins ~ @sxyhxy ┌∩┐(ò_óˇ)
1,098 viewers on sxyhxy

I want to know if I can use Regexp to capture the viewer count, the person's channel name, as well as the title of their stream in three separate groups.
I have the following regex: ([^\n]+)\n([^\n]+)\n{2} which only captures the title and all the below info, but what I want is the viewer count and channel name from that specifically. An ideal capture output would be 20Hour Stream w/ @summit1g., 19,075, and summit1g as capture 1-3 respectively.
Is there any way to do this with just regex? Thanks!

A:

The following regex will capture what you what you want: (.+)\n([\d,]+).+on (\w+)


Q:

"Creerle" vs "Creerla"

Tengo una duda respecto al uso de "creerle" o "creerla". He escrito algo así:

-- Quiero pedirte disculpas.
   Recordando la noche anterior, a Martín le costó creerle.

Una persona que posiblemente tenga un dominio del idioma mucho mejor que el mío me ha sugerido cambiar "creerle" por "creerla". Sin embargo me suena muy poco natural, aunque es posible que la causa sea que mi español nativo es latinoamericano y el suyo es de España.
¿Es una de las dos formas claramente correcta, o es cuestión de preferencia o dialecto?

A:

Es cuestión de laísmo, leísmo (que también hay mucho en España) y loísmo.
Etimológicamente, sin duda el pronombre de acusativo femenino con función de complemento directo es la y el masculino es lo, mientras le es un pronombre de dativo (del latín illi) que desempeña la función de complemento indirecto, independientemente del género del sustantivo al que se refiere el pronombre, aunque en  oraciones impersonales se ha usado el dativo como complemento directo ("Se le cree desaparecido") desde los orígenes del castellano.
Quizás por ello, para complicar más las cosas, desde desde los primeros textos medievales castellanos se comenzó a emplear le también como acusativo masculino de persona y lo para el acusativo masculino de cosa, aunque esto no caló mucho en Andalucía, y por tanto, tampoco se extendió mucho por América, donde el leísmo puede ser más  bien por influencia de otras lenguas y aplicado de formas menos aceptadas.
Para terminar de enredarlo todo, no siempre está claro cuando un verbo requiere un pronombre como CD o CI. Los verbos llamados de «afección psíquica» como afectar o asustar y algunos otros admiten tanto el uso de los pronombres acusativos como dativos. En esto casos la elección depende de que el sujeto sea animado y el agente de la acción,en cuyo caso el complemento verbal suele considerarse directo y se  emplea el acusativo, o bien el si sujeto es inanimado o es una oración, que no puede ser agente directos de la acción, entonces el complemento se considera indirecto y se usan el dativo, aunque no siempre es así porque pueden intervenir otros factores.
Así, si asimilamos creer a un «verbo de percepción» o de «afección psíquica» donde la acción proviene de una persona (las cosas no piden disculpas), sería más adecuado el acusativo, pero no se sabe a quién se refiere el pronombre en el ejemplo. Por tanto;
Si cree a Juan debería ser creerlo, pero también sería aceptable creerle (y quizás considerada más culta en España).
Si cree a María, debería ser creerla.
Pero no está clara la premisa (que creer e sea un verbo de afección psíquica como asustar, ni de percepción como ver, ni que sea descabellado usar el dativo en este caso), sobre todo sí María impone mucho respeto, porque entonces entre en juego el generalizado y aceptado (según la RAE) «leísmo de cortesía». Consideren que dicen en la consulta de un médico:

Me lo dijo la doctora María, pero me cuesta creerle.
Me lo dijo mi amiga María, pero me cuesta creerla.

Muchos usarían siempre creerla o creerle en ambos casos, pero muy raramente emplearían ambas palabras al contrario, simplemente porque el consejo médico de una doctora (aunque no nos convenciera) generalmente merece mayor consideración que el consejo médico de la vecina del 4ºB. Pero  un criterio basado en la cortesía puede ser muy laxo...
Conclusión: En mi opinión, ambos usos son aceptables.


Q:

Assigning a number to std::string is now allowed?

Consider the following code snippet:
#include <iostream>
int main() {
    std::string foo;
    foo = -1; // why is the compiler not complaining about this?
    std::cout << "1" << std::endl;
    std::cout << foo << std::endl;
    std::cout << "2" << std::endl;
}

Actual output (both ideone.com C++14 mode and GCC 4.8.4):
<no output>
Questions:

Why did the code snippet compile at all?
Commenting out foo = -1, I get the correct stdout (1 and 2). What has the compiler compiled with foo = -1; that causes the subsequent couts to fail?

A:

foo = -1;

resolves to std::string::operator=(char) since -1 is an int and int can, in theory, be converted to a char.
It's not clear to me what the standard says when the int does not represent a valid char. It looks like in your implementation, the program crashes.
Update
From the C++11 Standard (emphasis mine):

3.9.1 Fundamental types
1 Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character
  object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values.

It appears that you'll have to consult your compiler's documentation to understand whether it allows char object to hold negative values and, if it does, how does it treat such objects.

A:

char is an integral type in C++. std::string defines an assignment operator:
std::string& operator=(char);

Since int converts to char freely in this context, no diagnostic is given. (It's funny how best intentions pave the road to Hell, innit?)
Since (char)-1 is probably not a valid member if the execution character set on your platform, the stream enters an error state and will stay there, outputting nothing, until the error bit is cleared.
EDIT this is a bug of ideone. If the output stream contains an "illegal" character, the entire stream is not shown, even the parts produced and flushed before the bad character. Use another online compiler to check.


Q:

What's the physical meaning of the standard base vectors?

I can find 3 displacement $\vec d_1 ,\vec d_2, \vec d_3$ and use them as basis so that a displacement is $\vec d=a\vec d_1 +b\vec d_2+c \vec d_3$.
I can find 3 forces $\vec F_1 ,\vec F_2, \vec F_3$ and use them as basis so that a force is $\vec F=a\vec F_1 +b\vec F_2+c \vec F_3$.
So the basis are vectors with the meaning of displacement or force or others... the physical meaning is clear in these examples.
But standard base vectors $\vec i, \vec j, \vec k $  are different because they are good for all the kind of vectors for example they can be used to write forces as $\vec F=a\vec I+b \vec j+c \vec k $ or displacements as $\vec r=d\vec I+e \vec j+f \vec k $ and so on...
But what is their physical meaning? I thought they were just direction but then it doesn't make sense the fact that they can be multiplied by a scalar and change the intensity.  Furthermore it looks strange that a family of vectors like forces can be obtained by linear combinations of other objects that aren't the same kind of vectors.

A:

Your basis vectors are unit vectors that are (ironically) unitless. So for all of the examples of basis vectors you propose, specifying what the vector represents is somewhat misleading.
In other words, you can think of all of your basis vectors ($\hat d_1$, $\hat d_2$, $\hat d_3$, $\hat F_1$, $\hat F_2$, $\hat F_3$, $\hat i$, $\hat j$, $\hat k$) as just directions in space. These sets of basis vectors do not represent positions, forces, etc. Your actual component magnitudes ($a$, $b$, $c$, etc.) have units, and this is what determines what the vector physically represents.
This is why you can explain many vector quantities with the same set of basis vectors. Position, force, etc. all have some direction in the space you are looking at. Therefore,  you can express each vector using the same basis vectors.

So, when you say, "I can find three displacement vectors and use them as basis vectors," what you really mean is, "I have three displacement vectors, and I can take their directions and define basis vectors." (assuming they actually form a valid basis). With your example, these are
$$\hat d_1=\frac{\mathbf d_1}{|\mathbf d_1|}$$
$$\hat d_2=\frac{\mathbf d_2}{|\mathbf d_2|}$$
$$\hat d_3=\frac{\mathbf d_3}{|\mathbf d_3|}$$
These basis vectors are just directions, they have no units associated with them, and you can use them to explain any other vector. For example, a force could be
$$\mathbf F=F_1\,\hat d_1 +F_2\,\hat d_2+F_3\,\hat d_3$$
In other words, you have broken your force vector into components where each component is along the direction of each of displacement vectors you used to define your basis. The values $F_i$ have units of force, and this is what makes the vector a force vector. Also, note, for example, that the term $F_1\,\hat d_1$ is not "changing the intensity" of $\hat d_1$. It is just a scalar multiplication of the unit vector $\hat d_1$. This is analogous to how computing $3\cdot 4=12$ does not change what $4$ actually is.


Q:

Finding all quads in a mesh

I'm loading a mesh via Three.js, and I'm trying to texture each quad individually. Right now I can texture each face (tri), but I'm not sure how to determine if the current and last triangle are part of a quad (they'll share two vertices, but which ones?)
How can I figure out if two triangles form a quad?
var last = null;
for(var i in geometry.faces)
{
    var face = geometry.faces[i];
    var normal = face.normal.clone().normalize();

    if(normal.y >= 0.9999)
    {
        face.materialIndex = 1;

        //Determine if face & last are part of a quad
        if(face && last == same quad)
        {
            face.color = last.color;
        }
        else
        {
            face.color = new THREE.Color(Math.random() * 0xFFFFFF);
        }

        last = face;
    }
}

A:

First, you need to realize that the problem is under-defined. In a connected triangle mesh, every triangle has 3 neighbors. Each one of them could be it's quad. So you can only make a good guess as to what are quads. Your choice of checking the normal is a good start, but would not work for example if the mesh was a plane.
The first step is to find all the neighbors for each triangle. Each triangle has exactly 3 neighbors. This is a fun two pass algorithm that should be linear in time and memory. Each triangle should have something like neighbors[3] - which are indices to other triangles.
Then you can compute a "quadiness" heuristic for each of them. They should be roughly coplanar and rectangular. I would score by normals and inner angles on the four sides. Once you have those, you can sort all triangles by this number. Remove the best guesses first, merge them into a quad, and keep going until you are done.
This should work pretty ok most of the time, but there will be cases where this breaks down. Depending on why you need quads you can try to fix your heuristic function to fit your case. But it is important to remember that there is no right solution. The problem is under defined.


Q:

Worker automation, can't fine tune as much as in Civ4?

In Civ4 I would improve the key points around a city to be how I wanted them and then normally stick a worker in to the mode that would improve just that city, with workers do not remove forests and workers do not touch old improvements both enabled in the global options. I'd occasionally just stick a worker on to improve city around one I've captured that I've captured and am not interested in micromanaging.
All three of these options seem to be missing from Civ 5.
I don't want to automate my workers to work globally, as I hate them touching the stuff I've actually taken the time to configure myself, they remove too many forests for my liking, and I don't like them walking about the map all over the place (for safety and because I like my workers spread across the nation, not all bunched up irrigating one city).
So, are these options available anywhere in Civ 5?
If not, can I emulate them at all?
Update
On 22nd Oct 2010 the game was patched to version 1.0.0.62, which has added a option to the ingame menus so force workers to not change manually created improvements. I believe that they will still overwrite improvements previously created by automated workers.

A:

As you've said, there does not appear to be any kind of "Automate City" or "Leave Forest option" available either in the game or in any config files.
UPDATE: The recent patch (around 10/28/2010) has added "Workers leave manually built improvements" to the in-game options menu. All you have to do is start the game and steam will download it for you.
As you've said these options are not available from within the game. Based on my research, sadly, both "Leave Forests" and "Automate City" seem to be completely missing. However, you can switch on "Leave Existing Improvements" by editing a config file.

Navigate to "My Documents/My Games/Sid Meier's Civilization V/"
Open "UserSettings.ini"
Find "AutoWorkersDontReplace = 0", it was the 5th row (3rd real setting) for me.
change the "= 0" (off) to "= 1" (on).

There's some small chance that this option also forces them to leave forests, but I have not tested it in the slightest. If anyone else does test it please let us know!


Q:

Backspace Button In JavaFX

I am making a calculator project using JavaFX. In my calculator, I had a backspace button. I tried the old way, something like this:
strBuild.deleteCharAt(display.getText().length()-1);

But that didn't work, possibly and probably because of the versions. So, I was wondering if there was any way I could implement or create the backspace button in JavaFX.
This is my FXML Controller:
@FXML
    void handleButtonAction(ActionEvent event) {

        if(start)
        {
            display.setText("");
            start = false;
        }
        else if(event.getSource() == one)
        {
            display.setText(display.getText() + "1");
        }
        else if(event.getSource() == two)
        {
            display.setText(display.getText() + "2");
        }
        else if(event.getSource() == three)
        {
            display.setText(display.getText() + "3");
        }

        //and so on

        else if(event.getSource() == dot)
        {
            display.setText(display.getText() + ".");
            dot.setDisable(true);
        }
        else if(event.getSource() == clear)
        {
            display.setText("");
            dot.setDisable(false);
        }
        else if(event.getSource() == add)
        {
            data = Float.parseFloat(display.getText());
            operation = 1;
            display.setText("");
            dot.setDisable(false);
        }

        //and so on

        else if(event.getSource() == equals)
        {
            Float secondOperand = Float.parseFloat(display.getText());
            dot.setDisable(false);
            switch(operation)
            {
                case 1: //Addition
                    Double ans = data + secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 2: //Subtraction
                    ans = data - secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 3: //Multiplication
                    ans = data * secondOperand;
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
                case 4: //Division
                    ans = 0d;
                    try{
                    ans = data / secondOperand;
                    }catch(Exception ex){display.setText("Error");}
                    display.setText(String.valueOf(ans));
                    data = ans;
                    break;
            }
            if(event.getSource() != divide && event.getSource() != add && event.getSource() != multi && event.getSource() != minus)
            {
                start = true;
            }
        }
        else if(event.getSource() == backspace)
        {
            // the problem
        }

    }

A:

Traditionally backspace only removes the last character so all you would need to do is check if display.getText().isEmpty() and if its not then continue by pulling off the rightmost(Last typed Character)
else if(event.getSource() == backspace)
{
    if(!display.getText().isEmpty())
        display.setText(display.getText().substring(0,display.getText().length()-1));
}

or
else if(event.getSource() == backspace)
{
    if(!display.getText().isEmpty())
        display.setText(display.getText().replaceAll(".$", ""));
}

or even
import org.apache.commons.lang.StringUtils;

...

else if(event.getSource() == backspace)
{
    if(!display.getText().isEmpty())
        display.setText(StringUtils.chop(display.getText()));
}

or if you want to keep your StringBuilder
else if(event.getSource() == backspace)
{
    if(!display.getText().isEmpty())
        display.setText(new StringBuilder(display.getText()).deleteCharAt(display.getText().length()-1).toString());
}

If you forget to add the check you will get an StringIndexOutOfBoundsException


Q:

Summing Numerical Character String

I'm having an issue with my programming assignment where I cycle through a string and sum the integer value of character. As the following code states. Now I pass a string into this subroutine. For example given
num := '8888';

Expected Output would be
32

Resulting output is
-12

I'm using fpc pascal compiler on a Linux environment. Any insight as to why this is occurring would be much appreciated
   procedure subRoutine1(num : string);
   var
     i : byte;
     value : integer;
     sum : integer;
   begin
     sum := 0;
     for i := 0 to length(num) do
     begin
       value := Integer(num[i]) - 48;
       sum := sum + value;
     end;
     writeln(sum);
   end;

A:

The bug is that the loop should start with with 1, not 0.
for i := 0 to length(num) do...
should be
for i := 1 to length(num) do

Pascal strings have the first byte containing the length of the string.
in other words, num[0] contains the value 4 (string is 4 characters long)which gives -44 after subtracting 48, throwing off your expected sum value.
So your program iterates over the following values
  4  -->  -48   =  -44
 56  -->  -48   =  8
 56  -->  -48   =  8
 56  -->  -48   =  8
 56  -->  -48   =  8
            sum = -12

Also as suggested in other answers, do use the Ord() function rather than a cast to Integer, i.e. use
   value := Ord(num[i]) - 48;
or even better,
  value := Ord(num[i]) - Ord('0');


Q:

Tunneling one page apps (e.g. Backbone)

I would like to know if it is possible to nest/tunnel javascript rendered sites.
What I mean concrete:
I got a site bugs.example.org which serves a bug tracker application built on Backbone Routers, Views and Models.
over bugs.example.org/#/mybugs we can list all our bugs.
Now I have for example a second project worksuite.example.org.
This project serves roadmaps, presentations, etc. unfortunately this worksuite app doesn't serve an independent bug tracker. Instead it has a joint venture with bugs.example.org.
Now worksuite.example.org want to include/nest the bugtracker views in its own application.
This could look like:
worksuite client calls worksuite.example.org/#/bugs now the worksuite app calls a GET to bugs.example.org/#/mybugs and does a $el.html(requestedContent).
Does this work?
Another application which could work similar, which I know is the google captcha service which you nest with some js
Is there a keyword for such behavior?

A:

Depending on how well the backbone app is architected, you can have worksuite.example.org just pull all of bugs.example.org's JS files, but use its own base html/css:
<!-- on bugs.example.org -->
<script src="mybackbonestuff.js"></script>
<link href="mycss.css"></link>

<!-- on worksuite.example.org -->
<script src="http://bugs.example.org/mybackbonestuff.js"></script>
<link href="worksuite.css"></link>


Q:

can not find params from route in angular

i have this senario :
when use register in site i send a email to that email . in that have a link and must click on that link for verify registertion .
that route have this information :
http://localhost:4200/auth/verify-checking?email={0}&code={1}

and i create this route :
  { path: 'verify-checking', component: CheckingVerifedComponent },

but i have tow problem :
A : can not find the params :
i use this code but not worked :
this.route.params.subscribe(params => {
  this.sendModel.email = params['email'];
  this.sendModel.code = params['code'];
});

B : it show me this error :

Error: Cannot match any routes. URL Segment: 'auth/verify-checking%3Femail%3Dkianoushvv123456@gmail.com&code%3DCfDJ8PQkunuAtiZOulV9qQ%252F3astuT%252Fa2VVXDAhxbE%252Fpg%252FfmcpXTcFXPR3gunRzs443wcxrxxWefG3PHVqmdbJL5GZX8dwgI0UuZTVDW%25206U2hSNBTQ1X7xT3YHh%2520%2520ym3%252FP3rlinriN4vgxJEMbmqPKQYe7XsnjcjYCtNvHY141nk%252FEYkoj6FZkEPuVdZO5qH%2520jNyRXA%253D%253D'

how can i solve this problems ?????

A:

http://localhost:4200/auth/verify-checking?email={0}&code={1}

queryParam is used for ?email={0}&code={1}
this.route.queryParams.subscribe(params => {
  this.sendModel.email = params['email'];
  this.sendModel.code = params['code'];
});


Q:

Improve GeoFire query performance - Firebase

I'm building an app in Swift where Users( can post the locations of event they witness in the street. Each event has a lifetime of 45 mins, then it does no appear on the map after that threshold.
I built my Json tree like this (locations and events share the same id - not represented here) :
firebaseapp {
  locations {
    g
    l {
      0: "latitude"
      1: "longitude"
    }
  }
  events {
    timestamp: "UTC timestamp"
    description: "my description"
    user: "id of user"
  }
  users {
    // User data
  }
}

I query all the locations corresponding to the region displayed on the screen, then I query the events which occurred less than 45 mins ago. I do this this way:
regionQuery = geoFire.queryWithRegion(mapView.region)
regionQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in

// I query my events based on the key here

})

The problem with this method is that, for a specific region, I query ALL the locations of events that occurred in the past (which can be a LOT), and THEN I query the ones which happened less than 45 min ago using tradionnal Firebase queries.
Is there a better solution for my problem, cause I'm afraid I'll cross the bandwidth threshold pretty quickly if each time a user moves the map, all the locations of the region displayed are loaded...

A:

Just split the "recent locations" from the "historic locations":
recent_locations
   g
      l {
        0: "latitude"
        1: "longitude"
      }
historic_locations
   g
      l {
        0: "latitude"
        1: "longitude"
      }

Now you can run geo-queries against either recent locations or historic locations.


Q:

Uwsgi disables django.request logging

If I start application using uwsgi I don't see logs related to django.requests.
But If I start the same code on the same machine using
manage.py runserver 8080

it works perfectly.
Any ideas why it might happen?
I run uwsgi by this command
/home/gs/python-env/bin/uwsgi --ini /etc/uwsgi.d/uwsgi.ini --static-map /static=/home/gs/api/static/

uwsgi.ini
[uwsgi]
http-socket=:8080
home=/home/gs/python-env
chdir=/home/gs/api
module=server.wsgi
env=server.settings
processes=1
enable-threads=true

My logging configuration from settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(process)d %(threadName)s %(module)s %(funcName)s %(message)s'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/gs/api.log',
            'formatter': 'verbose',
            'maxBytes': 1024 * 1024 * 16,  # 16Mb
        },
        'elasticsearch': {
            'level': 'DEBUG',
            'class': 'api.common.elasticsearch_log_handler.ElasticSearchHandler',
            'hosts': [{'host': cluster.ES_HOST, 'port': 443}],
            'es_index_name': 'logstash',
            'es_additional_fields': {'type': 'api', 'cluser': cluster.CLUSTER_NAME},
            'auth_type': ElasticSearchHandler.AuthType.NO_AUTH,
            'use_ssl': True,
        }
    },
    'loggers': {
       'django': {
            'handlers': ['file', 'elasticsearch', 'console'],
            'level': 'INFO',
            'propagate': True
        },
        'django.request': {
            'handlers': ['file', 'elasticsearch', 'console'],
            'level': 'DEBUG',
            'propagate':False
         }
    }
}

If I change info to debug for 'django' I will see my logs from django logger but not from django.request.
UPD: If I write my own middleware I can log requests. But I want to know why django.request doesn't work with uwsgi.

A:

Django's runserver provides the log messages that show up under django.server. When not running under runserver there are still some messages that can be logged to django.request (mostly error messages) but the informational log message for each request only exists in runserver. I verified this by looking at the uWSGI and the Django source.
If you want a similar log message you can use django-request-logging.


Q:

Programmatically adding menu + items to NSPopupButton

I have a custom class "BackupIncrement" which gets its data from an sqlite3 database, and works just fine. I also have an NSPopUpButton called "pubDefaultIncrement" which is hooked up in IB.
The end result is that I would like to have the popupbutton populate with meaningful titles and also with each menuitem or value being the increment id (primary key) from the database.
Here is the code in question:
- (void)doAddItemsTopubDefaultBackupIncrement {
    marBackupIncrement = [[NSMutableArray alloc] init];
    pubDefaultIncrement = [[NSPopUpButton alloc] init];
    [pubDefaultIncrement removeAllItems];
    mnuBackupIncrement = [[NSMenu alloc] init];
    const char* chrSQLSelect = "SELECT * FROM _backup_increments";
    sqlite3_stmt* compiledSQL;
    if (sqlite3_prepare_v2(claAppDelegate.sl3Database, chrSQLSelect, -1, &compiledSQL, NULL) == SQLITE_OK) {
        while (sqlite3_step(compiledSQL) == SQLITE_ROW) {

            BackupIncrement* bi = [[BackupIncrement alloc]
                            initWithintIncrementId:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledSQL, 0)]
                            AndstrIncrementValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledSQL, 1)]
                            AndstrIncrementDescription:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledSQL, 2)]];
            NSMenuItem* mi = [[NSMenuItem alloc]
                            initWithTitle:[bi strIncrementValueDescription]
                            action:Nil
                            keyEquivalent:[bi strIncrementValue]];
            [mi setTarget:self];
            [mi setRepresentedObject:bi];
            [mi setTag:[[bi intIncrementId] integerValue]];
            [mnuBackupIncrement addItem:mi];
            NSLog(@"Menu Item: %@", mi);
            NSLog(@"Menu Item Title: %@", [mi title]);
            NSLog(@"Menu Item Tag: %ld", (long)[mi tag]);
            //[[pubDefaultIncrement menu] addItem:mi];
            //[marBackupIncrement addObject:bi];
        }
    }
    //NSLog(@"%@", mnuBackupIncrement);
    //[pubDefaultIncrement setTarget:self];
    [[pubDefaultIncrement menu] setSupermenu:mnuBackupIncrement];
    [pubDefaultIncrement setMenu:mnuBackupIncrement];
}

The sql works, it loops 5 times fetching each of the rows from the sqlite3 table.
This:
NSLog(@"%@", mnuBackupIncrement);

prints out the menu object with the 5 menu item objects inside it.
However when I run my project code the popupbutton has 3 things.
1st: a blank item
2nd: Item 2
3rd: Item 3

I was originally attempting this with an ArrayController and Bindings but I couldn't seem to get the tags for each menu item to work properly. If that is the way to do this, I would gladly listen to the proper way to the bindings.
Just f.y.i. the BackupIncrement object exposes 4 properties:
intIncrementId: the primary key from the table (1-5 currently for the 5 rows)
strIncrementValue: the single letter value from the table (h, d, w, m, y)
strIncrementDescription: the desc for the value (hour, day, week, month, year)
strIncrementValueDescription: a combination of the previous two - e.g. "d (day)", "m (month)"

So again - ideally id have the NSPopUpButton populate with menuitems which have strIncrementValueDescription as the visible "content" and the corresponding intIncrementId as the "value" such that when an item is selected I can get the tag or whichever an then act accordingly.
Can anyone point me in the right direction?

A:

As it turns out (once again) my issue was a timing one. I was calling the function in question from within the ViewController's initWithNibName...
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialization code here.
        if (!claAppDelegate) {
            claAppDelegate = [[AppDelegate alloc] init];
        }
        //[self doAddItemsTopubDefaultBackupIncrement]; <--- HERE doesn't work....
    }
    return self;
}

When instead I should have been calling it after the ViewController has been loaded:
- (void)loadView {
    [self viewWillLoad];
    [super loadView];
    [self viewDidLoad]; // <-- call in here instead
}

- (void)viewDidLoad {
    [self doAddItemsTopubDefaultBackupIncrement]; //<-- HERE: works just fine...
    [pubDefaultIncrement selectItemWithTag:claAppDelegate.intDefaultBackupIncrmentId];
}


Q:

VMware esxi and windows server 2008 R2 DC

We are going to install vmware esxi 5.1 on one HP Proliant DL380p G8 server with 4x300GB HDD and make some of our service through that server. we have very small business and only 32 clients. so I want to install Windows Domain Controller on that vmware esxi and the other  windows server machine for antivirus and one windows machine for Bandwith monitoring for client.
but I am a little bit scared about this solution. I am scared about the performance and Windows Server 2008 R2 DC problem?
I want to know that can I install windows Server 2008 r2 DC? Which RAID configuration for local disk? I created RAID 5.

A:

This solution is fine. Although you did not specify how much physical RAM would be installed in this server, I'd recommend 16GB or more. A single CPU is okay. Two is better if you plan on virtualizing additional systems.
If you can afford the space, using RAID 1+0 instead of RAID 5 would be my recommendation. Please make sure you have a battery-backed or flash-backed write cache module for this HP Smart Array RAID controller.
In terms of domain controllers, they do not require heavy resources, even when virtualized. I typically use one vCPU and 4GB of RAM for a domain controller.