text:
Q: are cranial measurements discrete or continuous data? I have to find which formula to use to calculate if there is an outlier in this piece of data. They are cranial measurements (Cranial length, Cranial height, Cranial Breadth and Facial Projection Length) which consist of whole numbers like (170mm,180mm,173mm) etc. I am not sure if this is an example of discrete data or continuous. I know discrete is like 24 students and continuous is like 6.5, 6.6 etc. but i know that continuous is a measurement of something which is confusing me because mm is a measurement but all the numbers are whole numbers. Can someone please help me?

A: Cranial measurements are continuous data. It is round because you are measuring it in mm, imagine you measure it in cm, then you would have decimals.
It would be discrete if you classify it into catergories for example, but given your example, your raw data is continuous.


text:
Q: Asp.net master/content page caching problem On my master page is repeater control, which basically puts together my site navigation.  It is driven by an ObjectDataSource with caching enabled, it uses SqlCacheDependency to notify itself when a page is added or removed from the database.
Now, on my content page, i am using the following:
<%@ OutputCache Duration="999999" VaryByParam="slug" SqlDependency="SiteDataCaching:MenuHeaders" %>

And then access my dl to put together the pages title, content, metadescription etc etc.
The content page will refresh the cache no worries, but for some reason, if i am on page that has the OutputCache enabled, my menu on the masterpage won't update itself unless i forcefully hit ctrl+f5.
Anyone know why this is?
Thanks,
Nick

A: I found this articles.. I hope they will help.
@ OutputCache
OutputCache - more examples
http://authors.aspalliance.com/aspxtreme/aspnet/syntax/outputcache.aspx
ASP.NET Page Output Cache

A: Hitting CTRL-F5 is a clientside action, so I would say that you've got the page you're looking at cached in your webbrowser. Try setting <%@ OutputCache Location="Server" ... %> to deny clientside caching.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the probability of the number 1 and number 2 employees getting the bonus at a call center? Two weeks ago, a friend working at a call center told me about their staff bonus policy. Here I paraphrase it.

Suppose employee A answers the maximum number ($N_1$) of calls among the staff, and employee B (Notice that there may be more than one such employee B if there are ties.) answers the second maximum number ($N_2$) of calls, if $N_1-N_2\le10$, then both employee A and employee B could get the same extra bonus, otherwise, only employee A could get the bonus.

It is really an interesting policy. I did try to formulize the probability that number 1 and number 2 employees (There may be more than two employees that can receive the bonus if there are ties for the second place.) that get the bonus.

Assume that there are $m$ employers working at the call center, and the calls arrive with a homogeneous Poisson process with rate $\lambda$ at every desk (every employee) of the call center. To simplify the problem, I also assume that every incoming call can be handled immediately within a negligible short period of time. Let $N_i(t)$ denote the $i$-th maximum number of calls that have been answered, where $1\le i\le m$. That is, $N_1(t)\ge N_2(t)\ge ...\ge N_{m-1}(t)\ge N_m(t)$.  If the number 1 and number 2 of the employees can get the bonus, then $0\le N_1(t)-N_2(t)\le10$.

Trying to calculate the probability $\Pr[0\le N_1(t)-N_2(t)\le10]$, I started out like this:

Assume $N_1(t)=k$, then $N_j(t)\le k$, where $k\ge11$ and $2\le j\le m$ and there exists at least a specific $N_r (t)$, and $k-10\le N_r(t)\le k$ and $2\le r\le m$. Then I think the probability could be expressed by
  $$ \Pr[\text{Numer 1 and number 2 employees get the bonus}] = \Pr[0\le N_1(t)-N_2(t)\le10] \\ =\sum\limits_{k=11}^\infty\Pr[N_1(t)=k] (\Pr[N_r(t)\le k]^{m-1}-\Pr[N_r(t) \le k-11]^{m-1})$$

But I'm not sure I am doing this right. And even if the formulization is correct, I still could not calculate the probability. It seems that the probability has no simple expression. I tried to estimate the bound of such probability, but all I've got are very complex power series.(See question Estimate the scale of…).

Then, here are my questions:
  1) Am I right in formulating the probability? If not, then how to formulize it?
  2) What is the distribution of $N_1(t)-N_2(t)$? How to calculate the probability or estimate the scale of it?

Sorry for my poor English. And anyone that provides any clue would be highly appreciated. Thank you in advance!

