text:
Q: Begin sessions using different QuickBooks versions programmatically I'm accessing a QuickBooks file from code using this call
win32com.client.Dispatch("QBXMLRP2.RequestProcessor")

I plan to install more than one version of QuickBooks on my computer. Is there a way to specify which version of QuickBooks is being used to open the session? I want to address particular versions of QuickBooks so that my program is in compliance with the restriction that only one QB file can be opened at a time by an SDK application. (For example, I might begin a session with company1.qbw with QuickBooks Pro, and another session with company2.qbw with QuickBooks Premier).

A: Only one QuickBooks file can be opened by the SDK on one machine at one time. Installing multiple versions of QuickBooks doesn't change this. If you have a file open in QuickBooks Pro and you want to open an Enterprise file, you must first close Pro. The only way to open multiple QuickBooks files at the same time with the SDK is to use multiple computers.
Side note: multiple versions of QuickBooks can be run on the same machine and the SDK will work; but don't try installing the Canadian or UK versions, or Reckon (Australia and Singapore) on a machine with the US version installed: that will screw up the SDK.


text:
Q: Logging all button clicks in WinForms app I'm looking to add a log statement for every WinForms button click that the user clicks, and ideally, an indentifier of the parent form (such as the title bar). I have seen posts logging all mouse clicks, but i'm interested in just logging button clicks. I have read the accepted answer here and adapted it:
public class ButtonLogger
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(ButtonLogger));
    public static void AttachButtonLogging(Control.ControlCollection controls)
    {
        foreach (var button in controls.OfType<Button>())
        {
            button.Click += LogButtonClick;
        }
    }
    private static void LogButtonClick(object sender, EventArgs eventArgs)
    {
        Button button = sender as Button;
        Logger.InfoFormat("Button clicked: {0} ({1})", button.Text, button.Parent.Text);
    }
}

This class is used at the end of a constructor in a form, e.g. :
ButtonLogger.AttachButtonLogging(this.Controls);

The problem I'm facing with this is that the Controls property doesn't seem to have a reference to my buttons. Presumably this is because the buttons aren't added directly to the form, but rather, another control that is in the Controls property. However, the Controls property only contains a single control, a ToolStrip.
Is there a way I can harness all of the buttons on a form, regardless of their parent container? My final goal is to add a log statement to my buttons, so if this can be accomplished some other way besides button click event methods, then I'm open to that as well

A: I believe you need to search for buttons recursively:
public static void AttachButtonLogging(Control.ControlCollection controls)
{
    foreach (var control in controls.Cast<Control>())
    {
        if (control is Button)
        {
           Button button = (Button)control;
           button.Click += LogButtonClick;
        }
        else
        {
            AttachButtonLogging(control.Controls);
        }
    }
}

A: One thing you could consider is to create a subclass of the standard Button class, and let the buttons themselves do the logging. Of course, you'd have to go around and substitute all the buttons in the application for your own implementation, but it should be possible to do that with a global search+replace.
Here's an example implementation:
public class LoggerButton : Button
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(LoggerButton));

    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        Logger.InfoFormat("Button clicked: {0} ({1})", this.Text, this.Parent.Text);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apple Watch locked when restarting after long powered-down state I've kept my Series 5 Apple Watch switched off for a long time and restarted it today. It shows "Device Locked. Unlock iPhone to start using Apple Watch" message when I wear it.
On my iPhone 7, the Watch app seems to have forgotten my Watch and shows the 'Start Pairing' screen, but when I go to start pairing mode, it doesn't detect the Watch, and the watch doesn't respond either. The watch is not listed when I go to manual mode as well.
What troubleshoot tips should I try?

A: To troubleshoot, I would follow the restore steps:

*

*https://support.apple.com/en-us/HT204505
It mentions that bluetooth should be on on the phone and you should be connected to WiFi so if you can turn both of those on on both devices (might be hard on watch unless it prompts you) but if you can get the same WiFi router as the last time it booted, it might reconnect automatically.
Once that's done, you might end up down the "watch won't restart" article which has a few more things to try before you contact Apple Support. Even though force restarting the watch isn't ideal, you might try that as well one time once WiFi and Bluetooth are enabled to the max extent you can manage.

*

*force restart - https://support.apple.com/en-us/HT204510

*reset and restore - https://support.apple.com/en-us/HT204567


text:
Q: One to Many to One relationship in laravel eloquent I have company, employee and motorCycle table.
One Company has many employee. One employee has One motorCycle
Company.php
<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    protected $table      = 'company';
    protected $primaryKey = '_id';

    public function employee()
    {
        return $this->hasMany(Employee::class);
    }
}
?>

Employee.php
<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $table      = 'employee';
    protected $primaryKey = '_id';

    public function motorCycle()
    {
        return $this->hasOne(MotorCycle::class, 'motorCycle', 'id');
    }
}
?>

MotorCycle.php
 <?php

    namespace App\Model;

    use Illuminate\Database\Eloquent\Model;

    class MotorCycle extends Model
    {
        protected $table      = 'motorCycle';
        protected $primaryKey = 'id';

        public function employee()
        {
            return $this->belongsTo('MotorCycle::class');
        }
    }
    ?>

I would like to fetch result in controller like below
   public function show(Company $company)
    {
        return $company->employee()->offset(0)->limit(20)->motorCycle()->get();

    }

I am trying to browse this URL http://127.0.0.1:8000/api/comapanys/1
My route is like below
Route::apiResource('comapanys', 'ComapanyController');

A: what kind of result do you want to display? you want to have a list of employees and his/her motorcycle in a certain company?
may you can return a query like this.
public function show(Company $company)
{
 return $company->employee()->with('motorCycle')->offset(0)->limit(20)->get();
}

A: There is to many problem in your code.
 First, for example you write class company extends Model but in controller you use Company $company. Also for class employee class employee extends Model but in motoCycle class return $this->belongsTo('App\Model\Employee');. Use naming convention like first letter uppercase for model name .
Second, im not sure but I dont think you can chain eloquent methods like this return $company->employee()->offset(0)->limit(20)->motorCycle()->get();. Offset and limit should be on the end of chain.
Also use (Employee::class) instead of ('App\Model\Employee')


text:
Q: How to perform a bootstrap and find confidence interval in R I want to create a custom bootstrap function because I want to better understand what bootstrap is doing and it seems like the other bootstrap libraries out there does not solve my issue.
The Problem: I would like to create my own wald confidence interval function where it takes in the bootstrap data, outputs the confidence interval, test the confidence interval is within a range, and gets the coverage.
Right now, I am getting this type of error:
Error in bootresults[i,}<-waldCI(y=bootdata[i], n=numTrials):number of
  items to replace is not a multiple of replacement length

The goal: My goal is to get the bootresults dataset to return 4 columns(p value,One that shows the upper bound, lower bound, and whether or not the p is in the interval) and get a graph similar to this one:
Wald interval chart

Code:
set.seed(42)
samples10 <- list()
i <- 1
while(i < 100) {
  sample10[[i]] <- rbinom(1500, size=10, prob=i*.01)  ## rows=1500 ;columns=10
  i <- i + 1
}
sample10 <- data.frame(samples10)
colnames(sample10) <- c(seq(.01, .99, .01)) ## p-values

waldconfidenceinterval <- function(y, n, alpha=0.05) {
  p <- colSums(y)/(n*200)
  sd <- sqrt(p*((1 - p)/(n*200)))
  z <- qnorm(c(alpha/2, 1 - alpha/2))
  ci <- p + z*sd
  return(ci)
}

B <- 200
numTrials <- 10
bootresults <- matrix(ncol=length(sample10), nrow=B)  ## rows=200, cols=99
                                                      ## empty matrix in the beginning
set.seed(42)

for(i in seq_len(B)) {
  bootdata <- sample10[sample(B, replace=T), ]
  bootresults[i, ] <- waldCI(y=bootdata[i], n=numTrials)
  ## Pseudocode:
  # boot_test_data$in_interval <-
  #   ifelse(boot_test_data$lower1 < i/100 & i/100 < boot_test_data$upper1, 1, 0)
  # coverage[i] <- sum(boot_test_data$in_interval) / length(boot_test_data$in_interval)
}

Any help is greatly appreciated since I am fairly new to R.

A: Looks like that you want to initialize a three-dimensional array bootresults rather than a two-dimensional matrix. In your waldCI() you may use colMeans.
waldCI <- function(y, alpha=0.05) {
  p <- colMeans(y)
  se <- sqrt(p*(1 - p)/nrow(y))
  z <- qnorm(1 - alpha/2)
  ci <- p + z*se %*% cbind(lower=-1, upper=1)
  return(ci)
}

B <- 200
numTrials <- 10
## initialize array
bootresults1 <- array(dim=c(ncol(samples10), 4, B),
                     dimnames=list(c(), c("p.values", "lower", "upper", "in.int"), c()))

set.seed(42)
for(i in seq_len(B)) {
  samp <- samples10[sample(nrow(samples10), numTrials, replace=F), ]
  ci <- waldCI(samp)
  bootresults1[,,i] <- cbind(p.values, ci, in.int=ci[, 1] < p.values & p.values < ci[, 2])
}

coverage <- rowMeans(bootresults[,4,])
plot(p.values, coverage, type="l", main="My Plot")

Similar approach, more R-ish, though:
p.values <- seq(.01, .99, .01)
set.seed(42)
samples10 <- `colnames<-`(sapply(p.values, function(pr) rbinom(1.5e3, 1, pr)), p.values)

BOOT <- function(numTrials, ...) {
  samp <- samples10[sample(nrow(samples10), numTrials, replace=F), ]
  ci <- waldCI(samp, ...)
  cbind(p.values, ci, in.int=ci[, 1] < p.values & p.values < ci[, 2])
}

B <- 200
numTrials <- 10

set.seed(42)
bootresults2 <- replicate(B, BOOT(numTrials=10))

stopifnot(all.equal(bootresults1, bootresults2))

Data:
Note, that I used rbinom(..., size=1, ...) to create your sample data. The use of "p" as an object name suggested that the data should be binomial.
set.seed(42)
samples10 <- matrix(nrow=1500, ncol=99, dimnames=list(c(), c(seq(.01, .99, .01))))
i <- 1
while (i < 100) {
  samples10[, i] <- rbinom(1500, size=1, prob=i*.01)  ## rows=1500 ;columns=10
  i <- i + 1
}

Without a while loop, you could proceed vectorized:
p.values <- seq(.01, .99, .01)
set.seed(42)
samples10 <- `colnames<-`(sapply(p.values, function(pr) rbinom(1.5e3, 1, pr)), p.values)


text:
Q: Haskell: Confusion over 'foldl' with parenthesized operator (==) Here are a few results of applying 'foldl' to this particular equality operator. I do not understand them - I thought that each line should return true, since "False == False == False ..." is true regardless of the length of the list. I am fairly new to Haskell.
Prelude> foldl (==) False [False]
True
Prelude> foldl (==) False [False,False,False]
True
Prelude> foldl (==) False [False,False,False,False]
False
Prelude> foldl (==) False [False,False,False,False,False]
True
Prelude> foldl (==) False [False,False,False,False,False,False]
False

I found these results when trying to write a function that tests whether a list of functions give the same result when applied to a common argument (returning a Boolean).