A: Here's how I would pursue something like this. Define $X$ to be the amount paid out and $B$ to be the amount that is paid out to a single person. Assume there are $n$ people at this call center. Suppose each $Y_{i}$ is the number of calls each person at this call center gets, where each $Y_i$ follows a Poisson distribution with mean $\lambda$. Also, assume that the number of calls among each person in this call center are mutually indepedent.
Let $Y_{(1)} = \text{min}(Y_1, Y_2, \cdots, Y_n)$, $Y_{(2)} = \text{min}(Y_1, Y_2, \cdots Y_n) \setminus Y_{(1)}$, $\cdots$, $Y_{(n)} = \text{max}(Y_1, Y_2, \cdots, Y_n)$. (My notation is different from yours here - this is just what I'm used to.)
The total paid out is a discrete random variable, which takes on the value $X = \begin{cases}2B & \text{ for } Y_{(n)}-Y_{(n-1)} \leq 10 \\ B & \text{ otherwise} \end{cases}$.
For convenience, I will assume that the total paid out to a single person, $B$, is constant.
Then, $P(X = 2B) = P(Y_{(n)}-Y_{(n-1)} \leq 10)$. I don't have a background on discrete order statistics or joint distributions of order statistics, but you can find something here (see p. 14).


text:
Q: Swift UILongPressGesture on Button or Switch I'm trying to find out if what I press with UILongPressGesture is a button or switch in the function delete
 func delete() {
    let subviews = self.view.subviews as [UIView]
    for v in subviews {
        if let button = v as? UIButton {
           println("button")
        }
        else if let loadSwitch = v as? UISwitch {
           println("switch")
        }
   }

I have as a print button and switch
I had no problems when I was only the buttons but now that I have integrated the switch ...
PS the longpress on the switch I get it only if I press just below the switch itself

A: You can check which type your UIViews are by using isKindOfClass
for v in subviews {
    if(v.isKindOfClass(UIButton)){
        //Do button stuff
    }else if(v.isKindOfClass(UISwitch)){
        //Do switch stuff
    }
}

But now there's still the problem with the switch. The problem is, that the UILonGestureRecognizer won't get called, because other UISwitch-actions fire up before. But you can stop that by using the UIGestureRecognizerDelegate-method shouldReceiveTouch:
class test:UIViewController, UIGestureRecognizerDelegate{

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        //If it's your switch, the normal gesture won't be called.
        if(touch.view == yourSwitch){
            return false
        }else{
            return true
        }
    }

}


text:
Q: R write list to CSV line by line I have the following code in R:
library(party)
dat = read.csv("data.csv", header = TRUE)

train <- dat[1:1000, ]
test <- dat[1000:1200, ]

output.tree <- cforest(t_class ~ var1 + var2,
                       data = train)

train_predict <- predict(output.tree, newdata = test, OOB=TRUE, type = "prob")

for (name in names(train_predict))
{
  p <- (train_predict[[name]][1:3])
  write.table(p, file = "result.csv",col.names = FALSE, append=TRUE)
}

I am trying to write the result of the random forest prediction to a csv file.
The result train_predict looks like the following:

When I run the above code its only write the first column of each row to the csv and not all three.
How can I write all three columns of the list to the file?
Also is there a way in R to clear the csv before you write to it in case there is something in it already?

A: Rather than write serially, you can convert to a data.frame and just write all at once:
Generate fake data that looks similar to what you posted:
fakeVec <- function(dummy) t(setNames(rnorm(3), letters[1:3]))
my_list <- lapply(0:4, fakeVec)
names(my_list) <- 6000:6004

Here's the fake data:
$`6000`
              a          b         c
[1,] -0.2444195 -0.2189598 -1.442364

$`6001`
             a        b          c
[1,] 0.2742636 1.068294 -0.8335477

$`6002`
            a        b         c
[1,] -1.13298 1.927268 -2.123603

$`6003`
             a        b            c
[1,] 0.8260184 1.003259 -0.003590849

$`6004`
              a         b         c
[1,] -0.2025963 0.1192242 -1.121807

Then convert format:
# crush to flat matrix
my_mat <- do.call(rbind, my_list)
# add in list names as new column
my_df <- data.frame(id = names(my_list), my_mat)

Now you have a data.frame like this:
    id          a          b            c
1 6000 -0.2444195 -0.2189598 -1.442364429
2 6001  0.2742636  1.0682937 -0.833547659
3 6002 -1.1329796  1.9272681 -2.123603334
4 6003  0.8260184  1.0032591 -0.003590849
5 6004 -0.2025963  0.1192242 -1.121807439

Which you can just write straight to a file:
write.csv(my_df, 'my_file.csv', row.names=F)

A: How about this?
temp = list(x = data.frame(a = "a", b = "b", c = "c"),
        y = data.frame(d = "d", e = "e", f = "f"),
        z = data.frame(g = "g", h = "h", i = "i"))

for (i in 1:length(temp)) {
  write.table(temp[[i]], "temp.csv",col.names = F, append = T)
}

Regarding clearing the csv. If I understood your question correctly, just erase the append = T?


text:
Q: DAX/PowerBI Rank taking a variable/parameter into account I'm working on a ranking/scoring system and I'm missing the PERCENTRANK.INC function in powerBI. Instead I have worked out below formula which is the closest I can get.
Score =
DIVIDE (
    RANKX (
        FILTER ( 'Table', NOT ( ISBLANK ( [Sold amounts] ) ) ),
        [Sold amounts],
        ,
        ASC
    ) - 1,
    COUNTROWS ( FILTER ( 'Table', NOT ( ISBLANK ( [Sold amounts] ) ) ) ) - 1
)

I really want to have the formula to take the type of "Fruit" into account in my scoring/ranking.
In short each fruit should be scored separately, with a range per fruit sold.
Could this somehow be done with a variable (VAR)?
Example of data:

A: This should work.
Score =
VAR fruit = 'Table'[Fruit]
VAR filteredTable = FILTER ( 'Table', NOT ( ISBLANK ( [Sold amount] ) ) && 'Table'[Fruit] = fruit)

RETURN
DIVIDE (
    RANKX (
        filteredTable,
        [Sold amount],
        ,
        ASC
    ) - 1,
    COUNTROWS ( filteredTable ) - 1
)


text:
Q: How to specify a path for Microsoft Azure Jupyter Notebooks? I am trying to upload a Python script I wrote for Jupyter Notebook to Microsoft Azure Notebooks, but it is not working correctly.
The Microsoft Azure project has a folder with XLSX files that I am trying to read, and the Python script. When I run the Python script on Jupyter Notebook it doesn't access the folder I previously uploaded to the project.
path =r'/Users/chorozco/Documents/Dr.Irwin/6 Column Data Acquisition Converted'
filenames = glob.glob(path + "/*.xlsx")

path = os.getcwd()
files = os.listdir(path)
files

I am expecting the list of the files inside "6 Column Data Acquisition Converted", but instead I get a list of the files inside my Microsoft Azure Project:
Expectation:
Script run from Anaconda in my computer
Reality:
Script run from Microsoft Azure Notebooks

A: Just according to your code path =r'/Users/chorozco/Documents/Dr.Irwin/6 Column Data Acquisition Converted', I think you are working on MacOS, not Linux. However, Microsoft Azure Notebooks is based on Linux for running. So the difference of code os.listdir(path) between Azure Notebook and your local Anaconda is caused by the different implementation of Python for this feature os.listdir on different OS like MacOS other than Linux and Windows, the result without the files recursively listed in the directories.
Here is my steps as reference.

*

*I created a new project named Test for listing xlsx files in a path of Azure Notebook Project in my account of Microsoft Azure Notebooks, and to create a new folder 6 Column Data Acquisition Converted as the figures below.
Fig 1.

Fig 2.

*I created some xlsx files on my local Windows for uploading, then move to the folder I created in Azure Notebook project previously to do the upload operation as the figures below.
Fig 3.

Fig 4.

Fig 5.

Fig 6.

*I created a notebook in Python 3.6 to run the same code with yours.
Fig 7.

Fig 8.

*I found the result is as same as the code on my local Linux and Windows, but other than your result on MacOS.
Fig 9. The almost same code run in Python 3.6 of Azure Notebook

Fig 10. The almost same code run in Python 2.7 of Azure Notebook

Fig 11. The result of os.listdir on Windows

Fig 12. The result of os.listdir on Linux

So I think the issue was caused by MacPython, please check it again. Hope it helps.


text:
Q: Genuino 101 does not run when BLECharacteristic defined For an application I'm developing we're working with the Genuino 101.
Because the BLEUnsignedLongCharacteristic is too small, I decided to go for the BLECharacteristic.
However the sketch doesn't run when I change it over
#ifdef _BLE_
BLECharacteristic data("9ff91ff6-e874-4ff6-8cff-83daaf9d7fc1", BLERead |BLEWrite, RD_BUF_LEN);
#else
BLEUnsignedLongCharacteristic data("9ff91ff6-e874-4ff6-8cff-83daaf9d7fc1", BLERead | BLEWrite);
#endif // _BLE_

I try to run both next to eachother, and the sketch runs when I define data as the unsignedLongCharacteristic.
ifdef _BLE_
    unsigned char rdBuf[RD_BUF_LEN] = { 0 };
    i2cRead(device.value(), memory.value(), sizeof(rdBuf), rdBuf);
    data.setValue(rdBuf, RD_BUF_LEN);
#else
    unsigned char rdBuf[4] = { 0 };
    i2cRead(device.value(), memory.value(), sizeof(rdBuf), rdBuf);
    unsigned long output = ((rdBuf[0] << 24) + (rdBuf[1] << 16) + (rdBuf[2] << 8) + (rdBuf[3]));
    data.setValue(output);
#endif // _BLE_

Again, the sketch runs fine when I don't define BLE, and it uses the Unsigned long.
Anyone have an idea?

A: turns out that i assigned 0x00 to Data a few lines below what i showed.
now this is fine when you define it as a long, but when the microcontroller expects an array and finds a single value, it crashes


text:
Q: Using root logger across multiple modules ActiveState Perl 5.12 on WinXP
I've recently become a convert to Log4perl and used it successfully where I defined a specific logger for each module that makes up my application. Example:
Upload.pm-----
my $logger = get_logger("Upload");  # specific logger
my $layout = Log::Log4perl::Layout::PatternLayout->new( "%d %p> %F{1}:%L %M - %m%n");
my $appender = Log::Log4perl::Appender->new( "Log::Dispatch::File",
                                     filename => "Upload.log",
                                     mode     => "append"
                    );
$appender->layout($layout);
$logger->level($OFF);    #  or $INFO
$logger->add_appender($appender)
....

This works but is hard to track program flow across numerous log files ie Upload.log , Parse.log , FileRead.log  etc.  Quick-n-dirty solution: use same filename in all loggers.
This works much better, but only as long as the program is used serially and in sequence.
Now for the wrinkle - suppose module Upload.pm is used by several progams ie  readMyFiles.pl, readHerFiles.pl and dumpAllFiles.pl . When running readMyFiles.pl I want the logger in Upload.pm to write to readMyFiles.pl.log  and when runnng dumpAllFiles.pl want the logger in Upload.pm to write to dumpAllFiles.pl.log
One method might be to declare an our  variable $logFileName in my .pl files and use it in all my modules like so:
                                      filename => $logFileName,

Another might be to remove all the loggers from my .pm's and define them only in the .pl's - but then how would I reference $logger in the .pm's ?
All thoughts and suggestions are appreciated.
Still-learning Steve

A: Configure your logging settings in the caller, not in the module. If somebody else uses your module, they might not want to log things to the same place that you do. They might also want to format log messages differently, or use a different type of appender, or...the list goes on.
Your module should only get a logger and write messages to it:
MyModule.pm
#!/usr/bin/perl

package MyModule;

use strict;

use Log::Log4perl qw(get_logger);

sub foo {
    my $logger = get_logger("Foo");
    $logger->debug("Hello from MyModule");
}

1;

Your main program(s) should configure and initialize logging:
logtest
#!/usr/bin/perl

use strict;
use warnings;

use Log::Log4perl qw(get_logger);
use MyModule;

Log::Log4perl->init("log4perl.cfg");

my $logger = get_logger("Foo");
$logger->debug("Hello from main");

MyModule::foo();

I prefer to use a separate config file for Log4perl settings:
log4perl.cfg
log4perl.logger.Foo=DEBUG, Screen

log4perl.appender.Screen=Log::Dispatch::Screen
log4perl.appender.Screen.Threshold=DEBUG
log4perl.appender.Screen.layout=Log::Log4perl::Layout::PatternLayout
log4perl.appender.Screen.layout.ConversionPattern=[%r] %F %L %c - %m%n

Output:
[0] logtest 12 Foo - Hello from main
[0] MyModule.pm 11 Foo - Hello from MyModule

Note that you must initialize logging with Log::Log4perl->init in the caller before trying to get_logger in the module. If you don't, log messages from the module will be ignored and you'll get the following warning:
Log4perl: Seems like no initialization happened.
Forgot to call init()?

See the documentation for details.


text:
Q: Discord.js: Cannot read property 'set' of undefined I'm creating bot with discord.js.
This is my code:
var Discord = require('discord.js');
const swarmConfig = require('./swarmConfig.json');

var swarmbot = new Discord.Client();
swarmbot.login('myToken');

fs.readdir('./commands/', (err, files) =>{
  if(err) console.log(err);
  var jsFiles = files.filter(f => f.split('.').pop() === 'js');

  if(jsFiles.length <=0){
    console.log('Cant find commands');
    return;
  }

  jsFiles.forEach((f, i) =>{
    let fileGet = require(`./commands/${f}`);
    console.log(`${f} loaded!`);
    swarmbot.commands.set(fileGet.help.name, fileGet);
  });
});

swarmbot.on("message", async message =>{
  if (message.author.swarmbot)
    return;
  var prefix = swarmConfig.prefix;
  var command = messageArray[0];
  var arguments = messageArray.slice(1);

  var commands = swarmbot.commands.get(command.slice(prefix.length));
  if(commands)
    commands.run(swarmbot, message, arguments);
});

But if I try to start it, I get this error:
C:\Users\purul\Desktop\swarm-dsbot\swarm.js:25
swarmbot.commands.set(fileGet.help.name, fileGet);
                  ^
TypeError: Cannot read property 'set' of undefined
at jsFiles.forEach (C:\Users\purul\Desktop\swarm-dsbot\swarm.js:25:23)
at Array.forEach (<anonymous>)
at fs.readdir (C:\Users\purul\Desktop\swarm-dsbot\swarm.js:22:11)
at FSReqWrap.oncomplete (fs.js:141:20)

I'm still learning JavaScript, Thanks to everyone who will help with this.

A: If we look in the documentation for Discord.js, there is no such object called 'commands'.
Link: https://discord.js.org/#/docs/main/stable/search?q=commands
I'm guessing that you're loading them from a file, so you should maybe create a js file that has the commands, and load them to you main file.
Reference for possible solution: https://stackoverflow.com/a/51333277/7363404 (you should also check the question)


text:
Q: Application Variant do Last for App Bundle I have entered below code in my Gradle.
///start
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            println("Roop: mappingFile:  ${output.outputFile}")
        }
            variant.assemble.doLast {
//            doLast {
                File dir = new File("${project.projectDir}/out1")
                dir.mkdirs()
                println("Roop: copy")
                variant.outputs.each { output ->
                    File file = output.outputFile
                    println("Roop: file:" + file)
                }
            }
    }

Now when i perform Build Apk from android studio, Variant.assemble.doLast gets executed after apk is created. But the same doLast is not called if i perform Build Bundle.
Any info why doLast does not get called for BuildBundle ?


text:
Q: Find Sequences of any range Given an array of numbers, print the each and every range available.
For example
Array : 9, 3, 5, 7, 4, 8, 1
Output: 1, 3-5, 7-9
Note: Please execute this problem without using an additional array.
How do i proceed?
*
#include<stdio.h>
int main()
{
int a[]={9,8,8,7,6,5,14};
int n= sizeof(a) / sizeof(a[0]);
int i,j;
int temp;
for(i=0;i<n;i++)
         {
               for(j=i+1;j<n;j++)
               {
                     if(a[i]>a[j])
                     {
                           temp=a[i];
                           a[i]=a[j];
                           a[j]=temp;
                     }
               }
        }
}

*
1st i will sort in ascending order, i don't know what to do next?
P.S : I am coding this in C.

A: The next step is to identify sequences. Try the following loop (not fully debugged):
first= next= a[0];
for (i=1; i<n; i++) {
    if (a[i] > next+1) {
        if (next>first)
             printf("%d-%d,", first, next);
        else printf("%d,", first);
        first= next= a[i];
    }
    else next++;
}

A: I wrote a simple, readable function for you, take a look:
void printRange(int sortedArray[], int len) {
    int i, current, next, printStart, printEnd, startIndex = 0;
    bool print = false;

    for (i = 0; i < len; i++) {
        printStart = sortedArray[startIndex];
        printEnd = sortedArray[i];

        current = sortedArray[i];
        if(i < len -1) {
             next = sortedArray[i + 1];
        } else
              next = current;

        if (next - current != 1) {
            startIndex = i + 1;
            print = true;
        }

        if (print) {
            if (printStart - printEnd == 0) {
                printf("%d,", printStart);
            } else {
                printf("%d-%d,", printStart, printEnd);
            }
            print = false;
        }
    }
}

Run live.
Note, for good understanding variable current is declared whereas current and printEnd is same. You may replace current by printEnd.

A: If you may to change the original array that is if you may to sort it then the program can look like
#include <stdlib.h>
#include <stdio.h>

int cmp( const void *lhs, const void *rhs )
{
    int a = *( const int * )lhs;
    int b = *( const int * )rhs;

    return ( b < a ) - ( a < b );
}

int main()
{
    int a[] = { 9, 8, 8, 7, 6, 5, 14 };
    const size_t N = sizeof( a ) / sizeof( *a );

    qsort( a, N, sizeof( int ), cmp );
/*
    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    printf( "\n" );
*/
    int *p = a;
    int *start = a, *end = a;
    do
    {
        if ( ++p == a + N || *p  != *end + 1 )
        {
            printf( "{ %d", *start );
            start == end ? printf( " }\n" ) : printf( ", %d }\n", *end );
            start = end = p;
        }
        else
        {
            end = p;
        }
    } while ( p != a + N );
}

The program output is
{ 5, 8 }
{ 8, 9 }
{ 14 }

A: There are already some pretty good answers for this task in here but maybe the sorting part in the beginning is worth to talk a little bit more about. Especially if you need something like that in school, university or in a job interview.
The easiest sorting technique/algorithm would be something like BubbleSort which can easily be implemented with 2 for loops.

void BubbleSort (int a[], int length)
{
  int i, j, temp;

   for (i = 0; i < length; i++)
   {
       for (j = 0; j < length - i - 1; j++)
       {
           if (a[j + 1] < a[j])
           {
               temp = a[j];
               a[j] = a[j + 1];
               a[j + 1] = temp;
           }
       }
   }
}

Source and more information

The best way of sorting such arrays with integers (or any kind of number) is QuickSort. The algorithm is pretty advanced but if you watch a good video on Youtube or read this article you definitely know how it works.

void quick(int array[], int start, int end){
   if(start < end){
       int l=start+1, r=end, p = array[start];
       while(l<r){
           if(array[l] <= p)
               l++;
           else if(array[r] >= p)
               r--;
           else
               swap(array[l],array[r]);
       }
       if(array[l] < p){
           swap(array[l],array[start]);
           l--;
       }
       else{
           l--;
           swap(array[l],array[start]);
       }
       quick(array, start, l);
       quick(array, r, end);
   }
}

Source and more information

Note: QuickSort uses a technique called recursion. If you are not familiar which that you can have a look here:

In computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time. Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.
Source and more information


text:
Q: I cannot change from Products only to Static block and products in Display Settings of an existing category Working with Magento ver. 2.2.2
I wish to change the design of category pages. Now certain categories are displaying only products, But I want to display a static block and products. I create the static block and choose that block in Category|Content, then choose "Static block and products" in display mode. Nothing changes - the store still only displays products with Description, not the block. It works, but is not the look I want. I can create a new category and it displays properly, with the block and products. But I cannot save it with the original URL key, which is necessary, even after changing the key of the original category. I get a duplicate key error.

A: Follow these steps:

*

*Head to backend.

*Go to Content tab.

*Under Content section, choose static block from Add CMS Block.

A: As you mentioned, for newly created categories, the static block getting displayed whereas for already existing categories it is not displaying right.
Cache might be the reason for the issue.
You can follow the below steps:-

*

*Delete all folders under pub/static

*Delete var/cache

*Delete var/composer_home

*Delete var/generation

*Delete var/page_cache

*Delete var/view_preprocessed
Now open your command prompt and go to your root installation of magento 2 and run the following commands

php bin/magento setup:static-content:deploy


text:
Q: Looping through $_POST Variable I have a PHP script that generates some form on the page I have. I also have a table and submit button within the form which all works fine and the data is sent to the next page as intended. Now on the next page I have a PHP code that reads the $_POST variable. Here is my code:
echo "<form name=\"myForm\" id=\"myForm\" method=\"post\" action=\"\">";
echo "
";
    echo "
";
        echo "ID	";
        echo "Name	";
        echo "Group	";
    echo "
";

while($row = mysql_fetch_array($qryRes))
{
    echo "
";
    echo "" . $row['id'] . "	";
    echo "<input name=\"aName" . $row['id'] . "\" id=\"aName" . $row['id'] . "\" type=\"text\" value=\"" . $row['aName'] . "\" />	";
    echo "<select name=\"gID" . $row['id'] . "\">";
        while($gRow = mysql_fetch_array($grpsQry))
        {
            if($gRow['id'] == $row['groupID'])
                echo "<option id=\"" . $gRow['id'] . "\" selected=\"selected\">" . $gRow['gName'] . "</option>";
            else
                echo "<option id=\"" . $gRow['id'] . "\">" . $gRow['gName'] . "</option>";
        }
    echo "</select>	";
    echo "
";
    mysql_data_seek( $grpsQry, 0 );
}
echo "
";
echo "<input type=\"submit\" name=\"submitForm\" value=\"Save\" />";
echo "</form>";

Then comes my PHP Code to read the $_POST:
if(isset($_POST['submitForm']))
{
    print_r($_POST);
    foreach($_POST as $x)
        echo $x . "
";
}

Everything works fine, except that I need to read only the text field in the foreach loop as I will generate a query on them and will compare the values I will have with the value returned from the List ..
As yuo can see, the textfield is named aName then the id of the user. I need to read this only. But I will use it to generate a query which will be then compared to the value of the List gID.

A: try this:
foreach($_POST as $key => $value){
    if(substr($key,0,5) == 'aName')
        echo $value . "
";
}


text:
Q: How to create Bean class in Javascript like Java? I may sound weird for this, please forgive me if this is an off topic question, but Since I came from java background and now working on nodejs last 1 week, at many places I personally felt that I should use something like Bean architecture with setters and getters feature (as we do have in java term).
Is there any way through which I can achieve this in nodejs/javascript ?,
suppose I have json data in my hand retrieved from db call, how can I convert it into a class with respective properties ?
(I have intermediate knowledge about javascript and prototype.)
Any help would be appreciated... thanks.

A: JSON that you get is already an object =)
Any way you can create a constructor function and pass this json as parameter. And do whatever you like

A: In addition of topic Getter/Setter  look at
 __defineGetter__
 __defineSetter__

they are default basic object methods, to specify getters and setters in JS (not sure abount NODE)


text:
Q: Maximise entropy of random sample of random distribution
Let $X_1, ..., X_n$ be positive discrete r.v.s such that $p^j_k = \mathbb{P}(X_j=k)$. Let $N \in \{ 1, ..., n\}$ be a discrete r.v. with pmf $a_j=\mathbb{P}(N=j)$. Then $X_N$ is the random variable chosen by sampling a random $p^j$ distribution according to $a_j$.
Calculate $H(N, X_N)$ and, for $p^j_k$ fixed, find its maximum value and the value of $a_1, ..., a_n$ which achieves it.

I believe $$ H(N,X_N)=-\sum_{j=1}^n\sum_{k=1}^\infty a_jp^j_k\log(a_jp^j_k)$$
I would guess that this is maximised by $$a_j=\frac{H(X_j)}{\sum_{j=1}^nH(X_j)}$$ simply because it seems like giving a higher probability to the r.v.s with more entropy would maximise the entropy. How can I prove (or disprove) this, preferably using Lagrange multipliers?

A: Your problem can be stated as:
$$\max_{a\in K} -\sum_{j=1}^n \sum_{k=1}^{\infty} a_j p_{jk}\log(a_j p_{jk})$$
where $K=\{a_1,\ldots,a_n\ge 0\,\mid\,a_1+\ldots+a_n=1\}$. This is a very favorable case of convex programming (objective is concave, constraints are affine) so for example in that case KKT conditions are necessary and sufficient conditions for optimality. So if we consider:
$$\begin{align} f(a)&=-\sum_{j=1}^n \sum_{k=1}^{\infty} a_j p_{jk}\log(a_j p_{jk})\\
g_i(a)&=-a_i\\
h(a)&=a_1+\ldots+a_n-1\end{align}$$
Notice that:
$$\begin{align}\nabla f(a)&=(-1-\log a_j+H(X_j))^T_{1\le j\le n}\\
\nabla g_i(a)&=-e_i\\
\nabla h(a)&=(1,\ldots,1)^T
\end{align}$$
Then at optimal $a^*$:

*

*Stationary condition: $-1-\log a^*_j+H(X_j)-\mu_j-\lambda=0$ for all $j$

*Primal feasability: $a^*_j\ge 0$ for all $j$ and $a^*_1+\ldots +a^*_n=1$

*Dual feasability: $\mu_j\ge 0$ for all $j$

*Complementary slackness: $\mu_j a^*_j=0$ for all $j$
The only way all these conditions are simultaneous satisfied is when $a^*_j=Ce^{H(X_j)}$ (for some constant $C$), so in the end:
$$a^*_j=\frac{e^{H(X_j)}}{\sum_{j=1}^n e^{H(X_j)}}$$
is the optimal solution. You can get to the same result using Lagrange multipliers but you probably need to handle manually what happens at the boundary.


text:
Q: SMTP settings not sending emails to hotmail,msn, microsoft accounts I have added the smtp settings in production. But it does not send any mail to hotmail, msn, microsoft accounts.
config.action_mailer.smtp_settings = {
      :address => "host.abc.com",
      :port => 25,
      :domain => "abcd.com",
      :user_name => 'abc@mymail.com',
      :password => 'XXXXXX',
      :authentication => 'plain'
}

Is there anything I missed, any help would appreciate .
Thanks

A: Have you included the config.action_mailer.default_url_options = { :host => 'localhost:3000' } into your environments/development.rb?


text:
Q: Deleted Assets still show up in the build log? So with the help of the "Editor Log" after building I´m trying to reduce the file size of the app I´m creating. But for some reason the Assets I´m deleting are still included in the build. The Log:
(All in Assets/Textures/Sprites/Sticker/)
...
16.0 mb  3.0% Sticker_1.png
15.9 mb  3.0% Sticker_2.png
15.8 mb  3.0% QR/Sticker_3.png
13.8 mb  2.6% Sticker_4.png
11.8 mb  2.2% Sticker_5.png
11.8 mb  2.2% QR/Sticker_6.png
11.6 mb  2.2% Sticker_7.png
...
The thing is, that I already deleted the whole "QR" folder. But for some reason, it still shows up in the log and the app size didn´t go down. What am I doing wrong?