A: == is a binary operator. When you write False == False == False, you're really writing (False == False) == False, which is True == False. Perhaps now you can understand what's happening.
Answer submitted in comments by 'Alexis King'


text:
Q: Complex SQL transformation This is my source table
Reference   ModifiedDate
------------------------------------
1023175     2017-03-03 16:02:01.723
1023175     2017-03-07 07:59:49.283
1023175     2017-03-12 11:14:40.230

Ineed the following output
Reference   StartDate                 EndDate
---------------------------------------------
1023175   2017-03-03 16:02:01.723     2017-03-07 07:59:49.283
1023175   2017-03-07 07:59:49.283     2017-03-12 11:14:40.230
1023175   2017-03-12 11:14:40.230     9999-12-31 00:00:00.000 (last record should have this value)

Any suggestions on how this can be achieved?

A: You can use lead/lag windowing function. It works from SQL Server2012 onwards... Before that you need to do self join with genereated row_number
select Reference, ModifiedDate as StartDate,
    lead(ModifiedDate, 1, '9999-12-31 00:00:00.000') over(order by Reference) as EndDate
    from #yourreference

Table details
create table #yourreference (Reference int, ModifiedDate datetime)

insert into #yourreference (
Reference ,  ModifiedDate ) values
 (1023175   ,'2017-03-03 16:02:01.723')
,(1023175   ,'2017-03-07 07:59:49.283')
,(1023175   ,'2017-03-12 11:14:40.230')

A: DECLARE @MyTable TABLE (Reference INT, ModifiedDate DATETIME)
INSERT INTO @MyTable VALUES

(1023175, '2017-03-03 16:02:01.723'),
(1023175, '2017-03-07 07:59:49.283'),
(1023175, '2017-03-12 11:14:40.230');

SELECT
    T1.Reference,
    T1. ModifiedDate AS Start_Date,
    COALESCE(MIN(T2.ModifiedDate),CAST('31/12/9999' AS DATETIME))  as EndDate
FROM @MyTable T1
    LEFT JOIN @MyTable T2
ON T1.reference = T2.reference AND T1.ModifiedDate < T2.ModifiedDate
GROUP BY
    T1.Reference,
    T1. ModifiedDate

A:  select a.Reference, a.ModifiedDate as StartDate,
        coalesce(min(b.ModifiedDate),9999-12-31 00:00:00.000)  as EndDate
 from source_table as a
 left join source_table as b
 on a.reference = b.reference and a.ModifiedDate < b.ModifiedDate
 group by a.Reference, a.ModifiedDate

A: This will work in Oracle versions from 9i:
select reference
       , modifieddate as startdate
       , lead ( modifieddate, 1, to_timestamp('9999-12-31 00:00:00.000', 'yyyy-mm-dd hh24:mi:ss.ff3'))
                 over (partition by reference order by modifieddate) as enddate
from your_table;

Note that the windowing clause needs to sort by modifieddate to ensure the correct value.


text:
Q: Prove line joining midpoints of non-parallel sides of trapezoid is parallel to the parallel sides of the trapezoid If I have a trapezoid with two sides parallel, and a line going through the midpoints of the other two sides, how do I prove that this line is also parallel to the two parallel sides of the trapezoid?

Assuming $AD || BC$ and $AE=EB$ and $DF=FC$, how do I prove that $EF||AD||BC$?

A: Without loss of generality, |AD|<|BC|. Draw a line passing through A and meeting BC at G and EF at H. Since AGCD is a parallelogram, H is the midpoint of AG. Note that triangles AEH and ABG are similar, hence, EH is parallel to BG, and the result follows.

A: Proof
Let  ABCD  be a trapezoid with the bases  AB  and  DC  and the mid-line  EF    Compare the triangles  DFC  and  FBG.
The segments  FC  and  BF  are congruent since the point  F  is the midpoint
 of the side  BC.  The angles  DFC  and  BFG are congruent as the vertical angles.
 The angles  DCF  and  FBG are congruent as the alternate exterior angles
 at the parallel lines  AB  and  DC  and the transverse  BC.
 Hence, the triangles  DFC  and  FBG are congruent in accordance with the  ASA-test of congruency of triangles.
 It implies that the segments  DF  and  GF  are congruent as the corresponding sides of the congruent triangles  DFC  and  FBG.
Thus the mid-line  EF  of the trapezoid  ABCD  is the straight line segment connecting the midpoints of the triangle  AGD.
It is well known fact that the the straight line segment connecting the midpoints of the triangle  AGD  is parallel to the triangle base  AG  and its length is half of the length of the triangle base.  In our case,  the length of the segment  EF  is half of the length  AG :   |EF| = 1/2*|AG| = 1/2*(|AB| + |BG|).
 Since  |BG| = |DC|  from the triangles congruency,  we have  |EF| = 1/2*(|AB| + |DC|),  or  |EF| = 1/2*(a + d),  where  a  and  d  are the lengths of the trapezoid bases.
Summary
 The mid-line of a trapezoid is parallel to its bases.
 The length of the mid-line of a trapezoid is half of the sum of the lengths of its bases.


text:
Q: Is HIPE with RabbitMQ production ready? does anyone enabled HIPE on RabbitMQ on production servers, if yes, did you face any problems beside the Rabbimq start-up time ,

A: HIPE has become more stable over the years and recent versions. Now I use it in production without any segmentation fault and an important performance boost. I am using the latest version:
RabbitMQ 3.6.10, Erlang 19.2.1
You can turn it on safely, but better use the last version you can.

A: About HIPE there are different opinions, someone uses HIPE without problems, but I'd be careful with it.
My suggestion is to test a lot in your environment before put it in production (Especially for mission critical applications).
You should use Erlang versions >= 19.2 because of (https://bugs.erlang.org/browse/ERL-205).
RabbitMQ can be tuned in different ways, and I'd start form there.

A: HiPE support has been dropped in Erlang 22. On 3.8.4 it is still possible to run it on Erlang 21.3.


text:
Q: disallow Search on Empty form field I have a form field and I have to see that search button is clicked only when there is some
data in the form field.
The following is the code.

    <script type="text/javascript">
        function IsEmptySearch(TxtField){
        var re = /\s/g; //any white space
        var str = TxtField.replace(re, "");
        if (str.length == 0) {
        return true;
        } else {return false;}
        }
    </script>

<div>
<form id="formsearch" name="formsearch"  />
<input type="text" name="TxtField" maxlength="255" class="findSearch" value="Enter Search..."
  onfocus="if (this.className=='findSearch') { this.className = ''; this.value = ''; }"
  onblur="if (this.value == '') { this.className = 'findSearch'; this.value = 'Enter Search...'; }"/>
<input type="button" value="Search" onclick="return IsEmptySearch()" >
</form>
</div>

The above is not working, as the form gets submitted, even though the Search field is empty.
On Debug the error is showing at "onclick="return IsEmptySearch()" "
 kindly help.

A: Try
onclick="return !IsEmptySearch()"

Your function returns true if the search is empty, but to stop your form from being submitted, you have to return a false. You can rewrite and rename your function too. Try this, enter something in the search box and see if you can submit.

A: Change function to following:
<script type="text/javascript">
function IsEmptySearch(txtField, defaultText){
    var re = /\s/g; //any white space
    defaultText = defaultText || "";
    var txt = txtField.value.replace(re,"");
    var ret = txt != ""  && txt != defaultText.replace(re,"");
    return ret;
}
</script>

change button to following:
<input type="submit" value="Search"
                  onclick="return IsEmptySearch(aTextField,'Enter Search...')" >

this will also not fire if textbox has default prompt text.


text:
Q: How do get rid of (1 not defined because of singularities) in R? I'm analyzing data in R, I'm trying to see how some variables affect test scores (Value) of different countries. In the data, since there is different time periods for different countries I need to use a panel technique to regress this data. I'm using a fixed-effect model, more specifically a constant-free model, where you include dummy variables for every particular country. In the equation I took off the intercept to eliminate collinearity. When I ran the regression, I could see the statistical information for all variables except one. I get "NA" for this variable in R. I think my model still suffers from collinearity and I think the solution to fix this problem is just to drop one dummy variable from the equation. I did do that and I'm no longer getting "(1 not defined because of singularities)". I just wanted to double check with someone else if I did the right thing? This is my code:
library(stats)
library(lmtest)
library(dplyr)
library(plm)

# running fixed effects with country dummies

Data_we_using2$LOCATION = as.factor(Data_we_using2$LOCATION)

dummyregress = lm(Value ~ Boysdummy + RGDPCapita+Graduation_rates + MissingGraDummy + Mortality_rate + GovtExpen + MissingGovt + Private + LOCATION-1, data = Data_we_using2)

summary(dummyregress)

LOCATION is the dummy variables of the countries. The pictures I included is the output I got for R.


text:
Q: Opencart Case sensitive search? I'm using Opencart Version 1.5.6.4 and the search results appear to be case sensitive?
if i search for "product name" and the actual product name is "PRODUCT NAME" opencart will return no results.
Is there anyway of ignoring the case?

A: This has been resolved.
I had updated from a previous version of opencart and imported product information (UTF8_Bin). Since 1.5 the database has been switched to utf8_general_ci collation so text matching in queries is no longer case sensitive.
Just updated the database collation to utf8_general_ci. Issue resolved.


text:
Q: Best practice to automate SVN checkout as a pre-build event with MSBuild I have a C#/ASP.NET MVC project on Visual Studio 2013
What is the best way to automate an SVN checkout as a pre-build event with MSBuild. I have two options working but I dont know what is considered best practive.
First way was in the csproj file:
<Target Name="BeforeBuild">
    <Exec ContinueOnError="false" Command="svn co --username my_username --password my_password https://my.repository $(MSBuildProjectDirectory)\my\subdirectory" />
</Target>

The second was right-click project -> properties -> build events -> pre-build event command line:
svn co --username my_username --password my_password https://my.repository $(ProjectDir)\my\subdirectory

A: I'm partial to the first one.
The prebuild command takes the text added to the corresponding field in the project property pane resolving it to this markup:
  <PropertyGroup>
    <PreBuildEvent>svn co --username my_username --password my_password https://my.repository $(ProjectDir)\Clients\LostGarden</PreBuildEvent>
  </PropertyGroup>

The @(PreBuildEvent) itemgroup would then be handled in Microsoft.Common.Targets:
  <PropertyGroup>
    <PreBuildEventDependsOn></PreBuildEventDependsOn>
  </PropertyGroup>
  <Target
      Name="PreBuildEvent"
      Condition="'$(PreBuildEvent)'!=''"
      DependsOnTargets="$(PreBuildEventDependsOn)">

    <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />

  </Target>

Next steps would be for you to define inputs and outputs for your BeforeBuild target allowing it to build incrementally so the SVN call :)


text:
Q: Installing multiple library versions in Delphi / C++Builder How I can install multiple versions of a library in Delphi or C++Builder?  For example, I might want to be able to develop the next version of our app using the current versions of JCL and JVCL while still being able to compile the release version of our app using whatever version of JCL and JVCL were tested for that release.
Using more than one version of a library is easy with libraries like Boost, since those are just header files and library / DLL files that I can put wherever I want, and so I can simply point my project files at the appropriate library directories.  However, since libraries like JCL and JVCL try to install themselves into the IDE, I'm not sure how to configure different projects to use different versions without it turning into an unmanageable hack.
(I'm still not entirely familiar with how Delphi manages components and projects - most of my experience is in C++ - so this may be part of my problem.)

A: We had the same problem, supporting older versions compiled with different versions of the components. Our solution was/is to use the IDE's " -r " command line option. With this switch it is possible to use different library paths and packages (at the same time). The only problem that we encountered with this approach was that some of us regularly tried to open an older project version in the wrong IDE instance.
[Old version 1.0] bds.exe -rVersion1.0
[trunk version  ] bds.exe

How to setup those:

*

*Start your IDE as you are used to it.

*Install everything you need for "Version 1.0"

*Close the IDE

*Install all (old) packages (JCL/JVCL/...)

*Start regedit.exe

*Export the registry key HKCU\Software\CodeGear\BDS\5.0 to a *.reg file

*Start nodepad.exe and do a search&replace in the *.reg file for "CodeGear\BDS\5.0" and replace it with "CodeGear\Version1.0\5.0"

*Import the *.reg file (by double clicking it in the Windows Explorer)

*Create a copy of your RAD Studio 2007 startmenu link and change the command line to include the "-rVersion1.0" key.

Now you have two IDE configurations that are equal. You can now change the IDE that doesn't use the " -r " command option to your trunk version's packages.
When you install all the packages, you must not use the default BPL and DCP directories unless the different package versions use different file names (like the JCL and JVCL do).
CodeGear\BDS\5.0 = Delphi 2007
CodeGear\BDS\6.0 = Delphi 2009
Borland\BDS\4.0 = Delphi 2006
Borland\Delphi\7.0 = Delphi 7


text:
Q: How dequeueReusableCellWithIdentifier: treat different indexPath? Let us look some standard codes of tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
    static int count = 0;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        NSLog(@"count %d", count++);
    }
    // Configure the cell...
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    return cell;
}

If we have 10 items in array, then it will alloc 10 cells for each indexPath.row
My question is
how does the function reuseIdentifier:CellIdentifier know different row ?

A:
If we have 10 items in array, then it
  will alloc 10 cells for each
  indexPath.row

That's not true - normally number of allocated cells will be NumberOfVisibleRows+2 (or similar value).
This is (roughly) how UITableView works: Once certain cell is scrolled out of visible area it is removed from UITableView view hierarchy (set table's clipToBounds property to NO and you'll be able to see that!) and is put to a some kind of internal cache. dequeueReusableCellWithIdentifier: method checks if there's cell available for reuse in that cache and returns it (and returns nil if no cell is available) - so you don't need to allocate cells more then actually fit visible area.
dequeueReusableCellWithIdentifier method does not depend on current indexPath, rather on cell string identifier you pass to it. And indexPath is used only by you to get appropriate contents to a cell.

A: Oh, the method **dequeueReusableCellWithIdentifier**: has nothing to do with indexPath.
When using UITableView, we use [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault] reuseIdentifier:cellIdentifier] to put the cell of a very kind into the cache (maybe an NSMutableDictionary) with key 'cellIdentifier'. And then, when we need one more cell, we query the cache first, if missed, we create a new one.
The indexPath is the coder's responsibility to treat. You separate different kinds of cells by sections, and show cells row by row in one section. Section and Row make up an NSIndexPath.


text:
Q: How to create a dictionary nested dictionaries? I have a dictionary that I want to use to store keys with dictionaries as values.
Essentially, using the below screenshot of my table of data, I want to have the dictionary (in json view) as:
{'Folder/PU01': {'PLCName':'PLCCC', 'DeviceName': 'fasasd', 'Description': '', '....'}
{'Folder/PU02': {'PLCName':'', 'DeviceName': '', 'Description': '', '....'}
etc...

I have the code below that's essentially creating this, however the very bottom line above the Next is where it's going wrong udtInstancesCurrent.Add deviceTagPath, udtInstanceParamsCurrent
This is assigning the udtInstanceParamsCurrent dictionary to the udtInstanceCurrent key, but because it's a reference to the dictionary and not a copy, it then gets overwritten the next time the loop goes around.
My question is: how can I set the value of the dictionary key in udtInstanceCurrent to a copy of the udtInstanceParamsCurrent dictionary and not a reference to the original?
Dim udtInstancesCurrent As Scripting.Dictionary
Dim udtInstanceParamsCurrent As Scripting.Dictionary

Set udtInstancesCurrent = New Scripting.Dictionary
Set udtInstanceParamsCurrent = New Scripting.Dictionary
'''' SAVE PARAMETER VALUES ''''
' For each udt instance tag path, add its param value into a dictionary to save its values
For Each udtTagPathCell In Range(.Cells(INSTANCES_ROW_HEADERS + 1, INSTANCES_COL_UDTTAGPATH), .Cells(INSTANCES_ROW_HEADERS, INSTANCES_COL_UDTTAGPATH).End(xlDown))
    udtTagPath = udtTagPathCell.Value
    deviceName = .Cells(udtTagPathCell.Row, INSTANCES_COL_DEVICENAME)
    deviceParentPath = .Cells(udtTagPathCell.Row, INSTANCES_COL_DEVICEPARENTPATH)
    deviceTagPath = deviceParentPath & "/" & deviceName
    Row = udtTagPathCell.Row
    udtInstanceParamsCurrent.RemoveAll

    ' For each parameter defined, add into a dictionary
    For Each param In Range(.Cells(Row, INSTANCES_COL_PARAMSSTART), .Cells(Row, .Cells(INSTANCES_ROW_HEADERS, 1).End(xlToRight).Column))
        paramName = .Cells(INSTANCES_ROW_HEADERS, param.Column)

        udtInstanceParamsCurrent.Add paramName, param.Value
    Next

    ' TODO: Dictionary is being overwritten. need to set this to a new instance of the dictionary
    udtInstancesCurrent.Add deviceTagPath, udtInstanceParamsCurrent
Next

A: I worked it out.. I just need to set the udtInstanceParamsCurrent to a new dictionary within the for loop instead of outside of it.
Dim udtInstancesCurrent As Scripting.Dictionary
Dim udtInstanceParamsCurrent As Scripting.Dictionary

Set udtInstancesCurrent = New Scripting.Dictionary

'''' SAVE PARAMETER VALUES ''''
' For each udt instance tag path, add its param value into a dictionary to save its values
For Each udtTagPathCell In Range(.Cells(INSTANCES_ROW_HEADERS + 1, INSTANCES_COL_UDTTAGPATH), .Cells(INSTANCES_ROW_HEADERS, INSTANCES_COL_UDTTAGPATH).End(xlDown))
    Set udtInstanceParamsCurrent = New Scripting.Dictionary

    udtTagPath = udtTagPathCell.Value
    deviceName = .Cells(udtTagPathCell.Row, INSTANCES_COL_DEVICENAME)
    deviceParentPath = .Cells(udtTagPathCell.Row, INSTANCES_COL_DEVICEPARENTPATH)
    deviceTagPath = deviceParentPath & "/" & deviceName
    Row = udtTagPathCell.Row
    udtInstanceParamsCurrent.RemoveAll

    ' For each parameter defined, add into a dictionary
    For Each param In Range(.Cells(Row, INSTANCES_COL_PARAMSSTART), .Cells(Row, .Cells(INSTANCES_ROW_HEADERS, 1).End(xlToRight).Column))
        paramName = .Cells(INSTANCES_ROW_HEADERS, param.Column)

        udtInstanceParamsCurrent.Add paramName, param.Value
    Next

    ' TODO: Dictionary is being overwritten. need to set this to a new instance of the dictionary
    udtInstancesCurrent.Add deviceTagPath, udtInstanceParamsCurrent
Next


text:
Q: moderncv: "Something's wrong--perhaps a missing \item. }" Error I am very new to Latex but I thought I would use it for my CV, I am using the moderncv template. I keep on getting the error above but only for the last line of this code (the \end{itemize}} line).
I can't see what the problem is, it seems exactly the same as the template.
\cventry{2016--2017}{\large{Teacher}}{\textsc{School}}{Place}{}{Lots of text and blah blah blah etc.
\newline{}\newline{}
\textsc{Achievements:}
\begin{itemize}[itemsep = 0ex]
    \item 97\% pass rate with grade C or above.
    \item Student placements include:
    \begin{itemize}[itemsep = 0ex]
        \item School
        \item School
        \item School
    \end{itemize}
    \newline{}
\end{itemize}}

A: *

*Help yourself and others by using structured code.

*I proposed some structure.

*For the future, I recommend, that you start by a simple code with the basic structure (see the second \cventry entry).

*The code that you provide is not compilable -- see my code for further questions. This is called an MWE.

As Ulrike Fischer points out, the [itemsep = 0ex] parts
  requires the enumitem package which people need to guess without an
  MWE. This (if the enumitem package is missing) causes the error that
  you describe.

\documentclass{moderncv}

\moderncvstyle{casual}
\moderncvcolor{blue}

\firstname{John} % Your first name
\familyname{Smith} % Your last name

\begin{document}

\section{Test Section}

%% https://tex.stackexchange.com/questions/387356
%\cventry{2016--2017}{\large{Teacher}}{\textsc{School}}{Place}{}{Lots of text and blah blah blah etc.
%\newline{}\newline{}
%\textsc{Achievements:}
%\begin{itemize}[itemsep = 0ex]
%    \item 97\% pass rate with grade C or above.
%    \item Student placements include:
%    \begin{itemize}[itemsep = 0ex]
%        \item School
%        \item School
%        \item School
%    \end{itemize}
%    \newline{}
%\end{itemize}}

\cventry{1}
    {2}
    {3}
    {4}
    {5}
    {6}

\cventry{2016--2017} %1
    {Teacher} %2
    {School} %3
    {Place} %4
    {5} %5
    {Achievements} %6

\cventry{2016--2017} %1
    {Teacher} %2
    {School} %3
    {Place} %4
    {5} %5
    {
    \begin{itemize}
    \item Achievement A
    \item Achievement B
    \item Achievement C
        \begin{itemize}
        \item Achievement C.1
        \item Achievement C.2
        \item Achievement C.3
        \end{itemize}
    \end{itemize}
    } %6

\end{document}


text:
Q: Memory Leak trackdown I have a server running Red Hat Enterprise Linux Server release 6.7.  The server runs a number of java processes including a tomcat server with nginx webserver.  The server has 12 GB of ram allocated to it.
Upon immediate startup the server shows to be using 1289 MB of ram (free -m -/+ buffers/cache line)... output below.
A "ps aux" on server startup shows the memory usage of all processes being a total of 1,290,996 k of memory (The RSS column)... The 2 numbers are pretty close.
After 2 days of uptime free -m now shows us using 10,698 MB of memory while "ps aux" totals up to 8,345,352 k for all processes.
We've attempted to stop/kill each process one by one and even with an absolute bare minimum number of things running (No Tomcat, no Java, no Nginx) we never recover the "Missing" ~2GB of ram.. The only thing we've found to recover the missing memory is to reboot the server.  If the server goes more than 3-4 days without a reboot it starts eating into swap space which eventually causes high CPU usage and the java applications running on it to crawl to a standstill.
I should also mention that this server is running as a virtual machine using VMWare.
Free -m output on startup:
             total       used       free     shared    buffers     cached
Mem:         11852       1787      10064          0         28        468
-/+ buffers/cache:       1289      10562
Swap:         8191          0       8191

Free -m output after 2 days uptime
             total       used       free     shared    buffers     cached
Mem:         11852      11625        226          0        146        779
-/+ buffers/cache:      10698       1153
Swap:         8191         43       8148

What can I do to help diagnose where the "Missing" memory goes to so that I can resolve the issue.  Any suggestions are appreciated.
Thanks!


text:
Q: Deserialize a Json complex property into a string of Json Is it possible to de-serialize a complex json object as a string. I am having trouble solving an issue similar to what is described below:
public class Model
{
    public List<int> MyList { get; set; }
    public int MyInt { get; set; }
    public string MyString { get; set; }
    public string/object/variant MyProblem { get; set; }
}

Code used in the midddle-tier
model = JsonConvert.DeserializeObject<Model>(request.Model);

The problem is that MyProblem is actually a jagged array or it comes in multiple shapes by which I can't typify the structure to allow for de-serialization in a uniform manner. Is there a way that I can force JsonConvert to treat MyProblem as a string of Json instead of an object of Json?
Moment of clarity: It appears that if I define MyProblem as an object then the de-serialization will treat it as such and then MyProblem.ToString() will yield the json object as native string.

A: It appears that if I define MyProblem as an object then the de-serialization will treat it as such and then MyProblem.ToString() will yield the json object as native string.


text:
Q: Мультирегиональность по URL в CMS BITRIX в рамках одного домена. Нужна помощь День добрый.
Такой вопрос, есть задача сделать мультирегиональность для вывода названия города в товарном каталоге, но, не через доменные имена, аля moscow.site.ru, spb.site.ru, а через URL вида: /msk/catalog/, /spb/catalog/
Сейчас, делаю это через:

*

*копирование самой папки каталога, в нужные подпапки /msk/, /spb/

*добавляю файл .section.php с кодом $arDirProperties = Array("city" =>"Москва") в данные папки.

*копирования правила обработки компонента catalog в файле urlrewrite.php.
Все, вроде бы водится корректно, но, подозреваю, что это какой-то тупиковый путь развития, ибо, если городов будет больше, чем два, то, копировать все это каждый раз, будет проблемно.
Подскажите пожалуйста, может какие-нибудь примеры кода по ссылке, где приведенная выше задача, решилась более гуманным образом?
Через urlrewrite обработка адресов каталога, или типа того?
Может за какую-нибудь адекватную цену кто возьмется сделать (500-1000 р)? черканите тогда, это тоже все обсуждается.

A: Путь тупиковый, однозначно.
Лучший вариант:

*

*Завести отдельный инфоблок с городами.

*В самом каталоге сделать привязку товаров к элементам инфоблока.

*Оставить один файл, который будет обрабатывать все города.

*Завернуть через urlrewrite.php все запросы на него

*В этом файле выбирать название города по коду, менять заголовок и настраивать фильтр для каталога.


text:
Q: Three.js raycasting does not work on DIV which is not full screen I wrote a simple web page displaying a 3D bone and using Three.js raycasting to draw dots and lines on it and it worked perfectly well. result of using raycast on full screen web page
But when I ported it to another web page having multiple windows, the process did not work.
I followed the instructions from fiddle http://jsfiddle.net/cn7ecoaa/ but still failed.
Here is the CSS:
.column2  {
    float: right;
    width: 80%;
    position: static;
}

#w3-container {
    width: 1522px;
    height: 1001px;
    position: static;
}