A: To reduce the file size of the app try looking at:
Remove unused assets
and at
Find Unused Assets In Project
For you second problem ('Assets I´m deleting are still included in the build'):
Try exiting your project and looking at the files from the file explorer, if they are not there they won't be in th e build (probably just still in the unity settings).

A: Try:
"File>Build settings..." (or just Ctrl+Shift+B) window select a drop down "Clean Build" from from "Build" button clean build option image.
it resolved my same issue
Ref: https://docs.unity3d.com/Manual/BuildSettings.html[2]


text: Q: Unable to view the version history of workflow in SharePoint Designer 2013 I am unable to view the previous versions of the workflow in SharePoint Designer 2013. I have tried to reset the IIS but it didn't work and it always says as "Server is busy" and never shows any history. Any pointers are highly appreciated.


text:
Q: Scala, my generic function "findFirst" doesn 't work object FPSEx2_1 {

    def factorial(n: Int) : Int = {
        def go(n: Int, acc: Int) : Int = {
            if (n <= 0) acc
            else go(n-1, n*acc)
        }
        go(n, 1)
    }
    def fib(n: Int) : Int = {
        @annotation.tailrec
        def go(n:Int, prev: Int, cur: Int): Int = {
            if( n == 0) prev
            else go(n-1, cur, prev + cur)
        }
        go(n, 0,1)
    }
    def formatResult(name: String, n: Int, f:Int => Int) = {
        val msg = "The %s of %d is %d."
        msg.format(name, n, f(n))
    }

    def findFirst[A] (as: Array[A], p: A => Boolean): Int = {
        @annotation.tailrec
        def loop(n: Int) : Int =
            if (n <= as.length) -1
            else if (p(as(n))) n
            else loop(n + 1)
        loop(0)
    }

    def isPear(p : String) : Boolean = {
        if (p == "pears") true
        else false
    }

    def main(args: Array[String]) : Unit = {
        println("hello word")
        println(factorial(3))
        println(fib(4))
        println(formatResult("factorial", 4, factorial))

        var fruit = Array("apples", "oranges", "pears")

        println(findFirst(fruit, isPear))  // this line prints -1, why doesn 't it work?
    }
}

println (findFirst (fruit, isPear))

The last and the marked line print -1, why  don 't they work?

A: Because the condition in this line of your method findFirst is wrong:
if (n <= as.length) -1

You probably meant:
if (n >= as.length) -1


text:
Q: How do I calculate $(1+i)^{3-4i}$ in normal form $z = x + iy$ and in the exponential representation $ z =\left | z \right |\exp (i \arg (z))$? How do I calculate $(1+i)^{3-4i}$ in normal form $z = x + iy$ and in the exponential representation $ z =\left | z \right |\exp (i \arg (z))$?
$z=(1+i)=\sqrt(2)e^{arctan(1)}$
$(1+i)^{3-4i}=z^{3-4i}$
But that is $(\sqrt(2)e^{arctan(1)})^{3-4i}$.
How do i simplify this expression?

A: You want to compute the logarithms of $1+i$; note that
$$
1+i=\sqrt{2}e^{i\pi/4}
$$
so the logarithms of $1+i$ are
$$
\frac{1}{2}\log2+\left(\frac{\pi}{4}+2k\pi\right)i
$$
for $k$ any integer.
Therefore the determinations of $(1+i)^{3-4i}$ are
$$
\exp\left((3-4i)\left(\frac{1}{2}\log2+\left(\frac{\pi}{4}+2k\pi\right)i\right)\right)
$$
I leave the final computations to you. The value for $k=0$ is called the principal value.