I loaded the model and examined it and it certainly contains mesh and buffer geometry:
result of console.log after loading the 3D model
Here is the loader code :
gltfLoader.load (
                    inputModel,

                    function(gltf)
                    {
                        scene.add(gltf.scene);
                        model = gltf.scene;
                        mesh = gltf.scene.children[0];

                        mesh.name = "tibia_glTF_01";

                        model.traverse
                        ( function ( child )
                            {

                                if ( child.isMesh && child.geometry.isBufferGeometry)
                                {
                                    const material = new THREE.MeshPhongMaterial(  {color:0x3c3c3c, emissive: 0x000000 } );
                                    child.material = material;
                                    const bg = child.geometry;
                                    console.log("Do not change geometry.");

                                }
                            }
                        );

                        getItem();  // Refresh the item list to be displayed

                        objects.push( mesh );

                    });

Here is the code for handling the onmousedown event :
function onMouseDown( event ) {
    if ( !DRAWLINE ) return;

    var raycaster = new THREE.Raycaster();

    event.preventDefault();

    mouse.x = (( event.clientX - renderer.domElement.offsetLeft) / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - (( event.clientY - renderer.domElement.offsetTop) / renderer.domElement.clientHeight ) * 2 + 1;

    console.log("mouse.x", mouse.x, "mouse.y", mouse.y);

    console.log("Objects", objects);

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects( objects );

    if ( intersects.length > 0 ) {

        alert("HIT!");

        dot.visible = true;

        // Copy the intersection points to be used in functions addPoint()
        mouse.copy( intersects[0].point );

        intersects.length = 0; // reset the variable

        addPoint();

    } else {

        console.log( "<<NO Intersection!!>>" );

    }

}

No matter what combinations I have used to cater for the offset, the result of raycasting is still "<<NO Intersection!!>>".
Any idea on how to fix this would be much appreciated!
Thanks for your help!

A: Try computing your mouse coordinates like so:
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ( ( event.clientX - rect.left ) / ( rect. right - rect.left ) ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / ( rect.bottom - rect.top) ) * 2 + 1;


text:
Q: Lauch a background process in Ruby and regist the PID What is the best way to launch multiple process in background with ruby ? I need to use Thread.new ?
I have like 5 process to launch in background then i want to get the pid to stop properly all the process.In bash i can do it easyli:
htop &
echo $! >/tmp/htop.pid

And to kill:
kill `cat /tmp/htop.pid`

I want to be able to do the same thing with Ruby

A: You could use spawn:
pid = spawn('htop')

And to Process.kill:
Process.kill('TERM', pid)


text:
Q: GWT RPC serialization I have an application using gwt RPCs as well as Ebean as ORM. Trying to upgrade Ebean from version 2.7 to 11.34, I found that the newer Ebean version does not support subclassing any more, but uses bean enhancement, which seems to confuse the gwt serializer. We had used Ebean subclassing, and actually thrown away the subclass for the cases where an entity bean was not just used on the server, but directly passed on to the gwt RPC.
As far as I see, the enhancement adds an instance of class EntityBeanIntercept to  each entity bean. As we do actually never use the beans that we get back from the client to the server to directly write them to the database, my approach was to add a CustomFieldSerializer for class EntityBeanIntercept that does nothing. However, I still get
com.google.gwt.user.client.rpc.SerializationException: Type 'io.ebean.bean.EntityBeanIntercept' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded.

I created two classes:
com.google.gwt.user.client.rpc.core.io.ebean.bean.EntityBeanIntercept_CustomFieldSerializer
com.google.gwt.user.server.rpc.core.io.ebean.bean.EntityBeanIntercept_ServerCustomFieldSerializer

with empty implementations of all serialization/deserializsation methods. By debugging, I found that nevertheless, EntityBeanIntercept is not put into the white lists for serialization/deserialization of the gwt internal SerializationPolicyLoader.
Do I need to add these custom serializers to some configuration for them to be taken into account by gwt?
By the way: current gwt version is 2.7.


text:
Q: Is there any possible ways to automatically fetch the DEX interacted users wallet addresses in the etherscan.io site? We need to know that is there any possible ways to automatically fetch the Users wallet addresses of those who swapped their tokens in a DEX exchange in the etherscan site! As we are now able track the DEX contract addresses and tokens for now. But, we do not have a clue about tracking the users wallet addresses of the DEX exchanges like uniswap, sushiswap, 1inch.
We are expecting a solution for a problem that we stated. we do not have a clue about tracking the users wallet addresses of the DEX exchanges like uniswap, sushiswap, 1inch.


text:
Q: The way to import any Stock Exchange Stock data to Google Sheets, if someone will BE ABLE TO FIGURE OUT THE IMPORT XML CODE HERE! Somebody, please write an IMPORTXML formula to get this price out of google search...
Google search link is https://www.google.com/search?q=
And if you ask it for the stock price with ticker like that https://www.google.com/search?q=ticker+096530
it will almost always get you the one you need
so the example link is https://www.google.com/search?q=ticker+096530
Please help to get the price from it. Thank You.


text:
Q: Colors and line style in ggplot2 I have 5 groups that I want to show on a plot in ggplot2 as shown in the example HERE. However I do not know how to specify that each group gets a different color in ggplot2 setting AND also different shades? So for example in the image red is group A and blue is group B. Solid line is female and dashed line is male. Yellow is reference group. Thank you!

A: Data
# random example
df <- structure(list(time = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
    6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), group = c("A", "A",
    "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B",
    "B", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C", "C", "C",
    "C", "C", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "E",
    "E", "E", "E", "E", "E", "E", "E", "E", "E"), value = c(3L, 3L,
    8L, 5L, 4L, 4L, 9L, 6L, 7L, 4L, 5L, 2L, 6L, 8L, 6L, 7L, 6L, 2L,
    4L, 10L, 3L, 7L, 3L, 2L, 8L, 6L, 5L, 3L, 1L, 7L, 6L, 9L, 7L,
    4L, 6L, 4L, 7L, 6L, 7L, 7L, 3L, 4L, 10L, 2L, 7L, 10L, 7L, 8L,
    10L, 3L)), row.names = c(NA, -50L), .Names = c("time", "group",
    "value"), class = "data.frame")

Plot
You can manually control colour and line type using scale_color_manual and scale_linetype_manual. For line type you can use numbers too:  0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash.
library(ggplot2)
ggplot(data = df) +
  geom_line(aes(
    x = time ,
    y = value,
    colour = group,
    linetype = group
  )) +
  scale_color_manual(values = c(
    A = "red",
    B = "blue",
    C = "green",
    D = "yellow",
    E = "violet"
  )) +
  scale_linetype_manual(values = c("twodash","dotted","solid", "dashed", "longdash"))


text:
Q: Why do Worf and Geordie have different ranking pips when they're both Lieutenants? In The Child (Season 2), Worf is called "lieutenant" and so is Geordie, but they have different pips (one has 1 full and 1 half pip, and the other 2).  Why is this so?

A: The reason is that there are three forms of lieutenant - lieutenant junior grade, lieutenant and lieutenant commander (see images below).  In this episode, Worf is Lieutenant (Junior grade) and Geordie is a full Lieutenant.  An example of the Lieutenant commander rank is Data.  For further reference, see this page.

Lieutenant (junior grade)

Lieutenant

Lieutenant Commander