text:
Q: T-SQL: How to obtain the exact length of a string in characters? I'm generating T-SQL SELECT statements for tables for which I have no data type information up-front. In these statements, I need to perform string manipulation operations that depend on the length of the original value of the tables' columns.
One example (but not the only one) is to insert some text at a specific position in a string, including the option to insert it at the end:
SELECT
  CASE WHEN (LEN ([t0].[Product] = 8)
    THEN [t0].[Product] + 'test'
    ELSE STUFF ([t0].[Product], 8, 0, 'test')
  END
FROM [OrderItem] [t0]

(The CASE WHEN + LEN is required because STUFF doesn't allow me to insert text at the end of a string.)
The problem is that LEN excludes trailing blanks, which will ruin the calculation.
I know I can use DATALENGTH, which does not exclude trailing blanks, but I can't convert the bytes returned by DATALENGTH to the characters required by STUFF because I don't know whether the Product column is of type varchar or nvarchar.
So, how can I generate a SQL statement that depends on the exact length of a string in characters without up-front information about the string data type being used?

A: try this:
SELECT
  CASE WHEN (LEN (REPLACE([t0].[Product],' ', '#') = 8)
    THEN [t0].[Product] + 'test'
    ELSE STUFF ([t0].[Product], 8, 0, 'test')
  END
FROM [OrderItem] [t0]

A: Can't you look up the type information for the columns in the system tables?
If not then to determine whether or not a column is varchar or nvarchar this would do it.
create table #test
(
c varchar(50),
n nvarchar(50)
)

insert into #test values ('1,2,3,4    ',N'1,2,3,4,5      ')

SELECT
       CASE
              WHEN datalength(CAST(c AS nvarchar(MAX))) = datalength(c)
              THEN 'c is nvarchar'
              ELSE 'c is char'
       END,
       CASE
              WHEN datalength(CAST(n AS nvarchar(MAX))) = datalength(n)
              THEN 'n is nvarchar'
              ELSE 'n is char'
       END
FROM   #test

A: Here's what I ended up using:
SELECT
  CASE WHEN ((LEN ([t0].[Product] + '#') - 1) = 8)
    THEN [t0].[Product] + 'test'
    ELSE STUFF ([t0].[Product], 8, 0, 'test')
  END
FROM [OrderItem] [t0]

Measurements indicate that the LEN (... + '#') - 1 trick is about the same speed as LEN (...) alone.
Thanks for all the good answers!

A: Use DATALENGTH and SQL_VARIANT_PROPERTY:
SELECT
  CASE
    WHEN 8
      = DATALENGTH([t0].[Product])
      / CASE SQL_VARIANT_PROPERTY([t0].[Product],'BaseType') WHEN 'nvarchar' THEN 2 ELSE 1 END
    THEN [t0].[Product] + 'test'
    ELSE STUFF ([t0].[Product], 8, 0, 'test')
  END
FROM [OrderItem] [t0]

A: If there are no leading blanks, len(reverse(column_name)) will give you the column length.


text:
Q: Stream iTunes to iPad I have a large library on my iTunes and I want to stream the sound to my iPad over wifi. I tested home sharing but it don't load the library, it blocks to the half (iOS 7) and it's quite long (nothing after 10mn). I also use Remote on my iPad to control my iTunes, but I can't get the sound from it…
On my Android I just use the Retune app to control iTunes (like Remote on iPad) and the georgous AirBubble app to receive stream from iTunes. But on an iPad? Why Apple doesn't permit to use AirPlay to do this? I don't want an Airport Express…
PS: I also tested Airfoil but it's another app to launch on the Mac and I don't need it with my Android.

A: If you have a large library, it will take a while for it to get the contents over Home Sharing, particularly depending on the wireless connection speed. Home Sharing is the expected way to do what you're trying to accomplish, simply let it finish doing the initial library transfer. If it's not giving an error, saying it is unable to connect or activate Home Sharing, then it is working.
The other options would be to sync the music to the iPad (wired or wirelessly), use iTunes Match to get the content directly (it, too will have to load the library data like Home Sharing does), or use a third-party method of sharing content from the computer to the iPad (like Plex).
It's also possible you're encountering network errors of some sort if you are receiving an error message of any kind (or if it succeeds but just takes a crazy long amount of time). It may help to review http://support.apple.com/kb/TS2972 or http://support.apple.com/kb/TS1629, depending on your network setup. Home Sharing requires UDP port 5353 to be open, which normally should not be an issue inside your network unless you have a very unusual setup.


text:
Q: Using generics in Spring Data JPA repositories I have a number of simple object types that need to be persisted to a database.  I am using Spring JPA to manage this persistence.  For each object type I need to build the following:
import org.springframework.data.jpa.repository.JpaRepository;

public interface FacilityRepository extends JpaRepository<Facility, Long> {
}

public interface FacilityService {
    public Facility create(Facility facility);
}

@Service
public class FacilityServiceImpl implements FacilityService {

    @Resource
    private FacilityRepository countryRepository;

    @Transactional
    public Facility create(Facility facility) {
        Facility created = facility;
        return facilityRepository.save(created);
    }
}

It occurred to me that it may be possible to replace the multiple classes for each object type with three generics based classes, thus saving a lot of boilerplate coding.  I am not exactly sure how to go about it and in fact if it is a good idea?

A: This is very possible! I am probably very late to the party. But this will certainly help someone in the future. Here is a complete solution that works like a charm!
Create BaseEntity class for your entities as follows:
@MappedSuperclass
public class AbstractBaseEntity implements Serializable{

    @Id @GeneratedValue
    private Long id;
    @Version
    private int version;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;

    public AbstractBaseEntity() {
        this.createdAt = LocalDateTime.now();
        this.updatedAt = LocalDateTime.now();
    }

    // getters and setters
}

Create a generic JPA Repository interface for your DAO persistence as follows:
NB. Remember to put the @NoRepositoryBean so that JPA will not try to find an implementation for the repository!
@NoRepositoryBean
public interface AbstractBaseRepository<T extends AbstractBaseEntity, ID extends Serializable>
extends JpaRepository<T, ID>{

}

Create a Base Service class that uses the above base JPA repository. This is the one that other service interfaces in your domain will simply extend as follows:
public interface AbstractBaseService<T extends AbstractBaseEntity, ID extends Serializable>{
    public abstract T save(T entity);
    public abstract List<T> findAll(); // you might want a generic Collection if u prefer

    public abstract Optional<T> findById(ID entityId);
    public abstract T update(T entity);
    public abstract T updateById(T entity, ID entityId);
    public abstract void delete(T entity);
    public abstract void deleteById(ID entityId);
    // other methods u might need to be generic

}

Then create an abstract implementation for the base JPA repository & the basic CRUD methods will also be provided their implementations as in the following:
@Service
@Transactional
public abstract class AbstractBaseRepositoryImpl<T extends AbstractBaseEntity, ID extends Serializable>
        implements AbstractBaseService<T, ID>{

    private AbstractBaseRepository<T, ID> abstractBaseRepository;

    @Autowired
    public AbstractBaseRepositoryImpl(AbstractBaseRepository<T, ID> abstractBaseRepository) {
        this.abstractBaseRepository = abstractBaseRepository;
    }

    @Override
    public T save(T entity) {
        return (T) abstractBaseRepository.save(entity);
    }

    @Override
    public List<T> findAll() {
        return abstractBaseRepository.findAll();
    }

    @Override
    public Optional<T> findById(ID entityId) {
        return abstractBaseRepository.findById(entityId);
    }

    @Override
    public T update(T entity) {
        return (T) abstractBaseRepository.save(entity);
    }

    @Override
    public T updateById(T entity, ID entityId) {
        Optional<T> optional = abstractBaseRepository.findById(entityId);
        if(optional.isPresent()){
            return (T) abstractBaseRepository.save(entity);
        }else{
            return null;
        }
    }

    @Override
    public void delete(T entity) {
        abstractBaseRepository.delete(entity);
    }

    @Override
    public void deleteById(ID entityId) {
        abstractBaseRepository.deleteById(entityId);
    }

}

How to use the above abstract entity, service, repository, and implementation:
Example here will be a MyDomain entity. Create a domain entity that extends the AbstractBaseEntity as follows:
NB. ID, createdAt, updatedAt, version, etc will be automatically be included in the MyDomain entity from the AbstractBaseEntity
@Entity
public class MyDomain extends AbstractBaseEntity{

    private String attribute1;
    private String attribute2;
    // getters and setters
}

Then create a repository for the MyDomain entity that extends the AbstractBaseRepository as follows:
@Repository
public interface MyDomainRepository extends AbstractBaseRepository<MyDomain, Long>{

}

Also, Create a service interface for the MyDomain entity as follows:
public interface MyDomainService extends AbstractBaseService<MyDomain, Long>{

}

Then provide an implementation for the MyDomain entity that extends the AbstractBaseRepositoryImpl implementation as follows:
@Service
@Transactional
public class MyDomainServiceImpl extends AbstractBaseRepositoryImpl<MyDomain, Long>
        implements MyDomainService{
    private MyDomainRepository myDomainRepository;

    public MyDomainServiceImpl(MyDomainRepository myDomainRepository) {
        super(myDomainRepository);
    }
    // other specialized methods from the MyDomainService interface

}
Now use your `MyDomainService` service in your controller as follows:

@RestController // or @Controller
@CrossOrigin
@RequestMapping(value = "/")
public class MyDomainController {

    private final MyDomainService myDomainService;

    @Autowired
    public MyDomainController(MyDomainService myDomainService) {
        this.myDomainService = myDomainService;
    }

    @GetMapping
    public List<MyDomain> getMyDomains(){
        return myDomainService.findAll();
    }
    // other controller methods

}

NB. Make sure that the AbstractBaseRepository is annotated with @NoRepositoryBean so that JPA does not try to find an implementation for the bean.
Also the AbstractBaseServiceImpl must be marked abstract, otherwise JPA will try to autowire all the children daos of the AbstractBaseRepository in the constructor of the class leading to a NoUniqueBeanDefinitionException since more than 1 daos (repository) will be injected when the bean is created!
Now your service, repository, and implementations are more reusable. We all hate boilerplate!
Hope this helps someone.

A: First of all, I know we're raising the bar here quite a bit but this is already tremendously less code than you had to write without the help of Spring Data JPA.
Second, I think you don't need the service class in the first place, if all you do is forward a call to the repository. We recommend using services in front of the repositories if you have business logic that needs orchestration of different repositories within a transaction or has other business logic to encapsulate.
Generally speaking, you can of course do something like this:
interface ProductRepository<T extends Product> extends CrudRepository<T, Long> {

    @Query("select p from #{#entityName} p where ?1 member of p.categories")
    Iterable<T> findByCategory(String category);

    Iterable<T> findByName(String name);
}

This will allow you to use the repository on the client side like this:
class MyClient {

  @Autowired
  public MyClient(ProductRepository<Car> carRepository,
                  ProductRepository<Wine> wineRepository) { … }
}

and it will work as expected. However there are a few things to notice:
This only works if the domain classes use single table inheritance. The only information about the domain class we can get at bootstrap time is that it will be Product objects. So for methods like findAll() and even findByName(…) the relevant queries will start with select p from Product p where…. This is due to the fact that the reflection lookup will never ever be able to produce Wine or Car unless you create a dedicated repository interface for it to capture the concrete type information.
Generally speaking, we recommend creating repository interfaces per aggregate root. This means you don't have a repo for every domain class per se. Even more important, a 1:1 abstraction of a service over a repository is completely missing the point as well. If you build services, you don't build one for every repository (a monkey could do that, and we're no monkeys, are we? ;). A service is exposing a higher level API, is much more use-case drive and usually orchestrates calls to multiple repositories.
Also, if you build services on top of repositories, you usually want to enforce the clients to use the service instead of the repository (a classical example here is that a service for user management also triggers password generation and encryption, so that by no means it would be a good idea to let developers use the repository directly as they'd effectively work around the encryption). So you usually want to be selective about who can persist which domain objects to not create dependencies all over the place.
Summary
Yes, you can build generic repositories and use them with multiple domain types but there are quite strict technical limitations. Still, from an architectural point of view, the scenario you describe above shouldn't even pop up as this means you're facing a design smell anyway.

A: I am working a project to create the generic repository for cassandra with spring data.
Firstly create a repository interface with code.
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("import org.springframework.boot.autoconfigure.security.SecurityProperties.User;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.AllowFiltering;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.Query;\n");
sourceCode.append("import org.springframework.data.repository.CrudRepository;\n");
sourceCode.append("\n");
sourceCode.append("public interface TestRepository extends CrudRepository<Entity, Long> {\n");
sourceCode.append("}");

Compile the code and get the class, I use org.mdkt.compiler.InMemoryJavaCompiler
ClassLoader classLoader = org.springframework.util.ClassUtils.getDefaultClassLoader();
compiler = InMemoryJavaCompiler.newInstance();
compiler.useParentClassLoader(classLoader);
Class<?> testRepository = compiler.compile("TestRepository", sourceCode.toString());

And initialize the repository in spring data runtime. This is a little tricky as I debug the SpringData code to find how it initialize a repository interface in spring.
CassandraSessionFactoryBean bean = context.getBean(CassandraSessionFactoryBean.class);
RepositoryFragments repositoryFragmentsToUse = (RepositoryFragments) Optional.empty().orElseGet(RepositoryFragments::empty);
CassandraRepositoryFactory factory = new CassandraRepositoryFactory(
    new CassandraAdminTemplate(bean.getObject(), bean.getConverter()));
factory.setBeanClassLoader(compiler.getClassloader());
Object repository = factory.getRepository(testRepository, repositoryFragmentsToUse);

Now you can try the save method of the repository and you can try other methods such as findById.
Method method = repository.getClass().getMethod("save", paramTypes);
T obj = (T) method.invoke(repository, params.toArray());

A full sample code and implementation I have put in this repo
https://github.com/maye-msft/generic-repository-springdata.
You can extend it to JPA with the similar logic.

A: I found an one more way to do this using one less class, inspired by @Jose Mhlanga's answer
Create a BaseEntity
@Getter
@Setter
@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
}

Create a BaseRepository
@NoRepositoryBean
public interface BaseRepository<T extends BaseEntity> extends JpaRepository<T, Long> { }

Finally create a BaseService to complete the setup
public interface BaseService<T extends BaseEntity> {

    BaseRepository<T> getRepository();

    default T create(T t) {
        return getRepository().save(t);
    }

    default Optional<T> update(T t) {
        if (getRepository().existsById(t.getId())) {
            return Optional.of(getRepository().save(t));
        }
        return Optional.empty();
    }

    default Optional<T> get(Long id) {
        return getRepository().findById(id);
    }

    default List<T> getAll() {
        return getRepository().findAll();
    }

    default void delete(Long id) {
        getRepository().deleteById(id);
    }

}

Now we can start creating our entities. Let's say we have an entity called Category. We will create a model, repository, service and controller.
The entity and repository will look something like:
@Getter
@Setter
@Entity
public class Category extends BaseEntity { String name; }

public interface CategoryRepository extends BaseRepository<Category> { }

For service, we need to override only one method: getRepository()
@ApplicationScoped
public class CategoryService implements BaseService<Category> {

    @Inject
    CategoryRepository categoryRepository;

    @Override
    public BaseRepository<Category> getRepository() {
        return categoryRepository;
    }

}

Finally, we create the controller. I haven't quite reached where I could create an abstraction for controller as well. Will edit this if I do.
@Path("categories")
@ApplicationScoped
public class CategoryController {

    // You can (and should!) use BaseService here.
    // Omitting that part as that would need qualifier.
    @Inject
    CategoryService categoryService;

    @POST
    public Response create(Category category) {
        return Response.status(Status.CREATED).entity(categoryService.create(category)).build();
    }

    @PUT
    @Path("{id}")
    public Response update(Category category, @PathParam("id") Long id) {
        if (Objects.isNull(category.getId()))
            category.setId(id);
        return categoryService.update(category).map(i -> Response.status(Status.ACCEPTED).entity(i).build())
                .orElseGet(() -> Response.status(Status.NOT_FOUND).build());
    }

    @DELETE
    @Path("{id}")
    public Response delete(@PathParam("id") Long id) {
        categoryService.delete(id);
        return Response.status(Status.ACCEPTED).build();
    }

    @GET
    @Path("{id}")
    public Response get(@PathParam("id") Long id) {
        return categoryService.get(id).map(i -> Response.status(Status.OK).entity(i).build())
                .orElseGet(() -> Response.status(Status.NO_CONTENT).build());
    }

    @GET
    public Response get() {
        return Response.status(Status.OK).entity(categoryService.getAll()).build();
    }
}

Hope this helps. Cheers!


text:
Q: Segmentation Fault when copying content from argv[] to a char* I have seen some questions about this kinds of issues but none of them helped so far.
The code works fine on the console but the debugger tells that there happens a segmentation fault when I allocate memory for the pointer *word, on main, right after the while that contains a switch statement. It says that argv[optind] points to NULL, I assume its because during debug it has no values attributed to it.
So, if I feel like I know what happens, why am I asking this question, you may ask. Its because one of my classes uses an online code tester and my code is segfaulting there, so, I, not being very well versed in this, am not sure if its my fault.
The code runs as I posted it, you can compile and run, it searches for a word in a file of text; Example: ./my_grep "word" "file"
Thank you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>

#define LINE 1000

static char* word=NULL;
int hasMultiWords=0, iflag=0, vflag=0, lflag=0, cflag=0;

void lowCase(char* s){
    //Nesta funcao recebe um apontador para o inicio de uma string, assim funciona com arrays in *char;
    for(int j=0; j<strlen(s); j++){
        *(s+j) = tolower(*(s+j));
    }

}

void readFile(FILE* in, FILE* out, int argc, char *file_name){

    char line[LINE];
    memset(line, 0, sizeof(char)*1000);
    int n_linhas=0;

    while( fgets(line, LINE, in) ){
        n_linhas++;
        if( cflag==1 && strstr(line, word) !=NULL ){
            printf("%d\n", n_linhas);
            continue;
        }
        if(iflag == 1){
            lowCase(word);
            char *ptr;
            ptr = &line[0];
            lowCase(ptr);
        }
        if( strstr(line, word) != NULL && vflag == 0){
            if(lflag == 1){
                fprintf(stdout, "%s", file_name);
                break;
            }
            fprintf(stdout, "%s", line);
        }
        if( strstr(line, word) != NULL && vflag == 1 ){
            if(lflag == 1){
                fprintf(stdout, "%s", file_name);
                break;
            }
            fprintf(stdout, "%s", line);
        }
    }

}

int main(int argc, char* argv[]){

    FILE* read;
    char* file_name;
    int opt, weirdArgs=0;

    while( (opt=getopt(argc, argv, "ivlc")) != -1){
        switch(opt){
            case 'i':
                iflag=1;
                break;
            case'v':
                vflag=1;
                break;
            case 'l':
                lflag=1;
                break;
            case 'c':
                cflag=1;
                break;
            default:
                break;
        }
    }

    if(optind > 0){
        word = malloc(sizeof(char)*strlen(argv[optind]));
        word = argv[optind];
    }

    optind++;

    for(; optind<argc; optind++){

        weirdArgs++;

        file_name = realloc(file_name, sizeof(char)*strlen(argv[optind]));
        file_name = argv[optind];

        if( strcmp(file_name, "-") == 0){
            readFile(stdin, stdout, argc, "stdin");
        }else{
            if( access(file_name, F_OK) != 0 ){
                fprintf(stderr, "%s : No such file.\n", file_name);
                continue;
            }
            read = fopen(file_name, "r");
            readFile(read, stdout, argc, file_name);
            fclose(read);
        }
        free(file_name);
    }

    if(weirdArgs == 0) readFile(stdin, stdout, argc, "stdin");

    return 0;
}

EDIT: So, its fixed, I added a if statement that checks if there are arguments and make the program print in stderr if there is not, thus it won't find out about the not assigned optind. Thank you!
if(argc == 1){
        fprintf(stderr, "No arguments found.\n");
        exit(2);
    }

A: I fixed the problem with what I said on that last EDIT:.
Since I don't even want the program to run if there are no arguments, I stop it before it reaches a point where errors can occur. So, if argc is equal to '1', meaning the only argument is the program path itself, it will exit() it, thus preventing the segmentation fault.
I should've think about this before posting, thank you for the feedback, I did use it to make it cleaner at least.


text:
Q: Output extent environment is not respected by Select Layer By Attribute (ArcGIS 10.2) I cannot get the arcpy.env.extent working for Select Layer By Attribute GP tool. I can verify that I get various values for coordinates when I have panned to various areas on the map. Copy Features GP tool does export only those feature that are located within the current visible map extent. According to the Select Layer By Attribute GP tool documentation:

If an Extent environment is specified, or if a definition query is
  present on the Input Layer or Table View, only the features or rows
  within the extent or matching the definition query may be selected.

Has anyone succeeded selecting features that are within the extent only? When I run the code below, regardless of the map extent, all features that fulfill the query requirements are selected.
This is the code I execute in the Python window in ArcMap.
fc = "Water distribution network fittings" #layer name in the TOC
field = "ObjectId"
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
print df.extent.XMin, df.extent.YMin, df.extent.XMax,df.extent.YMax

arcpy.env.extent = df.extent #also tried arcpy.Extent(XMin, YMin, XMax, YMax)
arcpy.CopyFeatures_management(fc, "in_memory\outputFeatures") #adds new layer correctly
arcpy.SelectLayerByAttribute_management(in_layer_or_view=fc,selection_type="NEW_SELECTION",where_clause = """ObjectId > 160""")


text:
Q: Refactoring an ASP.NET 2.0 app to be more "modern" This is a hypothetical scenario.  Let's say you've just been hired at a company with a small development team.  The company uses an internal CRM/ERP type system written in .NET 2.0 to manage all of it's day to day things (let's simplify and say customer accounts and records).  The app was written a couple of years ago when .NET 2.0 was just out and uses the following architectural designs:

*

*Webforms

*Data layer is a thin wrapper around SqlCommand that calls stored procedures

*Rudimentary DTO-style business objects that are populated via the sprocs

*A "business logic" layer that acts as a gateway between the webform and database (i.e. code behind calls that layer)

Let's say that as there are more changes and requirements added to the application, you start to feel that the old architecture is showing its age, and changes are increasingly more difficult to make.  How would you go about introducing refactoring steps to A) Modernize the app (i.e. proper separation of concerns) and B) Make sure that the app can readily adapt to change in the organization?
IMO the changes would involve:

*

*Introduce an ORM like Linq to Sql and get rid of the sprocs for CRUD

*Assuming that you can't just throw out Webforms, introduce the M-V-P pattern to the forms

*Make sure the gateway classes conform to SRP and the other SOLID principles.

*Change the logic that is re-used to be web service methods instead of having to reuse code

What are your thoughts?  Again this is a totally hypothetical scenario that many of us have faced in the past, or may end up facing.

A: You missed the first step that I would go through:
Cost-Benefit Analysis
Refactoring an app because you think it feels old is not a good reason. It's still running (I'm guessing fairly reliably by this point) and your company already has a lot of time and money invested in the code.
You probably also have a team of developers that are familiar with .NET 2.0 and WebForms whereas many may not understand the concepts/code you're trying to introduce.
Before changing anything, figure out how much money is invested, how much money you're going to spend on your changes, and how much money it'll save in the future...
If the numbers don't add up, no business is going to let you proceed.

A: *

*Make sure you have a complete suite of tests to cover the existing code before you go tearing it up.

*Write new features using your new techniques.

*Update old code to the new techniques if it needs modification because of a feature request.

*Refactor old code that doesn't need changes only if you are bored and have no new features to write.

A: While it can be tempting, I personally would not make these major changes to the architecture of the application unless they are satisfying specific user requirements.  Simply implementing these to make the application better in terms of maintainability sounds like a big risk.  You may get 60% of the way through and find major challenges with getting one of these changes to integrate with the rest of the legacy application.  It sounds like you'd almost be facing a complete rewrite of the application to ensure everything is consistent with the new architecture.  You may invest a lot of time into the rewrite, and find that the maintainability has only improved a little such that recapturing the time invested in the rewrite will take a long time.
If it were really poorly written or in a legacy language like VB6, I would personally say it would be a candidate for a major rewrite.  However, .NET 2.0 is a very capable language and for alot of applications is not crippled.  From your description it sounds like the application is pretty well designed as is.  It actually has a data access layer, business objects, and is layered in some way.  This sounds like a pretty good application considering you can identify these attributes.  Consider yourself luck that this isn't some app where it's such a mess you can't pick out anything that resembles a particular design pattern.
Maybe there are places where the things are a little nasty, but sometimes it's not pretty where the rubber meets the road and things get wired together.

A: I agree with other posters, dont rewrite unless you can demonstrate the cost saving benefits.
What you could do is write new areas of the system using eg entity framework, MVC and jQuery because the difference will be transparent to browser users. In time you can move the legacy code over bit by bit as you make upgrades/enhancements.
Its also always easier to implement new technologies on new system code, rather than porting existing code.


text:
Q: Update/merge dataframe row only with non NA values in R Let's say I have these data frames:
original = data.frame(id = 1, paramA = 12, paramB=30)
update = data.frame(id=1 , paramA = NA , paramB = 22)

How can I produce this data frame:
result_df = data.frame(id = 1, paramA = 12, paramB=22)

In essence, the update data frame must update the original data frame, but only on the columns that are not NA. That's why paramA remained 12 and only paramB got updated to 22 from 30. The data frames will always have only 1 row. I tried searching for similar questions but I did not find something that fits this.

A: We could update original at non-NA places from update like
original[!is.na(update)] <- update[!is.na(update)]

original
#  id paramA paramB
#1  1     12     22


text:
Q: What's the best way to see logged in users in Windows Server 2012? Right now I use a powershell script to see the currently logged in users. But I don't see if their session is idle, active or inactive. I can see when the session was started, that's it.
Is there an easy way to see how many users are currently logged in to the server I am logged in and see their status? It should not be remotely executed.
I would like to avoid third party tools if possible.

A: Use the query user command
Query User Command
http://technet.microsoft.com/en-us/library/bb490801.aspx

A: Open the Task-Manager and see the users tab. There you will find a list of users and their status.

A: "quser" command will give you the active now users
the same result will give you the "qwinsta" command

A: Get-WMIObject -class Win32_ComputerSystem -ComputerName 192.168.1.9 | Select-Object UserName

where 192.168.1.9 is the IP of the server

A: Use quser or query user to check users connected
quser

query user

Use qwinsta or query session to check sessions connected
qwinsta

query session

A: Also you can use the "UserLock" application to see which users logged in. By this 3rd party tool you can manage the session of the users as well as remote desktop sessions. It is a great tool in this case. I suggest you try this tool.

A: Its easy in Server 2016 when you are in a session:
Click the search glass bottom left on task bar
Type gateway in the box and this should bring up "Remote Desktop Gateway Manager"; select it.
Click on the ">" next to the RDS server you want to view (RDS-01) for most I guess,
then select the monitoring folder
You can now see who is logged on, how long for, since what time and can disconnect them or set connection limits.
Please note you probably need certain admin rights to do this, but it works for me.


text:
Q: How to read this grammar? (The C Programming Language 2e) This grammar is from the reference section of 'The C Programming Language 2e'.
A.7.6 Multiplicative operators

The multiplicative operators *, /, and % group left-to-right.
multiplicative-expression:
   multiplicative-expression * cast-expression
   multiplicative-expression / cast-expression
   multiplicative-expression % cast-expression

I understand that multiplicative-expression consists of three sub expressions. but it looks like a circular grammar for me. Because the grammar does not include terminal expressions like 'primary expression'.
How to read this grammar?

A: The definitive reference should be one of the standards or a draft standard which both the C99 and C11 are publicly available. If we look at the draft C99 standard section 6.5.5 Multiplicative operators the grammar is as follows:
multiplicative-expression:
    cast-expression
    multiplicative-expression * cast-expression
    multiplicative-expression / cast-expression
    multiplicative-expression % cast-expression

A: Something is indeed amiss with the production as presented!
There should be a rule multiplicative-expression: cast-expression somewhere; see The syntax of C in Backus-Naur Form.
However, the same grammar as presented in the post (without the rule above) appears in the PDFs ('88/2e print) I've found online and there is no errata note on the topic - maybe there should be ;-)


text:
Q: The "wrong" definitions of "Algebra" and "Lie Algebra" I am reading Robert Mann's "An Introduction to Particle Physics and the Standard Model" and a review from Amazon (with 12 upvotes) concerns me:

...The definition of algebra on page 54 is wrong. The definition of Lie algebra also on page 54 is wrong. I don't mean typo, I mean wrong...

The definition of Algebra in the book is:

An algebra is a vector space $V = \{v_I\} $ with a binary (combining) operation $\circ$ that obeys this rule:
$v^I \circ v^J = \sum_{k} C^{IJ}_kv^k = C^{IJ}_kv^k $, where $C^{IJ}_k$ is known as structure constant.

Whilst the definition of Lie Algebra is:

A Lie algebra is an algebra whose combining operation is the commutator: $\circ = [,]$ where $[T^a,T^b] = if^{ab}_cT^c$ and it is the Taylor-series expansion of a Lie Group. The group associativity implies the Jacobi identity: $[[T^a,T^b],T^c] + [[T^b,T^c],T^a] + [[T^c,T^a],T^b] = 0$.

As a novice in the subject, I can't tell what is wrong with these definitions. Can anyone clarify what's wrong with them and give the correct definitions?

A: For a physicist these definitions suffice (unless you get into aspects of theoretical physics where you need to be very precise with your definitions). The complaint is probably from someone with a very mathematical inclination (along with the up votes) but the issues tend not to cause problems in everyday use.
There are two places where I can see this as a legitimate argument coming from:

*

*The book never states that the binary operator for the algebra is bilinear, since we are probably going to think of these vector elements as matrices and the binary operator as matrix multiplication this doesn't matter.

*The book never states that the binary (multiplication/bracket) operator for the Lie algebra will always be anticommutative, $[x,y]=-[y,x]$ (note this is anticommutative where $A$ times $B$ is $[A,B]$ rather than $AB$). Since we are going to use the commutator $[x,y]=-[y,x]$ is obvious.

There is a technical third point that the lie algebra binary operator isn't stated to satisfy $[x,x] = 0$. Even if we correct point 2, if the field that the algebra is defined over has field characteristic 2 then we find that $2a = 0 \quad \forall a$. This means that while normally $[x,y] = -[y,x] \Rightarrow [x,x] = 0$, we instead find that $[x,x] = -[x,x]$ but that is true for any element of your lie algebra, not just for zero and so we could have $[x,x] \neq 0$. We tend to work over the real or complex numbers, so the field is of characteristic 0 and this point again isn't an issue.
As you can see you probably wouldn't ever run into these because we would only use a small class of algebras in this book, but if you want to try to use more general mathematics for your physics you need to be careful with your definitions. One example is p-adic quantum mechanics or p-adic QFT where instead of your field being the real numbers/complex numbers, your field is the p-adic numbers, i.e. integers mod p. If you want to consider particle physics and the standard model via this method then you start seeing why you need to be more careful. Similar if you want to use algebras where you can't use/don't want to use a matrix representation (I think von Neumann algebras might be a relevant example of this case).


text:
Q: Copying column data from s3 in a specific order Hi a vendor I use to retrieve data decided to insert a brand new column without maintaining column order to a csv file they drop in my s3 bucket, causing my daily jobs to fail. I used in alter statement to add the new column(channel_name) to the end of my table and updated my copy statement to specify the column mapping but I still get the same error message.
COPY myschema.chat_msg
(direction,text,channel,"user",date,sentiment,tags,filters,source_link,chatdesk_trends_message_id,chatdesk_trends_link,channel_name)
FROM 's3://myfile.csv'
CREDENTIALS 'MY CREDENTIALS
IGNOREHEADER 1
DATEFORMAT 'auto'
TIMEFORMAT 'auto'
MAXERROR 0
CSV
region as 'us-east-1'

The script is failing on the user column and the error reason is invalid data. The column, "channel_name" was inserted after the "channel" column causing the data to shift to the right.

A: I'm a bit confused about the order of columns in your CSV and script. Was channel_name added as a last column on the CSV? Or was it added after the channel column?
If your csv has channel_name after channel, then you'll have to write columns in the same order as your csv for copy to match columns. When using copy to load from flat files, such as in an Amazon S3 bucket, their order must match the order of the source data.


text:
Q: Exclude certain file patterns from rename detection in git? Question
Is it possible to exclude certain file patters from rename detection when doing merges with git?
Background
With our system, Salesforce.com, some metadata files are exactly identical, except for name.  Because of this (I believe) merges can get a bunch of conflicts, e.g. if a meta file was deleted in one branch, and a different meta file with an identical body is deleted in another, it sees things as a rename and conflict with one added on deleted.
I know I can tweak the sensitivity of the rename matching, but if they're identical that doesn't seem like it would be of any benefit.  I've searched the man pages and nothing is jumping out at me.  Has anyone had this issue and has suggestions for how to address?

A: See if that content matching detection would still happen during your merge if, before the merge, you did a:
git update-index --skip-worktree -- yourMetadataFile

(As mentioned in "Preserve git --assume-unchanged files between branch checkouts")


text:
Q: Tensorflow 1.4.1 google.protobuf.text_format.ParseError: 8:1 When i try to train a object_detection network using the tensorflow/models from github https://github.com/tensorflow/models/tree/master/research, I get the following error:
Traceback (most recent call last):
  File "train.py", line 163, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train.py", line 100, in main
    train_input_config_path=FLAGS.input_config_path)
  File "/home/d_sperber/models_fixed/research/object_detection/utils/config_util.py", line 100, in get_configs_from_multiple_files
    text_format.Merge(f.read(), model_config)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/text_format.py", line 533, in Merge
    descriptor_pool=descriptor_pool)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/text_format.py", line 587, in MergeLines
    return parser.MergeLines(lines, message)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/text_format.py", line 620, in MergeLines
    self._ParseOrMerge(lines, message)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/text_format.py", line 635, in _ParseOrMerge
    self._MergeField(tokenizer, message)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/text_format.py", line 703, in _MergeField
    (message_descriptor.full_name, name))