text:
Q: Date archives for custom post type I have seen many questions/posts regarding this, but have yet to find a decent solution. Basically I am trying to do what wp_get_archives does, but for a custom post type (personally I am unsure why wp_get_archives doesn't support custom post types!).
The code I am currently using is as follows
functions.php
function Cpt_getarchives_where_filter( $where , $r ) {
  $post_type = 'events';
  return str_replace( "post_type = 'post'" , "post_type = '$post_type'" , $where );
}

sidebar-events.php
add_filter( 'getarchives_where' , 'Cpt_getarchives_where_filter' , 10 , 2 );
wp_get_archives();
remove_filter('getarchives_where' , 'Cpt_getarchives_where_filter' , 10 );

This code displays the dates (e.g. April 2014, March 2014) etc, which is great, but clicking the links just goes to a 404. The URL that is created on each date link is /2014/04/, however it should be something like /events/2014/04/.
Is there any way to include 'events' in the URL so that the archive-events.php template can be used, and is there any reason why the links currently generate a 404?
Many thanks for any help

A: What you want can be done also filtering 'month_link' for monthly archives, 'year_link' for yearly archives and 'day_link' for daily archives.
You can also write a function that extends wp_get_archives to work with CPTs, adding filters to 'getarchives_where' and to the archive link.
function wp_get_cpt_archives( $cpt = 'post', $args = array() ) {
  // if cpt is post run the core get archives
  if ( $cpt === 'post' ) return wp_get_archives($args);
  // if cpt doesn't exists return error
  if ( ! post_type_exists($cpt) ) return new WP_Error('invalid-post-type');
  $pto = get_post_type_object($cpt);
  // if cpt doesn't have archive return error
  if ( ! $pto = get_post_type_object( $cpt ) ) return false;
  $types = array('monthly' => 'month', 'daily' => 'day', 'yearly' => 'year');
  $type = isset( $args['type'] ) ?  $args['type'] : 'monthly';
  if ( ! array_key_exists($type, $types) ) {
    // supporting only 'monthly', 'daily' and 'yearly' archives
     return FALSE;
  }
  $done_where = $done_link = FALSE;
  // filter where
  add_filter( 'getarchives_where' , function( $where ) use (&$done_where, $cpt) {
    if ( $done_where ) return $where;
    return str_replace( "post_type = 'post'" , "post_type = '{$cpt}'" , $where );
  });
  // filter link
  add_filter( "{$types[$type]}_link", function( $url ) use (&$done_link, $pto, $cpt) {
    if ( $done_link ) return $url;
     // if no pretty permalink add post_type url var
     // if ( get_option( 'permalink_structure' ) || ! $pto->rewrite ) {
     if ( ! get_option( 'permalink_structure' ) || ! $pto->rewrite ) {
       return add_query_arg( array( 'post_type' => $cpt ), $url );
     } else { // pretty permalink
       global $wp_rewrite;
       $slug = is_array( $pto->rewrite ) ? $pto->rewrite['slug'] : $cpt;
       $base = $pto->rewrite['with_front'] ? $wp_rewrite->front : $wp_rewrite->root;
       $home = untrailingslashit( home_url( $base ) );
       return str_replace( $home,  home_url( $base . $slug ), $url );
     }
  });
  // get original echo arg and then set echo to false
  $notecho = isset($args['echo']) && empty($args['echo']);
  $args['echo'] = FALSE;
  // get archives
  $archives = wp_get_archives($args);
  // prevent filter running again
  $done_where = $done_link = TRUE;
  // echo or return archives
  if ( $notecho ) {
    return $archives;
  } else {
    echo $archives;
  }
}

Please read inline comments for more info on how function works.
Now there is a problem. The url like /events/2014/04/ are not recognized by WordPress, so you need to add the reqrite rules that handle that sort of urls.
Again you can write a function that add that rules for you:
function generate_cpt_archive_rules( $cpt ) {
  if ( empty($cpt) || ! post_type_exists($cpt) ) return;
  global $wp_rewrite;
  $pto = get_post_type_object($cpt);
  if ( ! $pto->has_archive ) return;
  $base = $pto->rewrite['with_front'] ? $wp_rewrite->front : $wp_rewrite->root;
  $base = trailingslashit( $base );
  $slug = is_array( $pto->rewrite ) ? $pto->rewrite['slug'] : $cpt;
  $year = ltrim( $base . $slug . '/([0-9]{4})/?$', '/' );
  $month = ltrim( $base . $slug . '/([0-9]{4})/([0-9]{2})/?$', '/' );
  $day = ltrim( $base . $slug . '/([0-9]{4})/([0-9]{2})/([0-9]{2})/?$', '/' );
  $index = 'index.php?post_type=' . $cpt;
  $rules[$year] =  $index . '&m=$matches[1]';
  $rules[$month] = $index . '&m=$matches[1]$matches[2]';
  $rules[$day] = $index . '&m=$matches[1]$matches[2]$matches[3]';
  $page = 2;
  foreach ( array( $year, $month, $day ) as $rule ) {
    $paged = str_replace( '/?$', '/page/([0-9]{1,})/?$', $rule);
    $rules[$paged] = $rules[$rule] . '&paged=$matches[' . $page . ']';
    $page++;
  }
  return $rules;
}

This function generate the rules, however, you also need to add and flush them.
Now is recommend to flush rules on theme (or plugin) activation and register them on init, so you should do something like:
function register_cpt_dates_rules() {
  $cpts = array( 'events' );
  foreach ( $cpts as $cpt ) {
    foreach ( generate_cpt_archive_rules( $cpt ) as $rule => $rewrite ) {
      add_rewrite_rule( $rule, $rewrite, 'top' );
    }
  }
}
// flushing on theme switch
add_action('after_switch_theme', function() {
  register_cpt_dates_rules();
  $GLOBALS['wp_rewrite']->flush_rules();
});
// registering on init
add_action( 'init', 'register_cpt_dates_rules' );

Once you have added these functions to your functions.php (and you have deactivated and activated again your theme to make 'after_switch_theme' run) you can display the archives using:
wp_get_cpt_archives( 'events' );

And it will display the archives for event CPT, and the link will be something /events/2014/04/.
It works also for yearly or daily archives:
wp_get_cpt_archives( 'events', array( 'type'=>'yearly' ) );
wp_get_cpt_archives( 'events', array( 'type'=>'daily' ) );

Using my two functions you have a super-easy way to make wp_get_archives works with CPTs.
Note that all the code here require PHP 5.3+.

A: I think G.M has given everything you need. I wrote a blog post on the permalink generation for CPT date archives, but haven't had the time to get the other pre_get_posts portion of it in a blog post form yet.
There's basically 3 pieces to the puzzle:

*

*Generating your rewrite rules to read the /2014/04/30, /2014/, etc. date strings.

*Getting your WP_Query to recognize the query vars.

*and creating the pagination/archive links for sidebar widgets (which my post covers).


text:
Q: How is excess bandwidth distributed in linux htb? Say I have 100kbps bandwidth
                - Root - 100kbps
                /       \
               /         \
              /           \
             /             \
            /               \
           /                 \
Assured  30kbps             10kbps

And I assure Class A 30kbps, and Class B 10kbps. 60kbps are the reserve or the excess bandwidth
In the HTB manual it says

Any unused bandwidth can be used by any class which needs it (in proportion of its allocated share).

However when I run the following test, which is illustrated in the above ascii art:
tc qdisc add dev eno1 root handle 1: htb
tc class add dev eno1 parent 1: classid 1:1 htb rate 100kbps ceil 100kbps
tc class add dev eno1 parent 1:1 classid 1:10 htb rate 10kbps ceil 100kbps
tc class add dev eno1 parent 1:1 classid 1:20 htb rate 30kbps ceil 100kbps
tc filter add dev eno1 protocol ip parent 1:0 prio 1 u32 match ip dport 8000 0xffff flowid 1:10
tc filter add dev eno1 protocol ip parent 1:0 prio 1 u32 match ip dport 8001 0xffff flowid 1:20

I get the following results: 56kbps for Class A and 37kbps for Class B
Which is a ratio of ~1.5, whereas I expected the ratio to be 3:1, as the early allocation.
It seems that the 30 and 10 were served, then the excess was divided equally between the two classes which makes sense as in the code it says that the RedBlack tree holding these two classes, the scheduler does a RR on them.
My question, is the excess bandwidth divided equally as results and code suggest? (perhaps I misunderstood the code)
Or should I be expecting a 3:1 ratio between class A and B ?

A: Look at the "quantum" in HTB docs. All unallocated bw is handled by WRR algorithm according to classe's quantums.

A: As far as I know, the "allocated share" means ceil.
So, if you want the 3:1 ratio, you need to write:
tc class add dev eno1 parent 1:1 classid 1:10 htb rate 10kbps ceil 100kbps
tc class add dev eno1 parent 1:1 classid 1:20 htb rate 30kbps ceil 300kbps

Since the root class has a ceil at 100kbps, it will not offer more than 100kbps, and the 300kbps option is only here to specify the ratio.


text:
Q: Does arm64 platforms support mavsdk-python Hello I am trying to do a human-tracking drone and I am using Nvidia Jetson nano and pixhawk 4 . lately i learned that arm platforms do not support mavsdk-python. Is there any way to use Jetson nano and mavsdk together ?
And I tried to install mavsdk-python to Jetson nano but I couldn't.


text:
Q: Anyone attempted to perform automated tasks through the PCOMM or x3270 using Perl? Anyone attempted to  perform automated tasks through the PCOMM or x3270 using Perl?  I am doing some operations on Mainframe through PCOMM and x3270. Since some tasks include many repeatable operations, I am trying to find an easy way to automate these tasks on Mainframe.
BTW, Perl is my favorite language, so just mentioned Perl here.

A: I am not mainframe guy, but check this out
http://www.perlmonks.org/?node=611038
"I automate 3270 applications from Perl by using the IBM Personal Communications 3270 terminal emulator on Win32 via Win32::OLE. It is very well documented and it works very good."
This with example code: http://www.perlmonks.org/?node_id=674214
Using IPC to drive the session:
http://www.linuxquestions.org/questions/linux-software-2/how-do-i-use-s3270-x3270-for-scripting-767067/
I hope this help.
regards,

A: You should do some research on QUOTE SITE FILETYPE=JES.  This allows you to FTP batch jobs straight into the JES Spool.  I do this dozens of times a day (maybe hundreds) to get my PC to accomplish tasks on the mainframe.  If it can be done in batch, then this is a great way to do it.  And of course, Perl is an excellent way to create and manipulate the JCL before it's submitted.
Another thing to look into, if you Telnet to the mainframe, it opens a TSO command dialog (just like option 6 in TSO).  There are many things you can do there too.  Of course, if you're doing IPLs and the like, you already know this.
My trouble is that I am not a systems programmer so I cannot control the settings of the mainframe.  There are many settings that my company's systems guys are too lazy to look into, so they just shut them down out of hand.  I discovered the Telnet thing about a year ago, which I was using to see if a job had finished (that's the hard part of this... knowing when the job is done).  Next thing I know, the Telnet access had been disabled.
I have tons of things that allow me to do things on the mainframe via Perl.  Hit me up and I'd love to share them with you.


text:
Q: U2 Basic Developer Toolkit Does anyone here run the Basic Developer Toolkit with UniData 7.1?
Even though the IDE was released with UniData 7.2, I was given the impression that it works fine with 7.1. However, when opening up "Database Files" in an account, every single DIR type file gives a loading error dialog and doesn't register any records in them.
Are changes needed the the UniData server before the IDE works with 7.1, or is something else afoot here. As far as I know it just uses UniObjects for Java to talk to the UniData RPC daemon, so there shouldn't be any issues with communications.
Working with a decent IDE would be nice...

A: You can run BDT on older releases and we developed a Tech Note to explain how to install what you need. This doc was released with U2 Technical Resource Kit for 2009-10 if you got a copy of that at U2U. If not and you are on support you can access the doc online at: https://u2tc.rocketsoftware.com/documentation/display.asp?id=1392476.

A: BDT was released for Unidata 7.2.  There is another Eclipse IDE for U2 that works for Unidata 6.0 and above called XLr8Editor for U2logic.  You can get a trial for free just follow the download instructions at www.u2logic.com/downloads.html.
Regards,
Doug


text:
Q: R group time column by condition eg. hourly I have a time column like below.
Tcol <- as.data.table(c(1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326, "NA"))
Tcol$V1= as.numeric(gsub("\\D+", "", Tcol$V1))
Tcol$V1[is.na(Tcol$V1)] <- 100
Tcol$V1 <- chron::chron(times=Tcol$V1)

Glimpse(Tcol)
Observations: 12
Variables: 1
$ V1 <S3: times> 1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326,  100

I would like to group them by 1 hour blocks or 2 hours blocks for plotting.  ie.
100   1
1200  2
1300  2
1700  3
1900  1
2300  1

Searching other solutions on SO, it seems, I should be using cut().  But every time I apply cut(), I get an error.
table(cut(Tcol$V1, breaks="hour"))
Error in breaks + 1 : non-numeric argument to binary operator

I'm unable to find another post with the same issue to solve my issue.  So I'm hoping someone can help.

A: If I get it right, then your V1 column contains time in format hm.
I do not understand what you are trying to accomplish using chron function, but in your place, I would extract from V1 only hour and then work with that.
# for 1 hour intervals:
Tcol[, h := as.integer(substr(V1, 1, 2))]
Tcol[, .N, by = h]

#for different intervals
breaks <- seq(0, 24, by = 2) # define breaks
Tcol[, newintervals := cut(h, breaks = breaks)]
Tcol[, .N, by = newintervals]

A: Tcol[,.(Count=length(.I)),by=.(Hour=100*floor(V1/100))]


text:
Q: Problems in applying pattern at same time to restrict range and specific characters I need to apply pattern to one of my field in angularjs code. It needs to fulfill following conditions:

The value must be between 1 - 50 characters long. Name can contain only >letters, numbers, periods, hyphens, and underscores. Name must start and end >with a letter or number.
I have tried this pattern
  /^[a-zA-Z0-9][a-zA-Z0-9-_.]{0,48}[a-zA-Z0-9]$/
It works well for all other conditions except it accepts atleast two >characters.

I have tried many variations, but either range is compromised, or I face problem in restricting hyphens and underscores at start. Any help will be appreciated. Thanks.

A: You can use this regex,
^[a-zA-Z0-9](?:[\w.-]{0,48}[a-zA-Z0-9])?$

Explanation:

*

*^ - Matches start of string

*[a-zA-Z0-9] - Starts matching with an alphabet or digit

*(?: - Start of non-grouping pattern

*[\w.-]{0,48}[a-zA-Z0-9] - What next matches can be alphabets, digits, periods, underscore and hyphen but the last character should be an alphabet or digit

*)? - Non-group pattern closed and ? makes it optional so as to allow only one character as a valid variable

*$ - End of string

Regex Demo (For making demo easier to play with strings, I have reduced the length condition to 1-5 instead of 1-50 as asked in question)


text:
Q: Can you get three stars on all Angry Birds Space levels using only one bird? I have been playing Angry Birds Space for a few days so far (90 out of 90 stars for Pig Bang), and so far to get three stars, you need to finish all of the levels with only one bird. I was wondering if this is true for the rest of the game. Thanks!

A: No, this is not true for all levels. Using less birds is only more efficient if the amount of damage done by each additional bird will net you less than 10 000 points, the amount of score you get for each bird not used.
For instance, Pig Bang 1-14 can be completed with only one bird, but to get three stars you would need to use all three to cause the maximum amount of damage, as per my answer here: https://gaming.stackexchange.com/a/57853/3936


text:
Q: UIViewController not being released when popped I have a table view that when a cell is selected it pushes a view controller onto the navigation stack:
SAPostTableViewController *postViewController = [[SAPostTableViewController alloc] initWithNibName:NSStringFromClass([SAPostTableViewController class]) bundle:nil];
postViewController.site = site;
[self.navigationController pushViewController:postViewController animated:YES];
[postViewController release];

SAPostTableViewController has a static tableView which, and it's cells, are loaded from a nib.
I have overridden the initWithNibName:bundle: method:
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.sections = [NSMutableDictionary dictionary];
    }
    return self;
}

sections is a retained property.
In viewDidLoad of SAPostTableViewController I have this:
- (void)viewDidLoad
{
    [super viewDidLoad];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cellVisibiltyChanged:) name:@"SAStaticCellVisibiltyChanged" object:nil];
}

and so to match in viewDidUnload:
- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SAStaticCellVisibiltyChanged" object:nil];
}

However when I press the back button in the navigation bar (all standard behaviour, no override) and SAPostTableViewController is popped, it doesn't call viewDidUnload or dealloc. So this means that if I then reselect the cell that pushes SAPostTableViewController it creates a new instance of SAPostTableViewController and repeating this back and forward just means the memory usage keeps increasing as the popped SAPostTableViewControllers never get deallocated. (I know this by running Instruments on allocations)
The weird thing is that if I release SAPostTableViewController twice then it works as I'd expect:
SAPostTableViewController *postViewController = [[SAPostTableViewController alloc] initWithNibName:NSStringFromClass([SAPostTableViewController class]) bundle:nil];
postViewController.site = site;
[self.navigationController pushViewController:postViewController animated:YES];
[postViewController release];
[postViewController release];

(If I add a third release statement, it crashes as I'd expect it to with just 2)
I have resorted to using retainCount and stepped through the lines of code the are executed in the first line of the directly above code, the retainCount remains at 1. It jumps up between the first and second line, so I can't see anywhere it is being retain an extra time?
The SAPostTableViewController is only used in this place, it is not a delegate of anything, nor does it have a delegate.
How can I find a fix, or is it something simple I've missed?
Here is what Instruments shows after pushing SAPostTableViewController just once (with only one release statement):

And what it shows after navigating back and forth repeatedly (again, one release statement):

A: You are creating a new Object when you clic one Cell, why you don't create your Object (SAPostTableViewController) in the init Method and then Push the same object watch time you click in Cell
you can do something like this :
postViewController = [[SAPostTableViewController alloc] initWithNibName:NSStringFromClass([SAPostTableViewController class]) bundle:nil];

and in the
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
postViewController.site = site;
[self.navigationController pushViewController:postViewController animated:YES]; [postViewController release];

    }

A: I don't know what your problem is, but here are some things to consider:

*

*You should absolutely NOT release the view controller twice.  If you have indeed discovered a memory leak in UIKit (which is unlikely), then it is likely it would be fixed in a future version of UIKit.  That means that anyone running an old version of your app on a new version of the operating system would experience nothing but crashes (due to over-releasing the view controller).  It is better to leak than to crash.  A leaky app is still a usable app (at least until you leak too much).  But a crashing app can't be run at all.

*-viewDidUnload is not doing what you think it should be doing.  It is only called when the view controller's view is unloaded due to memory pressure.  It is not called during normal deallocation.  It would be wiser to rely on -viewWillAppear: and -viewDidDisappear: instead.


text:
Q: Finding the limit $\lim_{n\to \infty}\int^n_0 e^{-\lambda x}\mathrm dx$ Find the following limit:
$$\lim_{n\to \infty}\int^n_0 e^{-\lambda x}\mathrm dx$$
for all $\lambda>0$.

A: $$\int_0^n e^{-\lambda x}dx=\left[\frac{-1}{\lambda}e^{-\lambda x}\right]_0^n=\frac{1}{\lambda}\left(1-e^{-\lambda n}\right)\underset{\infty}\longrightarrow\frac{1}{\lambda}$$

A: let $u = -\lambda x, du = -\lambda dx$ then we have:
$$\lim_{n \to \infty} \int_0^n e^{-\lambda x}dx = \lim_{n\to \infty}\frac{-1}{\lambda}\int_0^{-\lambda n} e^u du$$
Note that the limits of integration change from $x = 0, x=n$ to $u=0, u=-\lambda n$ since we plug in those values to $u = -\lambda x$.
$$= \lim_{n \to \infty} [-\frac{1}{\lambda} e^u ]_0^{-\lambda n} = \lim_{n \to \infty}\frac{1}{\lambda}(1 - e^{-\lambda n}) = \frac{1}{\lambda}(1-\lim_{n \to \infty}e^{-\lambda n}) = \frac{1}{\lambda}$$

A: Try the substitution $u=-\lambda x$, $du=-\lambda dx$.


text:
Q: How/if to use android.provider.CallLog.Calls.LIMIT_PARAM_KEY I ran into this const [android.provider.CallLog.Calls.LIMIT_PARAM_KEY][1].
It is for some reason greyed out in the documentation, and when I try to use it, the app crashes (sqlite error)
Does anyone know how to use this? (if we at all should use it)

A: You just need to use a Uri.Builder and append the query parameter:
    Uri limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
        .appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, "50").build();

will limit the response to 50.


text:
Q: Inserting numbers (floats) in Elasticsearch with the node client library I'm trying to insert documents into Elasticsearch, they come as a format like:
  {
  total: 1,
  subtotal: 1.2,
  totalDiscount: 0}

The issue I'm having is with the zeroes, in JavaScript you can't force '0' to be represented as '0.0' or '0.00'.
I can't use text in the mappings in ES, as I want to obviously do mathematical operations on these fields. So I'm using a 'float' mapping for all of the above.
So, for each of those fields I have something like:
"subtotal": {
   "type": "float"
   },

I've tried all sort of different combinations, storing them as 'text' doesn't let me query them as I want, if I don't define the mapping I get a 'long' type for the fields, which truncates them, If I use float I get an exception mapper [totalDiscount] cannot be changed from type [float] to [long], if I remove them complitely, so skipping the save I get an error too
Rejecting mapping update to [...] as the final mapping would have more than 1 type
Any help much appreciated, thanks.

A: Update:
the scaled_float didn't work well for me, so I ended up doing this "the stripe way"
i.e. representing all monetary amounts in cents, safe, less space on disk, just works without having to define a mapping.
also used this https://currency.js.org/ to make sure the multiplication and output wouldn't suffer from the 'well known' issues with floats in JS.

A: as this might be useful to someone reading, I think the answer might be using this sort of mapping:
"price": {
"type": "scaled_float",
"scaling_factor": 100
}

not only is more disk-efficient, but it won't have the above issues.
I'll keep this thread updated, to see if that works.

A: I am not familiar with the node client library, but in elasticsearch, the errors signify that -
mapper [totalDiscount] cannot be changed from type [float] to [long]