google.protobuf.text_format.ParseError: 8:1 : Message type "object_detection.protos.DetectionModel" has no field named "model".

I used following command from models/research/object_detection to start the training
python train.py --logtostderr --model_config_path=./my_tests/faster_rcnn.config --train_dir=./train

*

*I am using tensorflow 1.4.1 (I cannot upgrade to 1.5 because the admins cannot install the CUDA 9 version for some reasons)

*I tried it with both Python 2.7 and Python 3.5.2

*Ubuntu 16.04

*Same issue for Faster-RCNN and SSD

My .config file looks as follows
# Faster R-CNN with Inception v2, configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  faster_rcnn {
    num_classes: 1
    image_resizer {
      fixed_shape_resizer {
            height: 480
            width: 640
      }
    }
    feature_extractor {
      type: 'faster_rcnn_inception_v2'
      first_stage_features_stride: 16
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 1.0, 2.0]
        aspect_ratios: [0.5, 1.0, 2.0]
        height_stride: 16
        width_stride: 16
      }
    }
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.7
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 14
    maxpool_kernel_size: 2
    maxpool_stride: 2
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: false
        dropout_keep_probability: 0.8
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.0
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 300
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
  }
}

train_config: {
  batch_size: 2
  optimizer {
    momentum_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0002
          schedule {
            step: 0
            learning_rate: .0002
          }
          schedule {
            step: 90000
            learning_rate: .0001
          }
          schedule {
            step: 120000
            learning_rate: .00002
          }
          schedule {
            step: 180000
            learning_rate: .000002
          }
          schedule {
            step: 250000
            learning_rate: .000001
          }
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  gradient_clipping_by_norm: 10.0
  fine_tune_checkpoint: "/home/d_sperber/pretrained_models/inception_v2.ckpt"
  from_detection_checkpoint: false
  num_steps: 800000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/mnt/bigtmp/datasets/rrlab/unreal/Pawlak/unreal_training.tfrecord"
  }
  label_map_path: "/home/d_sperber/TF_Training/unreal_label_map.pbtxt"

}