From the above error, it seems as if when you created the index, totalDiscount field, was defined with the float field data type and now you are changing it to the long data type. This is not possible, that is why the above error is thrown.
Rejecting mapping update to [...] as the final mapping would have more than 1 type

This error occurs because types are deprecated in APIs in 7.0, with breaking changes to the index creation, put mapping, get mapping, put template, get template and get field mappings APIs. Refer to this to know more about the removal of mapping types.


text:
Q: notify_url not working anymore in PayPal for my sandbox I don't see any log regarding this on my rails console.
I assume that this notify_url is called at the time of payment transaction.
Thanks in advance

A: I need more info, but:

*

*check that your notify_url is absolute

*check that your notify_url is a name and not an IP address

notice that:

*

*i experienced short periods of sandbox inactivity

*time between request and response is 30 seconds more or less in my country


text:
Q: bit vectors in c++ Recently I heard about bit vectors, but i cant really find any useful info or tutorials on this topic. Can you please suggest a book or a quick tutorial on how to implement your own bit vector classes? Thank you.
---/// i cant post answers to my own questions, so i decided to edit this post. here is what i have just found: "Data Structure for Game Programmers - Ron Penton and Andre Lamothe". Chapter 4, Bitvectors. This book has thorough explanation of bit vectors, and how to make a bit vector class yourself. have fun.

A: Here is a very simple statically sized bit vector implementation. It requires C++11 to function since it relies on the <cstdint> header, but this header is fairly commonly found since it's based on a C99 feature. In a pinch you can use the C <stdint.h> header and simply use types in the global namespace instead.
Note: This was typed on-the-fly and isn't tested at all. I didn't even verify it would compile. So, there may be errors.
#include <cstdint>  // ::std::uint64_t type
#include <cstddef> // ::std::size_t type
#include <algorithm>

class my_bitvector_base {
 protected:
   class bitref { // Prevent this class from being used anywhere else.
    public:
      bitref(::std::uint64_t &an_int, ::std::uint64_t mask)
           : an_int_(an_int), mask_(mask)
      {
      }

      const bitref &operator =(bool val) {
         if (val) {
            an_int_ |= mask_;
         } else {
            an_int_ &= ~mask_;
         }
         return *this;
      }
      const bitref &operator =(const bitref &br) {
         return this->operator =(bool(br));
      }
      operator bool() const {
         return ((an_int_ & mask_) != 0) ? true : false;
      }

    private:
      ::std::uint64_t &an_int_;
      ::std::uint64_t mask_;
   };
};

template < ::std::size_t Size >
class my_bitvector : public my_bitvector_base {
 private:
   static constexpr ::std::size_t numints = ((Size + 63) / 64);
 public:
   my_bitvector() { ::std::fill(array, array + numints, 0); }

   bool operator [](::std::size_t bitnum) const {
      const ::std::size_t bytenum = bit / 64;
      bitnum = bitnum % 64;
      return ((ints_[bytenum] & (::std::uint64_t(1) << bitnum)) != 0) ? true : false;
   }
   bitref operator[](::std::size_t bitnum) {
      const ::std::size_t bytenum = bit / 64;
      bitnum = bitnum % 64;
      ::std::uint64_t mask = ::std::uint64_t(1) << bitnum;
      return bitref(ints_[bytenum], mask);
   }

 private:
   ::std::uint64_t ints_[numints];
};

// Example uses
void test()
{
    my_bitvector<70> bits; // A 70 bit long bit vector initialized to all false
    bits[1] = true; // Set bit 1 to true
    bool abit = bits[1]; // abit should be true.
    abit = bits[69]; // abit should be false.
}

The whole my_bitvector_base thing is to create a sort of private type. You can mention it in the interface or implementation for derived classes because it's protected, but you can't mention it other contexts. This prevents people from storing a copy of a bitref. This is important because a bitref only really exists to allow assignment to the result of operator [] because the C++ standards committee, in all their wisdom, has not implemented operator []= or something similar for assigning to an array element.
As you can see, a bit vector is basically an array of bits. Fancier bit vectors will simulate an 'infinite' array of bits all initialized to true or false. They do this by tracking the very last bit that has been set and all bits before it. And if you ask for a bit after that, they just return the initialized value.
A good bit vector will also implement operator & and other such niceties so they behave sort of like a very large unsigned integer with reference to bit manipulation operations.

A:
vector<bool> is a specialization of the vector template. A normal bool variable requires at least one byte, but since a bool only
  has two states the ideal implementation of vector is such that
  each bool value only requires one bit. This means the iterator must be
  specially-defined, and cannot be a bool*.

from Thinking CPP Vol-2 from Bruce Eckel
chapter 4: STL Containers & Iterators
The book can be downloaded for free at
http://www.mindviewinc.com/Books/downloads.html
and it contains more informations on bits and C++


text:
Q: Accessing attributes on fields using extension method I want to check custom attributes on my class members (fields only) by using an extension method.
public class DatabaseIdAttribute : Attribute
{
    public int ID { get; set; }

    public DatabaseIdAttribute(int id)
    {
        this.ID = id;
    }
}

public class MyClass
{
    [DatabaseId(1)]
    double Height {get;set;}

    [DatabaseId(2)]
    double Width {get;set;}

    double Area { get { return this.Height * this.Width; }
}

I want to use LINQ expression in the extension method to access the class field instead of passing magic strings.
var myClass = new MyClass();
var attribute = myClass.GetAttribute<DatabaseIdAttribute>(c => c.Height);

Is it possible to achieve?
[EDIT]
For the time being, I have achieved the following with the help of @leppie
    public static MemberInfo GetMember<T, R>(this T instance, Expression<Func<T, R>> selector)
    {
        var member = selector.Body as MemberExpression;
        if (member != null)
        {
            return member.Member;
        }
        return null;
    }

    public static T GetAttribute<T>(this MemberInfo member) where T : Attribute
    {
        return member.GetCustomAttributes(false).OfType<T>().SingleOrDefault();
    }

which enables to get the attribute in the following way
var c = new MyClass();
var attribute = c.GetMember(m => m.Height).GetAttribute<DatabaseIdAttribute>();

but I want to be able to access it in the following way
var c = new MyClass();
var attribute = c.GetAttribute<DatabaseIdAttribute>(m => m.Height);

A: You are almost there! This should work (untested).
public static class ObjectExtensions
{
    public static MemberInfo GetMember<T,R>(this T instance,
         Expression<Func<T, R>> selector)
    {
        var member = selector.Body as MemberExpression;
        if (member != null)
        {
            return member.Member;
        }
        return null;
    }

    // unnecessary in .NET 4.5 and up, see note!
    public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute
    {
       return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T;
    }
}

Usage:
var attr = someobject.GetMember(x => x.Height).
              GetAttribute<DatabaseIdAttribute>();

Note: As of .NET 4.5 and up (including .NET Core), the BCL provides a GetCustomAttribute<T>(MemberInfo) extension method that functions identically to the GetAttribute method defined above, and should be used instead if available.

A: If you don't mind supplying the extra generic types, you can do this:
public static class ReflectionHelper
{
    public static TAttr GetAttribute<TClass, TProp, TAttr>(Expression<Func<TClass, TProp>> selector) where TAttr : Attribute
    {
        var member = selector.Body as MemberExpression;
        return member.Member.GetCustomAttributes<TAttr>(false).First();
    }
}

Then you can use it like this:
var attribute = ReflectionHelper.GetAttribute<MyClass, double, DatabaseIdAttribute>(m => m.Height);

Note that this is not an extension method (as we can't have static extensions) so there is no need to create an instance of your class.
Of course you could still have the extension method version:
public static TAttr GetAttribute<TClass, TProp, TAttr>(this TClass instance, Expression<Func<TClass, TProp>> selector) where TAttr : Attribute
{
   var member = selector.Body as MemberExpression;
   return member.Member.GetCustomAttributes<TAttr>(false).First();
}

Which would let you call it like so:
var c = new MyClass();
var attribute = c.GetAttribute<MyClass, double, DatabaseIdAttribute>(m => m.Height);

But either way is quite verbose. If you want the compile to infer all of the generic types, we'd need to pass in an instance of our attribute:
public static class ReflectionHelper
{
    public static TAttr GetAttribute<TClass, TProp, TAttr>(TAttr attribute, Expression<Func<TClass, TProp>> selector) where TAttr : Attribute
    {
        var member = selector.Body as MemberExpression;
        return member.Member.GetCustomAttributes<TAttr>(false).First();
    }
}

Usage:
var attribute = ReflectionHelper.GetAttribute(new DatabaseIdAttribute(), m => m.Height);


text:
Q: Dual vector space. Let $V = \oplus_{n \geq 0} V_n$, where $V_0, V_1, \ldots, V_n, \ldots$ are finite dimensional vector spaces. Why we have
\begin{align}
V^* = \prod_{n \geq 0} V_n^*,
\end{align}
but not
\begin{align}
V^* = \oplus_{n \geq 0} V_n^*?
\end{align}
Here $V^*$ is the dual vector space of $V$ and $V_i^*$ is the dual vector space of $V_i$. Thank you very much.

A: For example: if $\pi_n:V \to V_n$ denotes the projection map, and if we select non-zero maps $f_n \in V_n^*$ for each $n$, then the map $F \in V^*$ given by
$$
F(x) = \sum_{n \geq 0} f_n(\pi_n(x))
$$
is not an element of $\bigoplus_{n \geq 0} V_n^*$.  Note that this map is well defined over $\bigoplus V_n$, but not over $\prod V_n$.

A: Let $W$ be any vector space. By definition of the direct sum (i.e. coproduct in the category of vector spaces), for every sequence of linear maps $T_n:V_n\to W$ there is a unique linear map $T:V\to W$ such that $T\circ i_n=T_n$ where $i_n:V_n\to V$ is the inclusion map.
Now let $S_n:W\to V_n^*$ be a sequence of linear maps. Taking the dual maps of this sequence we have $S_n^*:(V_n^*)^*\to W^*$, and since $(V_n^*)^*\cong V_n$ canonically we have a sequence $S_n^*:V_n\to W^*$. By assumption, there is a unique linear map $T:V\to W^*$ such that $T\circ i_n=S_n^*$, and its dual $T^*:W\to V^*$ satisfies $$(T\circ i_n)^*=i_n^*\circ T^*=S_n$$ uniquely. Since this is true for any $W$ and any sequence $S_n$, it follows that $V^*$ is a product of the spaces $V_n^*$ with projection maps $i_n^*:V^*\to V_n^*$.
Basically the idea here is that
$$
\hom(\oplus A_n,B)=\prod\hom(A_n,B)
$$
since the product and coproduct are dual constructions, and the direct sum is a coproduct.


text:
Q: Razor view with asp.net core not working I'm still trying to get my head around asp.net core so this may be a stupid question but I can't get a razor view to work with asp.net core mvc.
I'm getting a 500 error when I'm trying to return a view and not getting anything useful in the console logging.
My project.json:
{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
        "Microsoft.AspNetCore.Mvc": "1.0.1",
        "Microsoft.Extensions.DependencyInjection": "1.0.0",

        "Microsoft.AspNetCore.Mvc.Razor": "1.0.1",
        "Microsoft.AspNetCore.StaticFiles": "1.0.0",
        "Microsoft.Extensions.Logging.Console": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  }
}

Program.cs:
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace aspnetcoreapp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Startup.cs:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;

namespace aspnetcoreapp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Debug);

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
            routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

            app.Run(context =>
            {
                return context.Response.WriteAsync("Hello from ASP.NET Core!");
            });
        }
    }
}