eval_config: {
  num_examples: 10
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/mnt/bigtmp/datasets/rrlab/unreal/Pawlak/unreal_eval.tfrecord"
  }
  label_map_path: "/home/d_sperber/caltech-pedestrian-dataset-converter/data/caltech_tf/label_map.pbtxt"
  shuffle: true
  num_readers: 1
}

Do you have any ideas?

A: Check whether you set model directory correctly. For example you should introduce the RCNN model path into "pipeline_config_path".
This problem only related to the model introduction.


text:
Q: как вывести сообщение на русском языке? Как вывести сообщение на русском языке? Файл main.cpp в IDE CodeBlock, кодировку пробовал и UTF-8 и WINDOWS 1251. Просмотрет много информации, ничего не получается. Далее, код
#include <windows.h>

int WINAPI WinMain(
 HINSTANCE,
 HINSTANCE,
 LPSTR,
 int) {
 MessageBox(NULL, "Привет Мир!", "Test", MB_OK);
 return 0;
}


text:
Q: что такое pip install и что означают слова "поставить Питон пакет" будьте добры, объясните пожалуйста)

A: pip - это система управления пакетами, которая используется для установки и управления программными пакетами, написанными на Python.
То есть благодаря pip вы можете устранить зависимости (если используете готовые исходники чьего-то проекта и собираетесь собрать его).
Но прежде, чем использовать pip его, конечно же, нужно установить. В интернете полно документации как на русском так и на английском языке.

Поставить питон пакет

Означает, что для сборки данного продукта требуется определенная зависимость и решить её можно с помощью pip


text:
Q: Applescript can't make  into type specifier -1700 error Can anyone explain why the following piece of Applescript code returns an error:
tell application "Photos"
    set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}
    set itemList to every media item in application "Photos" where its id is in idList
    log (count of itemList)
end tell

The error is:
error "Photos got an error: Can't make {\"v3xzjwPQT0y8a844gLHLHWg\", \"v3w3twPQT0y%%844gLgf4Wg\"} into type specifier." number -1700 from {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"} to specifier

A: There is no error in this line of code using OSX 10.9 and iPhoto.  Perhaps something changed in "Photos"/10.10?
In any event, do you still get the error if you move the line of code
set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}