Home.cs:
using Microsoft.AspNetCore.Mvc;
//using System.Text.Encodings.Web;

namespace MvcMovie.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /HelloWorld/

        public IActionResult Index()
        {
            return View();
        }

        //
        // GET: /HelloWorld/Welcome/

        public string Welcome()
        {
            return "This is the home Welcome action method...";
        }
    }
}

and I have a basic view in /Views/Home/Index.cshtml
any help would be greatly appreciated.
thanks

A: how annoying.
after hours of head banging, then posting the question, on my "one last go" I found the answer.
after debugging in VSCode i was able to get the actual error message.
then I found Internal Server Error while running a simple .Net Core MVC application on Ubuntu 16.04 and this had the answer.
time to go and try and find out what "preserveCompilationContext" actually does now.
thanks


text:
Q: VBA - Error Handling for Creating New Sheets Based on File Names I got the code below to create and name worksheets according to files in a folder:
Link: Creating Worksheets based on Filenames
Sub test()
  Dim Filenames As Variant, strFilename As Variant, strPath As String
  Dim i As LongPtr

  strPath = "D:\myPath"
  strFilename = Dir(strPath & "\" & "*.xlsx")
  Do Until strFilename = ""
    Filenames = Filenames & "|" & strFilename
    strFilename = Dir
  Loop

  Filenames = Mid(Filenames, 2)
  Filenames = Split(Filenames, "|")  ' <- all .xlsx filenames in this array

  For i = LBound(Filenames) To UBound(Filenames)
    with Worksheets.Add
      .name = Left(Filenames(i), Len(Filenames(i)) - 5)
    end with
  Next i

End Sub

However, I now require Error Handling for:
1) If the sheet name already exists
2) To exclude certain files in the directory by file name - This isn't such a huge issue, but if it can be done that would be really great
Here is some code for the first problem - but I don't know how to implement it as the parameters are a string:
Function sheetExists(sheetToFind As String) As Boolean
    sheetExists = False
    For Each Sheet In Worksheets
        If sheetToFind = Sheet.Name Then
            sheetExists = True
            Exit Function
        End If
    Next Sheet
End Function

Here is some code for the second problem:
For i = LBound(Filenames) To UBound(Filenames)

        Do While Filenames <> "test.xlsx"

            With x.Worksheets.Add
            .Name = Left(Filenames(i), Len(Filenames(i)) - 5)
        Loop

    End With

    Next i

With either the Do While or If Else Statement, I keep getting the error:

Loop without Do While

or

End If without Block If

or

Else Without If

I have posted this question at the below 2 links as well:
http://www.tek-tips.com/viewthread.cfm?qid=1785646
https://www.experts-exchange.com/questions/29091353/Creating-Worksheets-based-on-Filenames.html?anchor=a42513369&notificationFollowed=205670107#a42513369

A: I think you are after the code below:
Option Explicit

Sub test()

Dim strFilename As String
Dim strPath As String
Dim WB As Workbook

Set WB = ThisWorkbook ' define which workbook you want to add the sheets
strPath = "D:\myPath\"
strFilename = Dir(strPath & "*.xlsx")

Do Until strFilename = ""
    strFilename = Split(strFilename, ".")(0)

    ' check is strFilename already exists in existing sheets

    If sheetExists(strFilename) = False Then ' doesn't exist
        WB.Sheets.Add(After:=WB.Sheets(WB.Sheets.Count)).Name = strFilename
    Else
        ' just raise a message box
        MsgBox "Worksheet " & strFilename & " already exists.", vbInformation
    End If
    strFilename = Dir
Loop

End Sub

Function sheetExists(sheetToFind As String) As Boolean

    sheetExists = False
    For Each Sheet In Worksheets
        If sheetToFind = Sheet.Name Then
            sheetExists = True
            Exit Function
        End If
    Next Sheet

End Function


text:
Q: javascript variables and google maps distance service I use Google Maps Distance Service API to get driving distance and time between two points.
Here's my code:

I would like to get the distance and time between the points with a "console.log", but when I type console.log("Distanza: "+distanza); the javascript console says: "distanza is not defined"...
How could I access these two variables also outside the function?

A: There are multiple issues in the code you posted that I can see by just having a quick look (understand: I did not test it).
Declare your variables properly. Like var distanza = 0; that would be the first advice.
Also if you declare a variable within a function, it will only be available from within that function. That is called variables scope. If you need a variable to be available in other places, declare it in the global scope (outside of any function).
Then you should do your console.log within your showGeocodedAddressOnMap which is the callback function you used for the geocoder. Geocoder is asynchronous, so at the point where you do your console.log, it is very likely that the geocoder has not returned anything yet.
Below is an untested, corrected version of your code.
var durata, distanza;

function initMap() {
  var bounds = new google.maps.LatLngBounds;
  var markersArray = [];

  var origin1 = "<?php echo $partenza; ?>";
  var destinationA = "<?php echo $destinazione; ?>";

  var destinationIcon = 'https://chart.googleapis.com/chart?' +
    'chst=d_map_pin_letter&chld=D|FF0000|000000';
  var originIcon = 'https://chart.googleapis.com/chart?' +
    'chst=d_map_pin_letter&chld=O|FFFF00|000000';
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 55.53,
      lng: 9.4
    },
    zoom: 10
  });
  var geocoder = new google.maps.Geocoder;

  var service = new google.maps.DistanceMatrixService;

  distanza = 0;
  service.getDistanceMatrix({
    origins: [origin1],
    destinations: [destinationA],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    if (status !== 'OK') {
      alert('Error was: ' + status);
    } else {
      var originList = response.originAddresses;
      var destinationList = response.destinationAddresses;
      var outputDiv = document.getElementById('output');
      outputDiv.innerHTML = '';
      deleteMarkers(markersArray);

      var showGeocodedAddressOnMap = function(asDestination) {
        var icon = asDestination ? destinationIcon : originIcon;
        return function(results, status) {
          if (status === 'OK') {
            map.fitBounds(bounds.extend(results[0].geometry.location));
            markersArray.push(new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
              icon: icon
            }));

            distanza = results[0].distance.value;
            durata = results[0].duration.value;

            console.log("Distanza: " + distanza);
            console.log("Durata: " + durata);

          } else {
            alert('Geocode was not successful due to: ' + status);
          }
        };
      };

      results = response.rows[0].elements;
      geocoder.geocode({
          'address': originList[0]
        },
        showGeocodedAddressOnMap(false));

      geocoder.geocode({
          'address': destinationList[0]
        },
        showGeocodedAddressOnMap(true));
      outputDiv.innerHTML += results[0].distance.text + ' in ' +
        results[0].duration.text + '
';

      distanza = results[0].distance.value;
      durata = results[0].duration.value;

      document.innerHTML = distanza + "
" + durata;

    }
  });
}

function deleteMarkers(markersArray) {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}


text:
Q: Possible to add a nonArray property key with array literal notation? Let's say I have an array and then I add a non-array-index object property to it:

let a = [1,2,3];
a['tobey'] = 'marguire';
for (let [idx, elem] of Object.entries(a)) {
    console.log(idx, '==>', elem);
}

Is there a way to do this directly with the literal notation, or does it need to be added separately using only dot/bracket setter notation?I suppose one way might be this, but maybe it doesn't make the intent clear:

let a = {...[1,2,3], tobey: 'maguire'};
for (let [idx, elem] of Object.entries(a)) {
    console.log(idx, '==>', elem);
}

A: I don't recommend this, but one way would be the following:

const a = [1,2,3];
Object.defineProperty(a, 'tobey', { value: 'maguire', enumerable: true });

for (let [idx, elem] of Object.entries(a)) {
    console.log(idx, '==>', elem);
}


text:
Q: Why is indexingIterator.next() using dynamic dispatch? Why is for-in slower than while in swift debugging mode?
I wrote this.
Thanks for people who answer to me,  I could have learned Seqeunce and IteratorProtocol.
So I implemented custom type ( School below code  )  which conformed Sequence.
And I checked Xcode-time profile.
But I can't find anything protocol witness

But If only use range and for-in , time profiler show  protocol witness.

why is indexingIterator.next() using dynamic method but not in School ?
I thought that even struct conformed protocol, if variable in struct type use method of protocol, this method will be static method.  If I am wrong, Could you please tell me what is wrong?
⬇School code
struct SchoolIterator: IteratorProtocol {

    private var schoolList: School
    var idx = 0
    init(_ school: School) {
        self.schoolList = school
    }

    mutating  func next() -> String? {
        defer { idx += 1 }
        guard schoolList.count-1 >= idx
            else { return nil }

        return schoolList[idx]
    }
}

struct School: Sequence {
    fileprivate var list = Array(repeating: "school", count: 100000)
    var count: Int { return list.count }

    subscript(_ idx: Int ) -> String? {
        guard idx <= count-1
            else { return nil }
        return list[idx]
    }
    func makeIterator() -> SchoolIterator {
        return SchoolIterator(self)
    }
}
var schools = School()
for school in schools {
    print(school)
}

A: Your for loop translates to:
var schools = School()
var iterator = schools.makeIterator()
while let school = iterator.next() {
    print(school)
}

Notice how nothing here is a protocol. schools is of type School, iterator is of type SchoolIterator, everything that next does (like accessing schoolList.count, or the subscript of schoolList) deals with structs too. The key point is that the compiler can figure out exactly which member you mean, because its (compile-time) type is a struct. There is no need to look up witness tables.
Compare that to, e.g.
func f<S: Sequence>(_ s: S) {
    for thing in s {
        ...
    }
/*
    var iterator: S.Iterator = s.makeIterator()
    while let thing = iterator.next() {
        ...
    }
*/
}

f(School())
f(1..<100)

How would the compiler dispatch the calls to iterator.next()? I've deliberately added the type annotation to make it clear what's happening - this time, the compiler doesn't know which next you mean. Is it IndexingIterator.next()? Or SchoolIterator.next()? Or SomeOtherIterator.next()? Keep in mind that I can call f with any kind of Sequence! That's why it needs to look up the witness table of the actual type of S.Iterator at runtime - it is impossible to figure out which next to call.
As for why for i in 0..<100 uses dynamic dispatch, well, on first sight, there seems to be all structs:
let range: Range<Int> = 0..<100
var iterator: IndexingIterator<Range<Int>> = range.makeIterator()
while let i = iterator.next() {
    ...
}

However, iterator.next actually does something like this:
public mutating func next() -> Elements.Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
_elements is defined like this:
public struct IndexingIterator<Elements: Collection> {

  internal let _elements: Elements

_elements could be any kind of Collection, so again, we don't know which member _elements[_position] or _elements.formIndex refers to at compile time. Is it Array.formIndex? Or Set.formIndex? We only know at runtime, when we know what Elements is.
Recommended reading: https://medium.com/@venki0119/method-dispatch-in-swift-effects-of-it-on-performance-b5f120e497d3