to just before the Tell "Photos" block?  The error is saying "Photos" got the error trying to make the idList.  So try defining the idList without Photos. I would think the list could be defined without telling Photos to do it.

A: I have the same issue. My goal is to get all images that are not in a certain album.
The error rises in the line
set itemList to every media item in application "Photos" where its id is in idList

Also this one-liner results in an error
set itemList to every media item in application "Photos" where its name is in {"bla"}

What works is the following line
set itemList to every media item in application "Photos" where its name is "bla"

But that does not solve the problem. Maybe someone has a suggestion how to do it.

A: That feature does seem to be broken in Photos 4.  You can work around it in a couple of ways.  If your list is simple and fixed you can build up a command using or statements like so:
set itemList to every media item whose id is "wi9HoFU0SKCDianaQBtJBg" or id is "DT29HF1lRgCKOaIZFHoHrQ"

If you need something more flexible, you can use a repeat loop and build up the list through individual searches:
set idList to {"wi9HoFU0SKCDianaQBtJBg", "DT29HF1lRgCKOaIZFHoHrQ"}
tell application "Photos"
    set newList to {}
    repeat with thisID in idList
        set anItem to (first media item whose id is thisID)
        copy anItem to end of newList
    end repeat
end tell


text:
Q: JComboBox getSelectedIndex() method always return 0 I run into an issue with my code, and i can't figure it out.
What i'm trying to do is populate the jComboBox with data from SQLlite and then get index of selected item so i could use it for further activities.
I'm populating jComboBox using array list.
And here is the code for array list:
public ArrayList<Battery> batteries() throws Exception {
    ArrayList<Battery> batteriesList = new ArrayList();
    try {
        Statement stmt = null;
        Connection conn = null;
        Battery currentBattery = null;
        String url = "jdbc:sqlite:batteries.db";
        conn = DriverManager.getConnection(url);
        String sql = "Select * from batteries";
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            currentBattery = new Battery(rs.getString("companyName"), rs.getString("batteryType"), rs.getFloat("batteryVolt"), rs.getFloat("batteryAmp"));
            batteriesList.add(currentBattery);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
    return batteriesList;
}

Here is my code for populating jComboBox:
public void showBatteries() {
    ArrayList<Battery> list = null;
    try {
        list = batteries();
        for (int i = 0; i < list.size(); i++) {
            jComboBox_BatteryChooser.addItem(list.get(i).getCompanyName() + " " + list.get(i).getBatteryModel());
        }
    } catch (Exception ex) {
        Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
    }

}

To get the index of selected item i'm using this:
public void fillData(){
 System.out.println("Index of item: "+jComboBox_BatteryChooser.getSelectedIndex());
}

However all the time the result of function fillData() is always 0.
Could you point me to correct direction or help me solve this issue?
Thank you very much :)


text:
Q: Prove that if $(f_n)$ converges to $f$ almost uniformly then $(f_n)$ converges to $f$ in measure. Let $E$ be a measurable set, $(f_n)$ a sequence of real valued measurable functions on $E$ and $f$ a real valued measurable function on $E$. It is required to prove that if $(f_n)$ converges to $f$ almost uniformly then $(f_n)$ converges to $f$ in measure. The following is my proof.
Let $\epsilon>0$. Suppose $(f_n)$ converges to $f$ almost uniformly. Then there exists $F\subseteq E$ such that $m(F)<\epsilon$ and $f_n$ converges uniformly to $f$ on $E\setminus F$. Thus there exists $N\in\mathbb{N}$ such that for each $n\geq N$ and $x\in E\setminus F,$ $|f_n(x)-f(x)|<\epsilon.$
But\begin{align} \{x\in E:|f_n(x)-f(x)|\geq\epsilon\}=\{x\in F:|f_n(x)-f(x)|\geq\epsilon\}\cup\{x\in E\setminus F:|f_n(x)-f(x)|\geq\epsilon\}.\end{align}
Let $n\geq N$. Then $m(\{x\in F:|f_n(x)-f(x)|\geq\epsilon\})<\epsilon$ and
$m(\{x\in E\setminus F:|f_n(x)-f(x)|\geq\epsilon\})=0$.
Therefore for each $n\geq\mathbb{N}$, $m(\{x\in E:|f_n(x)-f(x)|\geq\epsilon\})<\epsilon$.
Hence $m(\{x\in E:|f_n(x)-f(x)|\geq\epsilon\})=0$ as $n\to\infty$ and the proof is complete.
Is this proof alright? Thanks.

A: Yes, your proof is essentially correct. Here it is with some small improvements.
Let $\epsilon>0$. Suppose $(f_n)$ converges to $f$ almost uniformly. Then there exists $F\subseteq E$ such that $m(F)<\epsilon$ and $f_n$ converges uniformly to $f$ on $E\setminus F$. Thus there exists $N\in\mathbb{N}$ such that for each $n\geq N$ and $x\in E\setminus F,$ $|f_n(x)-f(x)|<\epsilon.$
It means, for $n\geq N$, $$  E\setminus F \subseteq \{x\in E:|f_n(x)-f(x)|<\epsilon\} $$
So, for $n\geq N$, $$ \{x\in E:|f_n(x)-f(x)|\geq\epsilon\} \subseteq F$$ and so we have, for $n\geq N$,
$$ m(\{x\in E:|f_n(x)-f(x)|\geq\epsilon\})\leqslant m(F)<\epsilon$$
Hence $m(\{x\in E:|f_n(x)-f(x)|\geq\epsilon\})=0$ as $n\to\infty$ and the proof is complete.


text:
Q: Insert GetMetaData ChildItems.name directly into a table without using any iterators -Azure Data Factory Is there a method available in azure data factory to directly insert the getmetadata activity childitems directly into a sql table without using any control activities?
Any help would be appreciated.
regards,
Sandeep


text:
Q: Using the mysql commands from one docker container to another I created a network in docker and connected two docker containers to the same network. One container is the application container and the other is the database container. I checked if the ping is happening between the two containers, it was successful. Now, how do I run the MySQL commands from application container?
The container Ip of Mysql is 172.17.0.3
The container Ip of Application is 172.17.0.2

A: If you are using multiple containers, I suggest some tool to organize them, like Docker Compose, Docker Swarm, Kubernetes, etc. This way, you can completely forget about containers IPs, networks and connections are easily created and managed, etc.
For example, your stack on DockerCompose would be like:
version: "3"

services:

  mysql:
    image: mysql:latest
    environment:
      MYSQL_DATABASE: 'db'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'user'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    volumes:
      - my-db:/var/lib/mysql

  app:
    # Use ./ as Docker Build context path
    build: .
    environment:
      MYSQL_DATABASE: 'db'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'user'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'

# Names our volume
volumes:
  my-db:

You can even move database connection parameters to a .env and use its values from the YAML above.
In this example, the container named app can access the MySQL database using the mysql hostname. It will be automatically populated inside the container /etc/hosts.


text:
Q: Why Doesn't Visual Studio's Designer Match What I See At Runtime? I'm new to WPF and using Visual Studio (2015)'s Design view to create a sample application.  At design time, everything looks pretty much like what I want:

But when I run the application, it looks quite different.
I found a similar, but not quite the same question (Run time View of WPF Window doesn't match the Design View of Expression Blend) with layouts created in Blend not matching at runtime.  And this question (Different look in design-mode and at runtime) but that was involving a dynamic resource.
I'm not doing anything clever, just a grid and the controls.  I haven't modified any appearances with templates.  I've used the drag and drop functionality so my grid might be a little sloppy...but I'd really expect it to match.
Am I doing something wrong?  It seems crazy that the designer wouldn't match the runtime...below is my code.
<Window x:Class="Chap01_01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Chap01_01"
        mc:Ignorable="d"
        Title="Customer" Height="160" Width="350" ShowInTaskbar="true" ResizeMode="NoResize" Topmost="True" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="35"/>
            <RowDefinition Height="35"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="100*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="87"/>
            <ColumnDefinition Width="85"/>
            <ColumnDefinition Width="43"/>
            <ColumnDefinition Width="35"/>
            <ColumnDefinition Width="94"/>
        </Grid.ColumnDefinitions>
        <Label Content="_First Name" Grid.Column="0" Grid.Row="0" Margin="5,5,5,5" Target="{Binding ElementName=firstName}" VerticalAlignment="Center" />
        <TextBox x:Name="firstName" Grid.Column="1" Grid.Row="0" Margin="5,5,5,5" VerticalContentAlignment="Center" Grid.ColumnSpan="4"/>

        <Label Content="_Last Name" Grid.Column="0" Grid.Row="1" Margin="5,5,5,5" Target="{Binding ElementName=lastName}" VerticalAlignment="Center" />
        <TextBox x:Name="lastName" Grid.Column="1" Grid.Row="1" Margin="5,5,5,5" VerticalContentAlignment="Center" Grid.ColumnSpan="4"/>

        <RadioButton x:Name="radioButton" Content="EU Citizen" Grid.Column="1" Margin="5,5,5,5" Grid.Row="2" VerticalContentAlignment="Center" Grid.ColumnSpan="2"/>
        <RadioButton x:Name="radioButton2" Content="Non EU Citizen" Grid.Column="3" Margin="5,5,5,5" Grid.Row="2" VerticalContentAlignment="Center" Grid.ColumnSpan="2"/>
        <Button x:Name="okay" Content="Okay" Grid.Column="4" HorizontalAlignment="Right" Margin="0,0,5,5" Grid.Row="3" VerticalAlignment="Bottom"  Width="75"/>
        <Button x:Name="cancel" Content="Cancel" Grid.Column="2" HorizontalAlignment="Right" Margin="0,0,0,5" Grid.Row="3" VerticalAlignment="Bottom"  Width="75" Grid.ColumnSpan="2"/>
    </Grid>
</Window>

A: I couldn't really find anything to say WHY...but I did find a word-around.
Add SizeToContent="WidthAndHeight" in your window attributes...Mine looked delicious in both preview and debug.

A: You need to make sure that these couple pairs match:

*

*Height / Width

*d:DesignHeight / d:DesignWidth

Here is the difference between DesignWidth and Width, and basically both are one for the designer and one for the actual run time application.
All of these should be set in the UserControl. Look at the last line of your UserControl Xaml or Window Xaml and add what is missing + make sure they match. And Good luck!

A: It must be that in the design view a starting reference point for your dimensions is located differently as compared to your release build. I have experienced this with a similar type of thing in C++/C#, My only fix was to test for hours and apply corrections that ultimately make the design appear incorrect whilst fixing the release version.
I hope that helps.