text:
Q: declare an interface thrift How can I declare an interface in Thrift? I mean I have the interface IClient and I use it as parameter in login function in Server:
public interface IServer {
    void login(Pers pers, IClient client) throws ConcursException;
}

I have to use Thrift (Java server, C# client) and I don't know how to declare the interface for using it in login function.
Here is the IClient interface:
public interface IClient
{
    void increasedNrParticipants(Proba proba);
}

Thank you!

A: As the tutorial and the syntax documentation show, and even though the language used with Thrift is called an IDL (interface definition language), one does not declare interfaces in Thrift, instead one declares a service:
service MyCoolService {
    void login(1: Pers pers, 2: Client client) throws (1: ConcursException ce)
}

Any types to be used besides the built-in basic datatypes and containers must be declared as well:
enum creditibility {
  excellent, quite_good, medium_ok, could_be_worse, omg
}

struct Pers {
  1: string surname
  2: string firstname
  3: i32 age
}

struct Client {
  1: i32 client_number
  2: string company_name
  3: Pers  contact
  4: creditibility creditibility
}

Exceptions are declared in the same manner:
exception ConcursException {
  1: bool chapter7
  2: bool chapter11
  3: double outstanding_amount
}

All the subtleties of the syntax above are explained in more detail on the Apache Thrift web site and all the other, additional documentation available on the market today.
By using the Thrift compiler, some code is generated from that IDL, which is then compiled and linked into your program as usual. In our case, we want Java code. Assumed, we saved all declarations from above in a file called myfile.thrift, we enter:
thrift  -gen java  myfile.thrift

Again, it is highly recommended to walk through the tutorial. It takes not that much time, but teaches a  lot of basics about how Thrift works.
Additionally, have a look at the test suite code to learn more about enhanced concepts like alternative endpoint-transports, layered transports and protocols in Thrift.

I have the interface IClient and I use it as parameter in login function in Server

All types used with Thrift must be either built-in basic types, or have to be defined using the IDL. So that approach does not work, because IClient is not an IDL-defined type.

A: There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform and it uses DotNetty (windows is iocp, linux is nio)
[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}

more detail: https://github.com/endink/Thrifty


text:
Q: Styling hyperlink button inside a data template in Silverlight How do I change the visual state of a hyperlinkbutton inside a datatemplate? Basically I'm trying to iterate through the hyperlinkbuttons and set their visual state to active or inactive according to the current url. The hyperlink buttons are located inside the datatemplate of an itemscontrol. The itemsource is bound to a List where link is my custom class for links, that contains just some properties for the uri and caption.
Is there a best practice for styling the active hyperlink in a silverlight nav app? What I am using is the approach of the boilerplate code form the silverlight nav app project template.

A: I think the best way to achieve this would be to bind the HyperlinkButtons' IsEnabled properties to your URL and put a converter in between.
I assume you have something like this:
<ListBox
  ItemsSource="{Binding Path=Links}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <HyperlinkButton
        NavigateUri="{Binding Path=LinkUrl}"
        Content="{Binding Path=LinkUrl}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

So you could add the IsEnabled-binding like so:
<ListBox
  ItemsSource="{Binding Path=Links}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <HyperlinkButton
        IsEnabled="{Binding Path=LinkUrl, Converter={StaticResource LinkUrlToIsEnabledConverter}}"
        NavigateUri="{Binding Path=LinkUrl}"
        Content="{Binding Path=LinkUrl}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

and then in the Converter do e.g.:
public object Convert(...)
{
  var url = (Uri)value;
  if (url.AbsolutePath.EndsWith(".html"))
    return true;
  return false;
}

Cheers, Alex

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add hypens between specific numbers and characters? This is my data set and I want to put hyphens between specific digits and characters.
df_t
                  1 2 3 4 5 6         row_names
X2012SGA007930001 1 2 3 4 5 6 X2012SGA007930001
X2012SGA008360001 1 2 3 3 2 6 X2012SGA008360001
X2012SGA009170001 1 2 3 4 5 6 X2012SGA009170001
X2012SGA009180001 1 3 2 3 4 2 X2012SGA009180001
X2012SGA009200001 3 4 5 4 2 1 X2012SGA009200001
X2012SGA009210001 4 5 6 7 8 9 X2012SGA009210001

library(tidyr)
library(stringr)

y<- c(str_remove(df_t$row_names, pattern = "X"))
y
is.vector(y)
x<- c(substr( y, start = 1,stop=5))
x
is.vector(x)
z<- c(substr(y, start=6, stop=7))
z

t<- c(substr(y, start=8, stop=12))
t

u<- c(substr(y, start=13, stop=16))
u

    If I look to x,z,t,u I can see that I seperated it according I want it.

data<- paste(df_t, col='Genetic', c('x','z','t','u'), sep="-")

My question is to become the row_names as following:
                          1     2      3    4       5      6         Genetic

                          1     2      3    4       5     "2012S-GA-00793-0001"
                          2     3      4    5       6     "2012S-GA-00836-0001"
                          3     4      4    5       2     "2012S-GA-00917-0001"
                          2     1      2    3       5     "2012S-GA-00920-0001"
                          3     3      5    4       7     "2012S-GA-00921-0001"

But it doesn't work when I want to put these x,z,t,u together and change the row names to genetic. I tried to use unite function but it doesn't work neither.
Do anyone have any idea how can I add hyphens between specific digits and characters.

A: library(tidyverse)

dat %>%
   separate(row_names, letters[1:5],cumsum(c(1,5,2,5,4)))%>%
   unite('Genetics',letters[2:5], sep='-')
                  X1 X2 X3 X4 X5 X6 a            Genetics
X2012SGA007930001  1  2  3  4  5  6 X 2012S-GA-00793-0001
X2012SGA008360001  1  2  3  3  2  6 X 2012S-GA-00836-0001
X2012SGA009170001  1  2  3  4  5  6 X 2012S-GA-00917-0001
X2012SGA009180001  1  3  2  3  4  2 X 2012S-GA-00918-0001
X2012SGA009200001  3  4  5  4  2  1 X 2012S-GA-00920-0001
X2012SGA009210001  4  5  6  7  8  9 X 2012S-GA-00921-0001

A base R approach: Decided to use pipe and shorten each line fore clarity:
paste(dat$row_names, collapse = '\n')|>
   textConnection()|>
   read.fwf(c(1,5,2,5,4), colClasses = 'character')|>
   subset(select = -V1) |>
   c(sep = '-') |>
   do.call(paste, args = _)|>
   cbind(dat, Genetics = _)

                  X1 X2 X3 X4 X5 X6         row_names            Genetics
X2012SGA007930001  1  2  3  4  5  6 X2012SGA007930001 2012S-GA-00793-0001
X2012SGA008360001  1  2  3  3  2  6 X2012SGA008360001 2012S-GA-00836-0001
X2012SGA009170001  1  2  3  4  5  6 X2012SGA009170001 2012S-GA-00917-0001
X2012SGA009180001  1  3  2  3  4  2 X2012SGA009180001 2012S-GA-00918-0001
X2012SGA009200001  3  4  5  4  2  1 X2012SGA009200001 2012S-GA-00920-0001
X2012SGA009210001  4  5  6  7  8  9 X2012SGA009210001 2012S-GA-00921-0001

A: Assuming the string lengths are consistent, you could vectorize substr with mapply.
dat$genetic <- sapply(dat$row_names, \(x) paste(mapply(substr, list(x), c(2, 7, 9, 14), c(6, 8, 13, 17)), collapse='-'))
dat
#                   X1 X2 X3 X4 X5 X6         row_names             genetic
# X2012SGA007930001  1  2  3  4  5  6 X2012SGA007930001 2012S-GA-00793-0001
# X2012SGA008360001  1  2  3  3  2  6 X2012SGA008360001 2012S-GA-00836-0001
# X2012SGA009170001  1  2  3  4  5  6 X2012SGA009170001 2012S-GA-00917-0001
# X2012SGA009180001  1  3  2  3  4  2 X2012SGA009180001 2012S-GA-00918-0001
# X2012SGA009200001  3  4  5  4  2  1 X2012SGA009200001 2012S-GA-00920-0001
# X2012SGA009210001  4  5  6  7  8  9 X2012SGA009210001 2012S-GA-00921-0001

Data:
dat <- structure(list(X1 = c(1L, 1L, 1L, 1L, 3L, 4L), X2 = c(2L, 2L,
2L, 3L, 4L, 5L), X3 = c(3L, 3L, 3L, 2L, 5L, 6L), X4 = c(4L, 3L,
4L, 3L, 4L, 7L), X5 = c(5L, 2L, 5L, 4L, 2L, 8L), X6 = c(6L, 6L,
6L, 2L, 1L, 9L), row_names = c("X2012SGA007930001", "X2012SGA008360001",
"X2012SGA009170001", "X2012SGA009180001", "X2012SGA009200001",
"X2012SGA009210001")), class = "data.frame", row.names = c("X2012SGA007930001",
"X2012SGA008360001", "X2012SGA009170001", "X2012SGA009180001",
"X2012SGA009200001", "X2012SGA009210001"))


text:
Q: Running my first Spider, iterating through data returns None I am writing my first Spider with Scrapy, my goal is to scrape the imdb top 100 movies webpage, get the rating, title, and link of each movie. I am trying to iterate through every movie and store it's values in a dictionary, however when I attempt to iterate through the movies the Spider returns 'none' for each one.
    def parse(self, response):
       for movie in response.css('table.chart td'):
           yield {
               'title': movie.css('td.titleColumn a::text').get(),
               'rating': movie.css('td.ratingColumn.imdbRating strong::text').get(),
               'link': movie.css('td.titleColumn a::attr(href)').get(),
           }

Could someone explain to me why it's returning None?
When I change movie.css to response.css it returns the requested data for the first movie.

A: Looks like your selector is incorrect.

*

*response.css('table.chart td') will return a list of Selector objects.

*movie is a Selector object.

When you write movie.css('td.titleColumn a::text'), it combines both the selectors which effectively translates to the following:
response.css('table.chart td td.titleColumn a::text')

Is the selector a valid selector in your specific case?
The official docs on Selector should be helpful for you.


text:
Q: Setting an Image to my Image control private void SetShipmentStatus(bool status)
{
    if (status)
    {
        txtStatus.Text = "Su envio fue entregado!";
        imgStatus.Source = ???
    }
}

How can I give my XAML Image control a source programatically? I have the image in this location as Resource:


text:
Q: Weird onClick behavior on an element generated by ZF Helper I am using FormImage Helper from Zend Framework 1 in a project. The output generated by the helper (on lines 84-91) is as follow:
<input type="image" name="form_image" id="form_image" src="/images/icons/16x16/user1_add.png">

On the application I am getting a weird behavior where I click on such "image" and I got redirected to a URL. Why? I don't think there is a event handler for the class or the name not even for the input. This is an image of the event listeners for the element:

I have tried the same line on jsFiddle and there is not such behavior so I am confused, any advices?


text:
Q: C++ cost of default constructors for string, list, vector In many cases I would like to pass reference to const string parameter with default being empty string.
void func(std::string const& z = std::string());

I am wondering how expensive is calling default constructor vs. passing reference to some static empty string?
void func(std::string const& z = my_staticEmptyStr);

What about lists and vectors?
Update. Unfortunately, I do not see a nice generic way to have static empty-xxx objects, except having its own copy in every class that needs it. Fortunately, it seems to me that none of the default constructors for stl classes require memory allocations, so I decided to do it in a traditional way on all paths except frequently called ones.

A: It depends on the implementation. If the string in your standard library uses the "small string optimization" (which most modern libraries do), strings default constructor might be as small as three instructions. (zeroing three words).
vector and list can also be very cheap to initialize, but it depends on the implementation.

A:
I am wondering how expensive is calling default constructor vs passing reference to some static empty string?

If you have a static empty string, it is better to use it. Constructing a new object and destructing it is going to cost some time, however small it may be.
You don't lose anything by using the static empty string if construction and destruction of a default constructed std::string does not take any time at all.
You potentially gain quite a bit of time over the life of the program depending on how may times the function gets called if a default constructed std::string takes even a small amount of time in the constructor and the destructor.


text:
Q: How to prove this inequality with absolute value For every $x,y,z \in \mathbb{R} $
$$
|x|+|y|+|z| \leq |x+y-z|+|x-y+z|+|-x+y+z|
$$
I tried to prove it by cases, but I have troubles when the three numbers have the same sign.

A: Because
$$\sum_{cyc}|x+y-z|=\frac{1}{2}\sum_{cyc}\left(|x+y-z|+|x+z-y|\right)\geq\frac{1}{2}\sum_{cyc}|x+y-z+x+z-y|=\sum_{cyc}|x|$$

A: if all of the numbers are positive then the left is $x+y+z$ and the right is at least $x+y+z$ (that is what you get when you remove the absolute values).
Notice that if all three are negative all of the expressions have the same values as with $(-x,-y,-z)$.


text:
Q: Avoid part of a string search in elasticsearch I have a scenario where i want to search for 'bank of india' and documents retrieved have hits for 'reserve bank of india', 'state bank of india', etc. Basically the search string named entity is part of another named entity as well.
What are the ways to avoid it in elasticsearch?

A: If you use keyword type instead of text as the mapping for your entity field you will no longer have those partial matches. keyword says treat this text like a single unit (named entities are like this), while text says treat each word as a unit and consider the field as a bag of words, So the query looks for the most word matches, regardless of order or if all of the words are there. There are different queries that can get at that requiring order (match_phrase) and requiring all words to be matches (minimum_should_match parameter), but I like to use the term query if you follow the keyword mapping strategy. Does that make sense?


text:
Q: how to read xls chart in java? I am using POI API to read a template n to create an XLS file through java.
I want to get the chart from the template. IS there any way to do so?

A: You can use JFree chart API to create charts in excel.. http://www.programming-free.com/2012/12/create-charts-in-excel-using-java.html

A: Maybe Andy Khan's JExcel can help you.  It's a terrific tool.  I much prefer it to POI.

A: If you build the chart into the template it will automatically update when you insert data into the spreadsheet.
If you are wanting to create a chart from scratch I believe that this functionality is not yet available in POI.
from the POI site:

You can not currently create charts.
  You can however create a chart in
  Excel, modify the chart data values
  using HSSF and write a new spreadsheet
  out. This is possible because POI
  attempts to keep existing records
  intact as far as possible.

POI Limitations

A: Do you mean a way to get a GIF or JPEG? Actuate e.Spreadsheet can create images from Excel charts and ranges, but it's expensive (I worked there until 2002 but have no affiliation now).

A: // officetools.jar available at http://www.dancrintea.ro/xls-to-pdf/

import officetools.OfficeFile;

FileInputStream fis = new FileInputStream(new File("test.xls"));

OfficeFile f = new OfficeFile(fis, "localhost", "8100″, false);

// read a column
for (int i=0; i<=99; i++)
    System.out.println(f.getCell(1,i));


text:
Q: Applying dynamic arguments to JavaScript function but deferring invocation Consider this JavaScript code:
var someArg = "Hello";
elem1.onclick = function() { foo(someArg); };
someArg = "Bye";
elem2.onclick = function() { foo(someArg); };

I would like to invoke foo with the argument "Hello" when I click on elem1, however, the way above code works, foo is invoked with "Bye" every time.
Basically, I'd like to apply someArg to foo but not actually invoke foo until later.

A: The usual way you do this is with a builder function:
var someArg = "Hello";
elem1.onclick = buildHandler(someArg);
someArg = "Bye";
elem2.onclick = buildHandler(someArg);

function buildHandler(arg) {
    return function() { foo(arg); };;
}

...or with Function#bind:
var someArg = "Hello";
elem1.onclick = foo.bind(null, someArg);
someArg = "Bye";
elem2.onclick = foo.bind(null, someArg);

Either way, what you're doing is creating a new function that, when called, calls foo with the value you pass it. The reason your original code doesn't work is that the functions close over the variable someArg, not its value as of when they're created. So since they use the value when they're called, you don't get the value you want. Both of the solutions above (in different ways), create functions that close over something taking the value as of when the function is created instead.

A: This is because, this is how Javascript works. You will have to invoke foo() with different variables to achieve this. I only see one workaround for this..
var someArg1 = "Hello";
var someArg2 = "Bye";
elem1.onclick = function() { foo(someArg1); };
elem2.onclick = function() { foo(someArg2); };

This is because, foo will get the argument only when you call foo() and the argument will be the value of the variable someArg at that point of invocation. And since Javascript executes everything outside a function call on page load, it will execute someArg = 'Bye' as well on page load.

A: The way you have it set up, javascript is changing the definition of someArg on load, almost immediately after it first defines it.  You need to use another variable like so:
var someArg = "Hello";
elem1.onclick = function() { foo(someArg); };
var someArg2 = "Bye";
elem2.onclick = function() { foo(someArg2); };

or pass a variable into the function and define that variable elsewhere:
elem1.onclick = function(someArg) { foo(someArg); };
elem2.onclick = function(someArg) { foo(someArg); };
//Some stuff happens....
thisVariable = 'stuff happened';
elem2.onclick(thisVariable);

This will result in foo being called with 'stuff happened' in the argument.
Hopefully this helps.  If not, please provide more details on your use case so we can focus our answers a bit more.


text:
Q: Breadboard minimum lead length What's the minimum lead length for a component in order to reliably connect with solderless breadboard contacts?
Reading specs on cables, relays LEDs, and other components, what should I take as the minimum distance from the bottom of the device to the tip of the lead?  Or put another way, from the top of the breadboard to the pinch-point of its contacts?
I want to plug into a generic solderless breadboard and not worry about loose connections.  I have assumed through-hole PC board leads would be sufficient but occasionally they are not.  Case in point, a flex cable from Digi-Key has leads that are about 3.2mm or 0.125in long that keep falling out.  So the answer may be just a little longer than that.
This spec from 3M says nothing about this dimension, except that the standard interconnect wires go about 0.250in deep.

A: A standard DIP has a lead length of about 0.125" (3.1mm) but the actual penetration below the surface is probably more like 4.2mm because the holes and leads are both beveled.

A: The pins on the male jumper cables that came with my Raspberry Pi starter kit are about 8 mm/5/16".
For a specific breadboard, I'm sure this dimension can easily be determined experimentally.


text:
Q: Pulse width for mark pulse What is the pulse width for the mark pulse in an equal mark to space ratio pulse train operating at a repetition frequency of 5 MHz?
The answer is suppose to be 100 ns .But I didn't understand how to get the result.Can someone explain to me how to get the answer? Thanks in advance

A: A 5MHz waveform has a period of 200ns ( T = 1/f)
If the waveform has equal mark space ratio, then the duty is 50%. The width of a pulse is therefore 50% of the total period

A: A frequency of 5MHz has a period of 200ns. That's divided into one mark and one space. If the mark and space durations are equal, then each is exactly half of 200ns.


text:
Q: Add a JPanel in a BorderPane I have a Java project that plays a .flv media file through JavaFX Media Player, and it's working fine. Recently, I've been wanting to experiment by adding GUI components to this Project (JPanel, JLabel). However, I've failed in all my attempts and after doing some research turns out it's not as simple as i first thought.. I've tried borderPane.setTop(JLabel) but I get a "Cannot convert Jlabel to Node" error.. I feel that I'm missing something
If anyone has any idea why this isnt working for me, I would greatly appreciate any form of explanation or examples.. :)
Here is the code if it might be of use to you!
@Override
public void start(Stage stage){
    String path = "Data/Video/Clip.flv";
    Media media = new Media(new File(path).toURI().toString());

    MediaPlayer mediaPlayer = new MediaPlayer(media);
    MediaView mediaView = new MediaView(mediaPlayer);

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(mediaView);

    //borderPane.add(logoPanel);                            <<<<<<< Error

    Scene scene = new Scene(borderPane, 1024, 800);
    scene.setFill(javafx.scene.paint.Color.BLACK);

    stage.setTitle("Media Player");
    stage.setScene(scene);
    stage.show();

    mediaPlayer.setAutoPlay(true);

A: What you basically want to achieve: add some Swing components to an JavaFX application.
You have to use SwingNode class to "wrap" a JComponent.

SwingNode Class
JavaFX 8 introduces the SwingNode class, which is located in the
  javafx.embed.swing package. This class enables you to embed Swing
  content in a JavaFX application. To specify the content of the
  SwingNode object, call the setContent method, which accepts an
  instance of the javax.swing.JComponent class.

You can check this tutorial how embed Swing component into JavaFX application.
Small example to put a Swing Button into the center of a BorderPane:
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);

            SwingNode swingNode = new SwingNode();
            JButton jButton = new JButton("I am a Swing button");
            jButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Message from Swing");

                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    swingNode.setContent(jButton);
                }
            });

            root.setCenter(swingNode);

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

By the way, BorderPane has no method "add" (as in your commented line):
You can use setCenter, setTop, setBottom, setLeft and setRight to add Nodes into it (as you used to fill the center).
If your goal was not to embed Swing into JavaFX, just to use JavaFX controls, you can check this article what controls JavaFX has by default.

A: BorderPane is a JavaFX Node whereas JPanel is a Java Swing Component.
You cannot add a JPanel to a BorderPane, what you are looking for instead is the JavaFX equivalent of the JPanel which is the Pane class.
If you are developing using JavaFX it is easier to just use JavaFX components. If you must use Swing components then you can use the SwingNode class.


text:
Q: How to use the efficientnet-lite provided by tfhub for the second training on tf2.1 The version I use is tensorflow-gpu version 2.1.0, installed from pip.
import tensorflow as tf
import tensorflow_hub as hub

tf.keras.backend.set_learning_phase(True)

module_url = "https://tfhub.dev/tensorflow/efficientnet/lite0/classification/2"

module2 = tf.keras.Sequential([
    hub.KerasLayer(module_url, trainable=False, input_shape=(224,224,3))])

output1 = module2(tf.ones(shape=(1,224,224,3)))
print(module2.summary())

When I set trainable = True, the operation will give an error.
So, can't I retrain it on tf2.1 version?

A: The EfficientNet-Lite models on TFHub are based on TensorFlow 1, and thus are subject to many restrictions on TF2 including fine-tuning as you've discovered. The EfficientNet models were updated to TF2 but we're still waiting for their lite counterparts.
https://www.tensorflow.org/hub/model_compatibility
https://github.com/tensorflow/hub/issues/751
UPDATE: Beginning October 5, 2021, the EfficientNet-Lite models on TFHub are available for TensorFlow 2.


text:
Q: Nodejs (socket.io) memory usage compared to JavaScript's primitive data type memory usage First off, my title may be poorly defined or misleading, but it pretty much tries to summarize my question as a whole.
I've searched a lot without getting my questions fully answered.

*

*How does socket.io memory allocation through MemoryStorage (socket.get/socket.set) work and how much memory usage does approximately one socket.set use? Are memory freed correctly when a socket disconnects? Optional: Is there any known memory leaks I should be aware of in v0.11.0-pre?

*How does JavaScript's GarbageCollector work with objects and associative arrays declared in global scope? Are memory ultimately freed When I "delete" a key-value pair like this: "delete object[key];"? Or will RAM continuely increase as client requests increase?

*How are option 1 and 2 compared to each other? Should I use socket.set over globally declared "maps" when it comes to increasing and ultimately freeing memory? Optional: How are they compared to each other when it comes to performance ("executing" socket.get/object[key])?
As for basic information on my project, I'm developing a game server in Node.js (single process) which are expected to accept as many clients as a single server can handle (before extending to a cluster of servers). Optional: Is there something else regarding my project I should be aware of when it comes to load and memory??
Thank you for your time, it is much appreciated!


text:
Q: systeminfo command does not run on WIN XP Home Turkish I am trying to run systeminfo command on WIN XP home Turkish 32 bit. And it throw error-
'systeminfo' iç ya da dış komut, çalıştırılabilir program ya da toplu iş dosyası olarak tanınmıyor.

While this runs fine on English XP. Is there any special command in Turkish to get system information?

A: The systeminfo program comes with XP Professional if I remember correctly (see here, for example), so I don't think it's related to the fact you have a Turkish edition at all.
Since you have XP Home, it doesn't ship with that program, and copying it from a Professional installation may be ... worrisome from a copyright or licensing point of view.
One option is to download the sysinternals stuff from Microsoft, that contains a great many tools that may be able to give you what you need.


text:
Q: (Solved) Laravel New Installation - Removing PHP 7.1.23 from Mac without Brew Solution: I've updated my OS to the latest version where the latest PHP was supported.
I've got a new laravel project
When I run php artisan serve
it shows:
MacBook-Pro% php artisan serve

Warning: require(/Users/username/Desktop/code/argon/vendor/autoload.php): failed to open stream: No such file or directory in /Users/username/Desktop/code/argon/artisan on line 18

Fatal error: require(): Failed opening required '/Users/username/Desktop/code/argon/vendor/autoload.php' (include_path='.:') in /Users/username/Desktop/code/argon/artisan on line 18

composer update shows
MacBook-Pro% composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - This package requires php ^7.2.5 but your PHP version (7.1.23) does not satisfy that requirement.
  Problem 2
    - laravel/tinker v2.2.0 requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
    - laravel/tinker v2.1.0 requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
    - laravel/tinker v2.0.0 requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
    - laravel/tinker 2.x-dev requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
    - Installation request for laravel/tinker ^2.0 -> satisfiable by laravel/tinker[2.x-dev, v2.0.0, v2.1.0, v2.2.0].

MacBook-Pro% php -v
PHP 7.1.23 (cli) (built: Nov  7 2018 18:20:35) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies

also
MacBook-Pro% brew unlink php@7.1
Error: No such keg: /usr/local/Cellar/php@7.1
MacBook-Pro% brew unlink php71
Error: No such keg: /usr/local/Cellar/php71

also
MacBook-Pro% which php
/usr/bin/php

Any ideas how to remove php 7.1.23 ?

A: php -v gives the following response:
WARNING: PHP is not recommended
PHP is included in macOS for compatibility with legacy software.
Future versions of macOS will not include PHP.
The release notes for Catalina contain the following remark:

Info here

Scripting Language Runtimes Deprecations Scripting language runtimes
such as Python, Ruby, and Perl are included in macOS for compatibility
with legacy software. Future versions of macOS won't include scripting
language runtimes by default, and might require you to install
additional packages. If your software depends on scripting languages,
it's recommended that you bundle the runtime within the app.

In short: macOS continues to include 'legacy' versions of things like Python, Ruby, Perl, and indeed PHP, so that existing code won't break, but Apple is leaving it to the user to install the versions that they want to use.

A: Found a solution !
brew install php72
brew switch php@7.2 7.2.25

https://laravel.com/docs/6.x/homestead


text:
Q: How to use negative regex matching with grep -E? I'm using the following regex via grep -E to match a specific string of chars via | pipe.
$ git log <more switches here> | grep -E "match me"

Output:
match me once
match me twice

What I'm really looking for a is a negative match (return all output lines that don't contain the specified string something like the following but grep doesn't like it:
$ git log <more switches here> | grep -E "^match me"

desired output:
whatever 1
whatever 2

here is the full output that comes back from the command line:
match me once
match me twice
whatever 1
whatever 2

How to do arrive at the desired output per a negative regex match?

A: Use the -v option which inverts the matches, selecting non-matching lines
grep -v 'match me'

Another option is to use -P which interprets the pattern as a Perl regular expression.
grep -P '^((?!match me).)*$'


text:
Q: Best way to make List> to List , List in java I have a List(Pair(a,b)), i want to extract all b element and put them in one list( List(b))
what is the best way?

A: This is java 9:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Map.Entry<String, String>> list = Arrays.asList(
                Map.entry("a", "b"),
                Map.entry("a", "b"),
                Map.entry("a", "b")
        );
        System.out.println(list);
        List<String> result = list.stream().map(Map.Entry::getValue).collect(Collectors.toList());
        System.out.println(result);
    }
}


text:
Q: Understanding the logic flow of mock tests In an effort to learn the logic flow of mock tests I've unsuccessfully reproduced a test from a Symfony article using code from my application.
Background: Volunteer entity extends the abstract class Person, which extends the FOSUserBundle model User.  Person includes methods for firstName, lastName, and name.  Name returns lastName, firstName. The test that appears below returns this:
--- Expected
+++ Actual
@@ @@
-'Borko, Benny'
+', '

How should this test be modified?  Better yet, how do you tell when it's your test design and not the system under test that's failing?
Edit: see result of applying proposed solution below
Edit #2:
Not sure if this is relevant: Volunteer and two other entities are mapped via Inheritance Mapping to the Person entity (see PUGXMultiUserBundle).
The test:
use Truckee\MatchingBundle\Entity\Volunteer;

class MockVolunteerTest extends \PHPUnit_Framework_TestCase
{
    public function testFullName()
    {
        // First, mock the object to be used in the test
        $volunteer = $this->getMock('\Truckee\MatchingBundle\Entity\Volunteer');
        $volunteer->expects($this->once())
                ->method('getFirstName')
                ->will($this->returnValue('Benny'));
        $volunteer->expects($this->once())
                ->method('getLastName')
                ->will($this->returnValue('Borko'));

        // Now, mock the repository so it returns the mock of the volunteer
        $volunteerRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')
                ->disableOriginalConstructor()
                ->getMock();
        $volunteerRepository->expects($this->once())
                ->method('find')
                ->will($this->returnValue($volunteer));

        // Last, mock the EntityManager to return the mock of the repository
        $em = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
                ->disableOriginalConstructor()
                ->getMock();
        $em->expects($this->once())
                ->method('getRepository')
                ->will($this->returnValue($volunteerRepository));

        $user = new Volunteer();
        $this->assertEquals('Borko, Benny', $user->getName());
    }
}

Proposed solution:
class VolunteerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Volunteer
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new Volunteer();
    }

    public function testGetterAndSetter() {
        $this->assertNull($this->object->setFirstName("Benny"));
        $this->assertEquals("Benny", $this->object->getFirstName());

        $this->assertNull($this->object->setLastName("Borko"));
        $this->assertEquals("Borko", $this->object->getLastName());

        $this->assertEquals('Borko, Benny', $this->object->getName());
    }
}

Test results:

Failed asserting that Truckee\MatchingBundle\Entity\Volunteer Object
  &0000000067c9c33f00000000680c6030 (
      'id' => null ...
      'credentialsExpireAt' => null ) is null.

A: The main goal of mocks is to test repositories or services. There is a easier way to test your entity:
class VolunteerTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var Volunteer
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new Volunteer();
    }

    public function testGetterAndSetter() {
        $this->assertNull($this->object->setFirstName("Benny"));
        $this->assertEquals("Benny", $this->object->getFirstName());

        $this->assertNull($this->object->setLastName("Borko"));
        $this->assertEquals("Borko", $this->object->getLastName());
    }

}

A: The answer here is that the test is an inappropriate use of mock testing.  After reading the article "An Introduction to Mock Object Testing" it became clear that the technique is to mock the dependencies of the system (object) under test, not the object itself. In the test I attempted, the Volunteer entity was the SUT so it should not have been mocked.


text:
Q: JavaFX, Maven: Alternatives to JLink Currently I'm trying to create a runnable jar for my maven project. The problem is, that I use the automatic module itextpdf, which apparently cannot be used with jlink.
Are there alternatives for creating a runnable jar with javafx and maven in eclipse? I just can't figure out, how to make this work.
My POM.xml looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Mpp_App</groupId>
  <artifactId>Mpp_App</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>Dacemo</name>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <release>12</release>
        </configuration>

      </plugin>
        <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.2</version>
        <configuration>
            <release>12</release>
            <jlinkImageName>mppapp</jlinkImageName>
            <mainClass>app.Start</mainClass>
        </configuration>
        </plugin>

    </plugins>

  </build>

  <dependencies>
        <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
      <exclusions>
        <exclusion>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
        </exclusion>
        <!-- maven note: must manually exclude all ancestors
                see http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html -->
        <exclusion>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
      <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>12.0.1</version>
      </dependency>
      <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>12.0.1</version>
      </dependency>
    <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-graphics -->
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-graphics</artifactId>
        <version>12.0.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.jfoenix/jfoenix -->
    <dependency>
        <groupId>com.jfoenix</groupId>
        <artifactId>jfoenix</artifactId>
        <version>9.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.0.6</version>
</dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.15</version>
    </dependency>

  </dependencies>
</project>


text:
Q: JUnit integration test with parameterized annotations In my integration tests I use custom annotations to start part of my application. I definitively need to use these annotations for my tests. Therefore, a typical integration test looks like this:
@Test
@MyAnnotation(a = MyEnum.B, b = someOtherConstant)
public void test() {
}

What I'd like to do is to run the tests for all enums in MyEnum. I thought about using a parameterized tests. But since the value I pass into the annotation must be constant, I think this is not an option. What other options do I have?

A: I don't think there is a need for an annotation here.
A very simple enum:
package stackoverflow52828976;

public enum MyEnum
{
   A,
   B,
   C;

   public boolean isA()
   {
      return this == A;
   }
}

The test class:
package stackoverflow52828976;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith( Parameterized.class )
public class MyEnumTest
{

   @Parameterized.Parameters
   public static Collection<Object[]> data()
   {
      final List<Object[]> list = new LinkedList<>();

      list.add(new Object[]{ MyEnum.A, true});
      list.add(new Object[]{ MyEnum.B, false});
      list.add(new Object[]{ MyEnum.C, false});

      return list;
   }

   private final MyEnum e;
   private final boolean testResult;

   public MyEnumTest
         ( final MyEnum    anEnum
         , final boolean   aTestResult
         )
   {
      this.e = anEnum;
      this.testResult = aTestResult;
   }

   @Test
   public void testIsA() throws Exception
   {
      assertEquals(testResult, e.isA());
   }

}


text:
Q: Pandas Dataframe: IndexError: single positional indexer is out-of-bounds I'm trying to populate a matrix with values from a pandas dataframe, but get the error message: IndexError: single positional indexer is out-of-bounds. Can anyone help me solve this problem?
ampl.param['request'] = {
    (subjects[i], 1+p): request.iloc[p, i]
    for i in range(len(subjects))
    for p in range(len(students))
}

pandas dataframe

A: loop over range(1, len(subjects)) and try this  (subjects[i-1], p): request.iloc[p-1, i-1]


text: Q: Can the Android SDK work with JDK 1.8? I have a java project compiled with java 1.8 working on eclipse, now i want to change that code android project, but after setting complier as jdk 1.8 my error of java are not removing, that means that the compiler not working with 1.8 , please suggest how can i compile my android code with jdk 1.8.


text:
Q: Cannot remove or add class using jQuery I am trying to operate a toggle class on an element but cannot use the toggleClass facility as the script is running other functions and is being actioned on the classname. Therefore I am using removeClass / addClass. For some reason I cannot get it working. Please find my script below;
$(".view-followers").click(function(){
    alert("off");
    $(this).removeClass("view-followers");
    $(this).addClass("view-followers-on");

});

$(".view-followers-on").click(function(){
    alert("on");
    $(this).removeClass("view-followers-on");
    $(this).addClass("view-followers");
});

or you can view is on jsFiddle;
http://jsfiddle.net/dannyj6/UGBda/
Thank you for any help you can provide

A: Try
$(".view-followers, .view-followers-on").click(function(){
    $(this).toggleClass("view-followers view-followers-on");
});

Demo: Fiddle
if you want to have two separate handlers then use event delegation
$(document).on('click', '.view-followers', function(){
    $(this).removeClass("view-followers").addClass("view-followers-on");

});
$(document).on('click', '.view-followers-on', function(){
    $(this).removeClass("view-followers-on").addClass("view-followers");
});

Demo: Fiddle

A: That's because when the page is loaded there is not element with class of view-followers-on, so jQuery can't find the target element, you should delegate the event, but I would suggest adding another class and using toggleClass method(in case that you are using 2 handlers just for adding and removing classes):
$(".follow").on('click', function(){
    $(this).toggleClass("view-followers view-followers-on");
});

Usually there is no need to toggle 2 classes, using one class is enough.

A: The click handlers will be attached when the script gets executed for the first time. This means that the element with the class "view-followers-on" doesn't exist, yet. They are attached to the element itself, that is why only the first handler is called.

A: It works but the problem is you must reassign the handler for "-on" and remove the handler for off. It is probably better to use a extra class for the handler which checks for the current state and replaces the state.

A: This function looks for either of the two classes, view-followers OR view-followers-on.
If either of these are detected, it will toggle the two classes on the selector, essentially toggling the class that is applied to the element.
This will also work on dynamic elements as it uses event delegation to detect elements created after page load.
$(document).on('click', '.view-followers,.view-followers-on', function(){
    $(this).toggleClass("view-followers view-followers-on");
});

A: use the toogleClass() function it will call alternative
$(".view-followers, .view-followers-on").click(function(){
    $(this).toggleClass("view-followers view-followers-on");
})

;


text:
Q: nodejs - Export queries result to other files I'm doing some query to retrieve some data from a database, and trying to export said data to be used in my nodejs aplication. But everything I've tried so far, does not work.
r.js

async function site() {
  var test = await db
    .select("*")
    .from("site_credentials")
    .then(data => {
      return data;
    });

  return test;
}

module.exports = { user: site().then(data=>{return data})}

but I always get Promise pending. Even when I do the imports:
import users = require("./r")

users.then(data=>{return data})

and still doesnt work. How can I fix this?
Thank you,

A: For starters, there's no reason to resolve a promise and immediately return the same object resolved in its then block.  Just omit the "then" if there is nothing else you need to do.
So this:
async function site() {
  var test = await db
    .select("*")
    .from("site_credentials")
    .then(data => {
      return data;  <--- this isn't necessary.  Only adds noise unless there is something else you need to do.  It's similar to "catching" and immediately "rethrowing" an error... just pointless
    });

  return test;
}

Can be this:
async function site() {
  var test = await db
    .select("*")
    .from("site_credentials");
  return test;
}

Secondly, I'm not really sure why you're trying to resolve it in the export.  Just export the function.
module.exports = site;

Then when you require it elsewhere in your app, call it and resolve it there:
const users = require("./r")

users.then(data=>{
  // do something with your data here...
})

Note that in your first example, you are exporting an object, containing a "users" property which is the function.  If you do it that way, you would need to invoke it like so:
const users = require("./r")

users.users().then(data=>{
  // do something with your data here...
})

You can see that users.users clearly doesn't make sense.  So, export properly to avoid that.  Export only the function itself, not nested inside some other object.
But, if you look closely, you'll notice another thing I did wrong.  I'm exporting a "site" function, yet requiring it in as a "users" function.  Naming conventions matter.  If this function is called "site" here, you ought to require (or import depending on your module loader...) it in as "site"... thus:
const site = require('./r');

Otherwise you just confuse the crud out of a fellow developer.


text:
Q: Webserver isn't working after moving to new location I had a webserver that was up and working. I recently moved to a new location and brought my server with me. It is now not working remotely but is locally. It's a Ubuntu system running apache2.

*

*I verified that it has the correct IP address given to it, and port 80 is forwarded to this IP on the router.

*On my LAN, I type in the local IP address of the webserver and I see the webpage.

*I did a curl ifconfig.me and put that address into Chrome and it does not show my webpage, just a 'website cant be reached'.

(for what its worth, my domain name A record was changed and properly points to the new public IP as well, but I am using the public IP for troubleshooting purposes)
To me, it seems like a forwarding issue, but the router settings have not changed since the move and everything look to be fine.  Other forwarding rules for other servers are unchanged and work fine.
Is there anything I am missing here?

A: ISP was blocking, had to log into account and allow port 80.


text:
Q: Automate firebase analytics using Appium Can we automate firebase analytics(events/views) triggered from android/ios apps using appium-java?
i have just triggered the events that needs to be automated and stuck with proceeding further...
Is it possible to link to firebase analytics and query the data to validate?
(or)
Is there any other way that we can catch the analytic events while triggering the events from app?
I have gone through many articles not getting correct answer
Please advise, Thank you!

A: Option 1 -

*

*Generate a build with unique build#.

*After Appium execution for the events, initiate web browser through selenium.

*Filter that specific  build version in Firebase and check the events

Option 2 -

*

*Track network calls and validate the requests.


text:
Q: Android: Use Google API for Real-time directions, or Communicate with Google Maps? I know this question has been asked before, but I could not find a satisfactory answer: Is it possible to get Real-Time Direction updates from the Google API available to Android. The Google Maps API only provides the visual functionality, but not any directional capability. The Google Directions API is not meant to be used for real-time direction. Is there anything that could be used in this capacity, or should I try instead to communicate with the Android Google Maps app and gather directions through that?

A: @Benjamin, I think it is not possible; in the Google Maps/Google Earth APIs Terms of Service under:

10.4 Restrictions on Unfair Exploitation of the Service and Content
c.Restrictions on your Maps API Implementations.
iii.No navigation. You will not use the Service or Content for or in connection with (a) real-time navigation or route guidance; or (b) automatic or autonomous vehicle control.


text:
Q: How to implement view and url patterns for Post and Category models in Django 3 I'm trying to learn Django by building a simple blog. I have three models: Post, Category, and Tag.
    class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True, null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    updated_on = models.DateTimeField(auto_now=True)
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=POST_STATUS, default=0)
    visibility = models.IntegerField(choices=POST_VISIBILITY, default=0)
    content = models.TextField()
    excerpt = models.TextField()
    category = models.ForeignKey('blog.Category', on_delete=models.CASCADE)
    tags = models.ManyToManyField('blog.Tag')
    image = models.ImageField(upload_to="images/", default=0)

    class Meta:
        ordering = ['-created_on', 'title']
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'
        unique_together = ('title', 'slug')

    def __str__(self):
        return self.title

class Category(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True, null=False)
    description = models.TextField()

    class Meta:
        ordering = ['title']
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
        unique_together = ('title', 'slug')

    def __str__(self):
        return self.title

class Tag(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True, null=False)
    description = models.TextField()

    class Meta:
        ordering = ['title']
        verbose_name = 'Tag'
        verbose_name_plural = 'Tags'

    def __str__(self):
        return self.title

I have two views - posts_index shows all the posts, and single should show a single post.
from django.shortcuts import render
from .models import Post, Category, Tag

def posts_index(request):
    all_posts = Post.objects.all()
    return render(request, 'index.html', {'posts': all_posts})

def single(request, slug, category):
    single_post = Post.objects.get(slug=slug)
    return render(request, 'single.html', {'single': single_post, 'category_slug': single_post.slug})

In mu urls.py I have the following configuration:
from django.urls import path
from . import views

urlpatterns = [
        path('', views.posts_index, name='index'),
        path('<slug:category_slug>/<slug>/', views.single, name='single')
]

I added several categories (General, Sports...) and their slugs are same as titles but lowercase i.e. general, sports.
I want to achieve that when I click on a post title on my index page (I already have that sorted out in templates) that I am transferred to a single blog post page with a url that looks like this: example.com/category-slug/my-post-slug
Currently, I'm getting this error:
TypeError at /general/test-post-we-hope-best/

single() got an unexpected keyword argument 'category_slug'

Request Method:     GET
Request URL:    http://127.0.0.1:8000/general/test-post-we-hope-best/
Django Version:     3.0.5
Exception Type:     TypeError
Exception Value:

single() got an unexpected keyword argument 'category_slug'

Exception Location:     /Users/XXXXX/XXXXXXX/lib/python3.8/site-packages/django/core/handlers/base.py in _get_response, line 113

This is the index.html template that looks and work fine, but when I click on links it throws an error i pasted above.
<!DOCTYPE html>

    <title>Example</title>

    {% for post in posts %}

{{post.title}}

Posted in: {{post.category}}, Posted by: {{post.author}}

{{post.excerpt}}

    {% endfor %}

Any help would be greatly appreciated, I'm stuck on this one for a while now.
Thanks!

A: {% url 'single' post_id %}

and if you have two slugs
{% url 'single' post_id, another_id %}

Will do that for you, but I suggest to change the url name for something like post_details.

A: There - I was able to figure it out myself, here's the view function now:
def single(request, slug, category_slug=None):
    single_post = Post.objects.get(slug=slug)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
    return render(request, 'single.html', {'single': single_post, 'category_slug':category_slug})

And in your url.py you simply pass it as an argument like this:
urlpatterns = [
    path('', views.posts_index, name='index'),
    path('<slug:category_slug>/<slug>/', views.single, name='single')
]


text:
Q: Can a PAGEDLIST save the current URL? in ASP.net MVC4 VIEW
//Some Codes in my VIEW
@foreach (var item in Model._oList)
{
    //Grid table code
}

@Html.PagedListPager((IPagedList)ViewBag.activityList , page => Url.Action("Solution",new { page }),PagedListRenderOptions.OnlyShowFivePagesAtATime)

CONTROLLER
//For my pagination Code
var pageNumber = page ?? 1;
var onePageNumberBugs = _oList.ToPagedList(pageNumber, 5);
ViewBag.activityList = onePageNumberBugs;

First load of my Page
(URL:) http://localhost:50969/Home/Solution?value=00003%20

When I click my Pagination from my page, the URL will  be
(URL:) http://localhost:50969/Home/Solution?page=2

My question is, How can I make my URL like this:
(URL:) http://localhost:50969/Home/Solution?value=00003%20&page=2

or
(URL:) http://localhost:50969/Home/Solution?page=2&value=00003%20

So that I can use my value for my controller for other purposes.

A: To retain your value, you should change your pagination link as follow:
@Html.PagedListPager((IPagedList)ViewBag.activityList , x => Url.Action("Solution",new {value = ViewBag.StoredValue, page = x}),PagedListRenderOptions.OnlyShowFivePagesAtATime)

And your action will look like:
public ActionResult Solution(string value, int? page)
{
    ViewBag.StoredValue = value;
    //do what you want to do here
}

The trick here is to cache the value in your query string to ViewBag and use it inside your pagination link. So whenever you go to new page, you also pass your current value to your action

A: try to send value in querystring from view
@Html.PagedListPager((IPagedList)ViewBag.activityList , page => Url.Action("Resolution",new { page,value=YOURVALUE }),PagedListRenderOptions.OnlyShowFivePagesAtATime)

A: It's better to pass the value as a MODEL
@Html.PagedListPager((IPagedList)ViewBag.activityList , page => Url.Action("Solution",new { Model.variable_name ,page }),PagedListRenderOptions.OnlyShowFivePagesAtATime)

CONTROLLER
public ActionResult Resolution(int? page, SolutionModel _oSolutionModel)
{ /*Some codes*/ }

A: This works for me.
@Html.PagedListPager(Model, p => Url.Action("", "Solution/" , new { p, tanz = Request.Params["value"] }))


text:
Q: EF: Avoiding multiple update statements Code like this:
var compIds = from p in packinglist.List
              select p.ComponentId;
var components = from c in context.Components
                 where compIds.Contains(c.Id)
                 select c;
 foreach (var item in components)
 {
     item.CurrentSiteId = packinglist.DestinationId;
 }
 context.SaveChanges();

Ends up issuing lots of SQL Statements like
update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] = @1)

Is there a way to instruct EF (Code First) to issue the following statement:
update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] in (....))

Or should I look into using the one of the SQLQuery methods available, or a seperate tool like Dapper or massive or ...?

A: There is not currently a way to perform bulk updates in EF 4 out of the box. There are some very long, complicated work arounds that end up generating SQL though. I suggest using a stored procedure or T-SQL. Here's a quick T-SQL snippet that I've used in the past:
using (var context = new YourEntities())
{
    context.ExecuteStoreCommand(
                     @"UPDATE Components SET CurrentSiteId = 1 WHERE ID IN(1,2,3,4)");
}

A: The simplest answer for this is just to write that query and use DbContext.SQLQuery() to run it. As mentioned, there's no way to do this in EF itself.


text:
Q: Using a distributed processing system for FOREGROUND requests in PHP I'm familiar with php-resque and other job-processing systems for handling background jobs, but I don't think it'll do what I need.
In this case, I have an incoming web service request that needs to perform multiple (2-4) independent callouts to external systems and return with a consolidated response to the client. Each callout might take 300-500ms, so I want each callout to be performed in parallel so that the entire process takes no more than 500ms+/- total.
my problem with php-resque and other systems is that waiting even 1 second to start issuing those callouts is too long to wait, and I'm considering another approach.
What I'm thinking:

*

*each individual callout is described and stored in a database with a given unique request ID

*we kick off the jobs immediately as a asynchronous php process (aka "worker process")

*Each worker writes its result back to the job record and indicates that it's complete

*meanwhile, we poll the job table every 50-100ms to check on the status of each job

*when each is complete, we parse the results as necessary and return the response.

Of course, we'd implement a timeout for each request and the overall process...
Thoughts? Am I wrong? Could php-resque kick off multiple jobs in parallel virtually instantly?

A: Your plan should work, but I think you could avoid all the database communication and even polling by using the PHP Process Control functions.

*

*Fork your main process as many times as tasks you need it to run in parallel. See: pcntl_fork

*Perform your tasks in those forked processes and let them exit normally.

*The process that initiates the tasks should wait for them to all complete by listening for their SIGCHLD signals as they exit. Or if they don't before your chosen timeout, then send the SIGTERM signal to them to clean up. See: pcntl_sigtimedwait and posix_kill.

You will have to use these functions in a PHP CLI script, though, because...
http://www.php.net/manual/en/intro.pcntl.php

Process Control should not be enabled within a web server environment
  and unexpected results may happen if any Process Control functions are
  used within a web server environment.

But your web server could easily exec() your CLI script, which will do all the hard work, return the status of those tasks, etc.

A: If your external calls are simply HTTP requests, you could simply use curl and do multiple requests. They seem to do exactly what you need.
If it's something different, I can highly recommend Gearman.
If you want to get your hands dirty and write your own daemon, I would suggest skipping the IPC functions, and go for something a bit more high-level, such as ZeroMQ, and perhaps use Supervisord to restart the PHP processes if they die. It's relatively hard to write long-running PHP processes, so you have to build this with the notion in place that the external scripts will die randomly and prepare to handle that gracefully.


text:
Q: How can I return an object with converted type from a new operator+ (Template class) I wrote a template class for spheres. It saves their central point and their radius. Now I'm trying to write an operator+ that adds a value to the every value of the central point. The call from my main function looks like this:
Sphere<int, double> s1(1,1,1,2.5); // (x,y,z,radius)
auto s2 = s1 + 1.5;

While my operator+ looks like this:
template <typename T, typename S> class Sphere {

...

    template <typename U>
    friend Sphere operator+(const Sphere<T, S> s, U add){ // Sphere<int, double>
        decltype(s.m_x + add) x,y,z;
        x = s.m_x + add;
        y = s.m_y + add;
        z = s.m_z + add;
        Sphere<decltype(x), S> n(x,y,z,s.rad); // now Sphere<double, double>
        return n; //error occurs here
    }
};

The error message i get is:
could not convert 'n' from 'Sphere<double, double>' to 'Sphere<int, double>'

What do I have to change that it works and why is my way wrong?

A: The Sphere in your friend function's return type refers to the type of the enclosing class, so it's Sphere<int, double>. Use a trailing return type to specify the correct type
template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
    -> Sphere<decltype(s.m_x + add), S>
{ ... }

Or if you have a C++14 compiler that supports deduced return types for functions, then just drop the trailing return type.
template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
{ ... }

A: So in your example you have return n and n is made of Sphere<int, double> and Sphere<double, double>.
It gives you the error because you have the value of type int and double iss the type that the compiler expects in the other Sphere function.
Examples:
int number;
double(number);

or
static_cast<double>(number);


text:
Q: AssemblyInfo patcher in TFS TeamCity has a nice feature called AssemblyInfo patcher. I used it to set AssembliInfo version equal to build number (only in binaries). Now I need to implement the same behaviour in TFS. Is there any tool for that?

A: There's a guide for doing similar with the TFS Build Extensions  and another to Create a Custom WF Activity to Sync Version and Build Numbers

A: If you are looking for the update of version numbers specifically for AssemblyInfo files, then I would suggest taking a look at the TfsVersion activity in the Community TFS Build Extensions on CodePlex.  You can also take a look at the AssemblyInfo build workflow activity available on there as well.


text:
Q: mongodb is using most of disk space for journal and not cleaning itself I am using mongodb on production with journal enabled. I am using mongodb to store application data and also using gridfs to store images. I am using Elastic Block Storage (EBS) with 10GB for each mongodb instances I have (total 3 instances on replica).
When I checked the disk usage then I got surprised that journal folder is using almost all the space. Following is details.
bitnami@ip-172-31-25-9:~/stack/mongodb/data/db$ pwd
/home/bitnami/stack/mongodb/data/db
bitnami@ip-172-31-25-9:~/stack/mongodb/data/db$ du -h *
65M admin.0
16M admin.ns
65M bhs.0
129M    bhs.1
257M    bhs.2
513M    bhs.3
16M bhs.ns
3.1G    journal
64M local.0
1.1G    local.1
16M local.ns
4.0K    mongod.lock
4.0K    _tmp
bitnami@ip-172-31-25-9:~/stack/mongodb/data/db$ df -h journal
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      9.8G  7.0G  2.4G  76% /

However when I did mongodump on my data then I found that exported data size is only 500MB. I.e. most space is bsing used by journal. I understand journal does keep details on each write operation made which causing large file size. However I am surprised is that its not deleting old transaction.
Ideally I beleive after write transaction is flushed to disk then journal should be deleted. Is this journal folder size expected? Or I am missing some configuration? Should I think to increase the disk volume soon?
Please advice.

A: MongoDB (for MMAP storage engine) will allocate 3 journal files by default at 1GiB each.  That's where your journal related space usage is coming from, but it will not grow unless you have a very high insert rate.
You can start with the smallfiles option and reduce the size to 3 x 128MiB if you wish, but be aware that your data files will also be reduced (to 512MiB each) so there will be many more of them and they will need to be allocated more often when adding data.
As for whether to increase your storage, that depends on how much data you intend to add to the database - it will need to allocate new data files to store any data you insert, so it really is dependent on your planned usage as to whether 10GiB is enough or not.


text:
Q: Why "lock" block not work? public class ThreadInteroperateWithLock
{
    private int m_count;
    private object m_synLock;
    public ThreadInteroperateWithLock()
    {
        m_count = 0;
        m_synLock = new object();
    }

    public int Count { get { return m_count; } }

    public void Add()
    {
        //just simulate some work
        int temp=0;
        for (int i = 0; i < 10000; i++)
        {
            temp++;
        }

        //really job
        lock (m_synLock)
        {
            m_count++;
        }
    }
}

This code is in a console application:
ThreadInteroperateWithLock ope = new ThreadInteroperateWithLock();
Thread[] threadArray = new Thread[100];
for (int i = 0; i < 100; i++)
{
    Thread thread = new Thread(new ThreadStart(ope.Add));
    thread.IsBackground = false;
    threadArray[i] = thread;
}
for (int i = 0; i < 100; i++)
{
    threadArray[i].Start();
}
Console.WriteLine(ope.Count);
Console.ReadKey();

Sometime it prints '99' and sometime '100', regardless of whether the lock{...} block  exists or not. Is there any wrong in my code?

A: The problem here would be that you're kicking off the threads and they're not entirely finished by the time of your call to write output to the console.
The loop starts off i threads, we'll imagine these as bees going of collecting as work, not all going to the same food source so some take longer to return than others; then, back at the hive, we suddenly say: "Hey, bees, I need a headcount!", "...1, 2, 3..., only three?" No, some  i-3 are still scrounging around outside!
So, the idea is that we must have an indicator of when work is completed, or a homing signal of sorts to get all bees back to the hive for the headcount. This can be done with Join, or manual state checking (which essentially has you holding out until the last sojourner returns.)

A: You're not waiting for the threads to finish. It'e entirely a matter of luck how many have done their work before you output the count.
Add
        for (int i = 0; i < 100; i++)
        {
            threadArray[i].Join();

        }

before the WriteLine, and you always get 100.

A: You should protect your getter public int Count { get { return m_count; } } with a lock to, else a thread B could be reading that value, while another thread A is updating count in your Add method, this can cause you to get an inconsistent view of your data.

A: It's a classic race condition, and I consider you lucky to get anywhere near 100 by the time your Console.WriteLine is invoked.
for (int i = 0; i < 100; i++)
{
    threadArray[i].Start();
}
//absolutely no guarantee that **ANY** threads have completed before next line
Console.WriteLine(ope.Count);

Consider using a CountdownEvent or similar to do a bit of synchronization.

A: It is not deterministic when your call to Count happens. It may happen before any thread has finished, or after all threads have finished or even somewhere in the middle. If you want to wait until all thread have finished, you should join them.

A: Not sure that this is the answer you're looking for, but to incrememnt a counter in a threadsafe way you should use Interlocked.Increment docs

A: When you print the count you have no idea of whether or not the threads have completed or not. A "correct" output in your code could be any number between 0 and 100.
To be certain to get 100 as output, you mustn't get the value of Count until all threads have completed. You can do that by calling Thread.Join on all threads or (even better) use something like Parallel.For to start the threads:
Parallel.For(0, 100, idx => ope.Add);
// When we reach this line, we know all threads have completed so we can
// safely get the count
var count = ope.Count;


text:
Q: Handling errors on php contact form The below code is working great for handling errors for text fields in my contact form, but how do I get this same method to work for dropdown select option boxes and textareas?
<input type="text" name="name" value="<?php if($errors){echo $name;} ?>" id="name" size="30" />

For example:
<textarea name="message" value="<?php if($errors){echo $message;} ?>" id="message" rows="10" cols="40"></textarea>

does not work.

A: In the case of a textarea, you have to put the default value within the tag itself.
For example:
<textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>

A: This is how you should do the INPUT: it's like you have it, but you really should escape the user-provided content with htmlentities (or htmlspecialchars, etc.) in case they had quotes, brackets, etc. in the text that would be interpreted as HTML characters by the browser.  That's just good practice.
<input type="text" name="name" id="name" size="30"
  value="<?php if ($errors) { echo $name; } ?>" />

This is how you should do the TEXTAREA: put the content between the textarea open/close tags.  And make sure to escape it properly too.
<textarea name="message" id="message" rows="10" cols="40"
  ><?php if ($errors) { echo htmlentities($message); } ?></textarea>

This is how you might handle the SELECT tag.  I've spaced out the code for readability so you can understand what's going on.  Basically you just have to output selected="selected" in the OPTION element you want to be selected.
<select>
  <option value = "val1"
    <?php if ($error && ($selval=="val1")) { echo 'selected="selected"'; } ?>
  >
    Option Label 1
  </option>
  <option value = "val2"
    <?php if ($error && ($selval=="val2")) { echo 'selected="selected"'; } ?>
  >
    Option Label 2
  </option>
  ... (additional <option> tags here) ...
</select>

A: for the text area:
textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>

For the dropdown, you'll need to do something like this:
<select>
  <option value = "1" <? echo ($errror && $myposted_val == "1") ? "selected = \"selected\"" : ""; ?></option>
</select>


text:
Q: Is it possible to exclude multiple categories in JUnit 4? I would like to do something like:
@RunWith(Categories.class)
@Categories.IncludeCategory(Small.class)
@Categories.ExcludeCategory({Manual.class, NonFunctional.class})
@Suite.SuiteClasses(AllTests.class)
public class SmallTests {
}

but ExcludeCategories accepts only one class, not an array of classes.

A: This will be supported in JUnit 4.12 version, see https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/experimental/categories/Categories.java

A: There's a JUnit 4 feature request for this:
https://github.com/junit-team/junit/issues/146
This link also suggests a workaround:

There is a not-so-beatiful workaround. You can get multiple includes or excludes
  if you create an inheritance hierarchy of suites and exclude one category on
  each level.

A: It looks like runtime-suite may provide another workaround/solution.


text:
Q: expanding.apply in polars In pandas I could call data.expanding(min_periods=1).apply(lambda_func) to call a func on expanding or a cumsum-like view.
How to do the same thing with polars? I could only find rolling_apply or apply.

A: From polars>=0.13.36 you can run cumulative_eval to run polars expressions on a cumulative increasing window.
Note that you should not use this for an aggregation like sum as this will have O(n^2) complexity.
df = pl.DataFrame({
    "values": [1, 2, 3, 4, 5]
})

df.select([
    pl.col("values").cumulative_eval(pl.element().first() - pl.element().last() ** 2)
])

shape: (5, 1)
┌────────┐
│ values │
│ ---    │
│ f64    │
╞════════╡
│ null   │
├╌╌╌╌╌╌╌╌┤
│ -3.0   │
├╌╌╌╌╌╌╌╌┤
│ -8.0   │
├╌╌╌╌╌╌╌╌┤
│ -15.0  │
├╌╌╌╌╌╌╌╌┤
│ -24.0  │
└────────┘


text:
Q: Transforming a sql table into its inverse In SQL Server, I have the following table with State & City:
CREATE TABLE #State_City
(
    State VARCHAR(100),
    City VARCHAR(100)
)

INSERT INTO #State_City (State, City)
VALUES ('PA', 'Philadelphia'),
       ('PA', 'Pittsburgh'),
       ('NJ', 'Trenton'),
       ('NY', 'Albany')

  State    City
  ----------------------
    PA     Philadelphia
    PA     Pittsburgh
    NJ     Trenton
    NY     Albany

I want to transform it into the following output where for every State, I want to return Cities that belong to different States(other than the one in the current row) in the original table.
State   City
----------------------
PA      Trenton
PA      Albany
NJ      Philadelphia
NJ      Pittsburgh
NJ      Albany
NY      Philadelphia
NY      Pittsburgh
NY      Trenton

For example, Philadelphia & Pittsburgh belong to PA in the first original table. Trenton and Albany don't belong to PA as they belong to NJ & NY respectively. Therefore, I want to return two cities that don't belong to PA in the first two rows. Similarly, Philadelphia, Pittsburgh & Albany belong to states other than NJ and that's why I am returning cities that don't belong to NJ in the output result. Finally, I am assigning the three cities that don't belong to NY(Philadelphia, Pittsburgh & Trenton) in the first table to NY in the output result.
I was trying to use a cursor to loop through the carrier list and use dynamic SQL, NOT IN & UNION ALL to accomplish the desired output to no avail.

A: Kind of a unusual requirement if these are the actual data.
Anyway, do a SELF CROSS JOIN or INNER JOIN on the same table and check for State not match
SELECT  DISTINCT sc1.State, sc2.City
FROM    #State_City sc1
        INNER JOIN #State_City sc2  on  sc1.State   <> sc2.State
ORDER BY sc1.State, sc2.City

A:   SELECT DISTINCT
        SC2.[State],
        SC1.City
  FROM
        #State_City AS SC1
    INNER JOIN
            #State_City AS SC2 ON SC1.[State] <> SC2.[State]


text:
Q: ASP.NET параметр в button CommandArgument Хочу передать текст из LabelFrom и LabelTo как параметр в OnClick.
<asp:Label ID="LabelFrom" runat="server"></asp:Label>
<asp:Label ID="LabelTo" runat="server"></asp:Label>
<asp:Button ID="ConcatConditions" runat="server" Text="Слияние без удалением старого" CommandArgument='<%#Eval(LabelFrom.Text) + ";" +Eval(LabelTo.Text)%>' OnClick="ConcatConditions_Click" />

Значение Label задается в js:
  document.getElementById("<%= LabelFrom.ClientID %>").innerHTML = idFrom;
  document.getElementById("<%= LabelTo.ClientID %>").innerHTML = idTo;

На сервере:
 protected void ConcatConditions_Click(object sender, EventArgs e)
  {
      var btn = (Button)sender;
      var arg = btn.CommandArgument.Split(';');
  }

В CommandArgument, LabelFrom.Text, LabelTo.Text всегда пустота.
Подскажите в чем проблема!

A: Дело в том, что при отправке данных на сервер передаются только значения из полей <input> формы. Элемент <asp:Label> рендерится в тег <span>, соответственно, его значение на сервер не отправляется.
Можно передать данные на сервер в скрытом поле. Добавьте на форму <asp:HiddenField>:
<asp:HiddenField ID="LabelValues" runat="server" />

Скрипт:
document.getElementById("<%= LabelFrom.ClientID %>").innerHTML = idFrom;
document.getElementById("<%= LabelTo.ClientID %>").innerHTML = idTo;
document.getElementById("<%= LabelValues.ClientID %>").value = idFrom + ';' + idTo;

Обработчик на сервере:
protected void ConcatConditions_Click(object sender, EventArgs e)
{
    var arg = LabelValues.Value.Split(';');
}

Параметр CommandArgument вам в принципе не нужен.


text:
Q: ParameterFieldCurrentValueException when data not saved with a report and exporting to PDF I have a report that I created with Crystal Reports 2008.  This report uses upwards of 40 parameters to control the layout of the report.  All the parameters are boolean and are defaulted to False in the saved report.  The report is saved with the save data with the report option unchecked as I want to read the results from the database rather than within the report.
However, when I go to export the report to PDF I receive a ParameterFieldCurrentValueException.  I do not receive this error when the data is saved with the report.
I have verified that all five tables in the report are connected to their data source with the following code.
foreach (Table table in reportDoc.Database.Tables)
{
   bool isConnected = table.TestConnectivity();
   Console.WriteLine(table.Name + " connected? " + isConnected.ToString());
}

What might be causing the ParameterFieldCurrentValueException when data not saved with a report and it is exported to disk?
This is the simplest code that can reproduce this issue.
string report =  "list_report.rpt";
string pdf = "list_report.pdf";

ReportDocument reportDoc = new ReportDocument();
reportDoc.Load(report);

// Setting parameters (or not) does not have an effect on the error
// All parameters have defaults
// reportDoc.SetParameterValue("hideRegion", false);

reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, pdf);

A: When you have Save Data with Report selected the report does not try to hit the database. It's a static report with saved data. That's why this report doesn't error compared to when you try to pass parameters without saved data.
The error suggests that one or more of the parameter values you're passing at runtime does not match what the report is expecting. In your code you're exporting to PDF directly.  Since you're not viewing the report there's no opportunity for the engine to prompt for missing values.
You can build a simple windows application that loads your report and passes it to the Crystal Report Viewer control. Start by not passing any parameter to the report without saved data. You should be prompted for all your parameters. Add them manually in the parameter prompt form. Does this work? It should. Now start adding parameter code one at a time. The parameter prompt form should just prompt for the parameters that are missing. At some point you'll get the error again and this should help narrow down the issue.
Sincerely,
Dan Kelleher

A: This answer isn't mine, it is by a gentleman on the Crystal Reports forums. That posting can be found on the SAP Forum  The answer there was:

When you have Save Data with Report
  selected the report does not try to
  hit the database. It's a static report
  with saved data. That's why this
  report doesn't error compared to when
  you try to pass parameters.
The error suggests that one or more of
  the parameter values you're passing
  does not match what the report is
  expecting. Since you're not viewing
  the report there's no opportunity for
  the engine to prompt for missing
  values.
You can build a simple windows
  application that loads your report.
  Start by not passing any parameter to
  the report without saved data. You
  should be prompted for all your
  parameters. Add them manually in the
  parameter prompt form. Does this work?
  It should. Now start adding parameter
  code one at a time. The parameter
  prompt form should just prompt for the
  parameters that are missing. At some
  point you'll get the error again and
  this should help narrow down the
  issue.

What I then did was to load the report into a Crystal Report Viewer control.  When this loaded it prompted me for any missing parameters I had. I had missed one parameter in a list of 40+ parameters which was causing the error.  The code for that follows:
ReportDocument reportDoc = new ReportDocument();
reportDoc.Load(")list_report.rpt";
Form1.SetParameterValues(reportDoc);

this.crystalReportViewer1.ReportSource = reportDoc;

If said person replies to Stack Overflow with this answer I shall select his post as the answer in order to appropriately credit the source.

A: This one will not be easy to solve!
What about giving default values to all your parameters before saving? Do you get the same error? If no, you'll then have to try each one of them to find the one causing the trouble. I guess you'll end somewhere with a parameter value used in a formula...
PS: even if this has nothing to do with your problem, I feel confused by the use of the CR keyword 'formula' in your code.


text:
Q: How to overwrite settings for a folder I have a folder inside a workspace and I need to overwrite some settings only for that folder. How to do that ? (probably a stupid question but I've been trying for last half hour with no success)

A: You can create a .vscode/settings.json file inside that folder. These settings will overwrite your workspace settings for this folder only - cf this documentation.


text:
Q: Spring Boot vs Spring MVC (In depth) I've got the basic idea of, what both of them are and when they can be used. I've already referred to this question as well. As of now what I understood was:
Spring Boot bundles a war file with server runtime like Tomcat. This allows easy distribution and deployment of web applications. As the industry is moving towards container based deployments, Spring Boot is useful in this context.
Spring MVC is a traditional web application framework that helps you to build web applications.
What I wanted to know is that, what can be the best practice when it comes to web applications and the differences of using either one of them in depth. Any help would be appreciated.


text:
Q: Getting new parameter after Python Toolbox gets executed I am trying to build a toolbox which would first take some inputs and execute some code and return me results. After the results I would like toolbox to ask me for new parameters so I can use these results.
Here is my idea with the code
# -*- coding: utf-8 -*-

import arcpy

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Toolbox"
        self.alias = "toolbox"

        # List of tool classes associated with this toolbox
        self.tools = [Tool]

class Tool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Tool"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""

        input_folder = arcpy.Parameter(
            name='input_folder',
            displayName='Input Folder',
            datatype='DEWorkspace',
            direction='Input',
            parameterType='Required')

        params = [input_folder]

        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""

        #show me some results which i will make use.

        #execute something to get new parameter from user input and make operation.

        #and make the operation.
        return

A: In What is a Python toolbox? it says:

Python toolboxes are geoprocessing toolboxes that are created entirely
in Python. A Python toolbox and the tools contained within look, act,
and work just like toolboxes and tools created in any other way.

In Setting script tool parameters it says:

Almost all tools have parameters, and you set their values on the tool
dialog box or within a script. When the tool is executed, the
parameter values are sent to your tool's source code. Your tool reads
these values and proceeds with its work.

There is no option to interrupt the work of a tool and have new parameter values collected from the user of that tool.


text:
Q: Comparing a particular column value for two rows in SQL I have a table as follows:
ID  Version Type  Value
121    1     A     100
121    1     B     200
122    2     A     300
122    2     B     300
123    3     A     300
123    3     B     300
124    4     A     420
124    4     B     420
121    3     A     410
121    3     B     410

I am trying to build a query which gives returns the rows where "Value" is different between Type A and Type B for same ID and Version.
For example, in the above scenario, ID and Version is Unique 5 times (121-1,122-2,123-3,124-4,121-3). I would look at "Type" for each unique group and compare "Value" for Type A and Type B.
The above scenario should return:
ID  Version Type  Value
121    1     A     100
121    1     B     200

The above two rows are the only ones with different "Value" for unique ID and Version and among Type A and Type B.
Any help will be greatly appreciated :)

A: You can use exixts :
select t.*
from table t
where exists (select 1
              from table t1
              where t1.id = t.id and
                    t1.Version = t.Version and
                    t1.type <> t.type and
                    t1.Value <> t.Value
             );

A: You can join a table to itself:
SELECT *
FROM [MyTable] t0
INNER JOIN [MyTable] t1 ON t1.ID = t0.ID AND t0.Type <> t1.Type AND t0.Value <> t1.Value

or
SELECT *
FROM [MyTable] t0
INNER JOIN [MyTable] t1 ON t1.ID = t0.ID AND t1.Type = 'B' AND t0.Value <> t1.Value
WHERE t0.Type = 'A'

A: If you have only two types, I am going to recommend a different result set format:
select id, version,
       max(case when type = 'A' then value end) as value_a,
       max(case when type = 'B' then value end) as value_b
from t
where type in ('A', 'B')
group by id, version,
having max(case when type = 'A' then value end) <> max(case when type = 'B' then value end);

I recommend this because a typical follow-on question might be "how big is the difference".

A: This is one way to approach this problem:
select *
from t1
where (id, value, version) in (select id, value, version
                      from t1
                      group by id, value, version
                      having count(id) = 1);

Here is a DEMO

A: This is what I ended up doing:
SELECT MAX(Value), MIN(Value)
FROM table_name
GROUP BY ID, Version
HAVING MAX(Value)<>MIN(Value);


text:
Q: Spring MVC REST + Spring Security + Basic Authentication Environment :
Spring 4.1
Spring security 4.0
Issue :
I am developing a simple REST service using Spring 4.1. And using Spring security for authentication purpose.
I am using HTTP Basic Authentication.
The issue is , basic authentication is not working even after all configuration is correct.
I am using postman to send a request to server.
REST client can call the REST controller method without Authorization header.
The method gets executed successfully without any authentication error.
Since I am using Tomcat 6 , I am not using servlet 3.0 features , so web.xml does exist.
The method level security has been implemented using @Secured annotation on REST controller layer.
Can anybody please help as to where I am going wrong ?
Code :
web.xml :
<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet-security.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

</web-app>

mvc-servlet-dispatcher-security.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-4.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

    <http use-expressions="true" create-session="stateless">
        <http-basic/>
       <csrf disabled="true"/>
    </http>

    <global-method-security secured-annotations="enabled"/>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="XYZ" password="12345" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

mvc-dispatcher-servlet.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Specifying base package of the Components like Controller, Service, DAO -->
    <context:component-scan base-package="org.ngo" />
    <!-- Getting Database properties -->
    <context:property-placeholder location="classpath:application.properties"/>

    <mvc:annotation-driven/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="org.ngo.abhishek.entity"></property>
    </bean>

    <!-- Transaction -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

The REST controller :
@RestController
@RequestMapping("/abhishek")
public class AbhishekController {

    @Autowired
    private AbhisheskService abhishekService;

    @RequestMapping(method=RequestMethod.POST,consumes="application/json")
    @Secured("ROLE_USER")
    public ResponseEntity<Boolean> getUserById(@RequestBody List<AbhishekDTO> abhishekDtoList) {

        boolean flag = this.abhishekService.createAbhishek(abhishekDtoList);
        return new ResponseEntity<Boolean>(flag, HttpStatus.OK);
    }

}

A: I tried your setup and it worked for me. Since you did not provide all of your code, my best guess is either the component scan of your controller for Spring Security is not happening or maybe your browser is caching and sending the Basic Auth credentials without you realizing it.

A: After getting a clue from Stiletto , I removed @Secured("ROLE_USER") and used  expression based security check. It worked (using intercept url). So the issue was with where @Secured has been placed.
Since @Secured was in dispatcher servlet  context (child context as per Spring philosophy) and spring security scope was in applicationContext (parent context) , the spring security was getting ignored.
Putting <security:global-method-security secured-annotations="enabled"/> in mvc-dispatcher-servlet.xml resolved the issue.
Similar question on SO : Spring MVC, Method level security


text:
Q: How to combine two selection with 1 option I have a select option(drop down) on my hmtl. I want to post this to database. Normally if I will select "Selection1" the value="3" will be selected and if I select "Selection2" the value="4" will be selected.
Now, I want that if I select "Selection1&2" the value="3" and value="4" will be selected or post to database.
Any ideas or suggestions on how to do that?
<select class="form-control" id='Selection'>
    <option value="3">Selection1</option>
    <option value="4">Selection2</option>
    <option value="5">Selection1&2</option>
</select>

Thank you

A: Use attribute multiple and set name of your select using []:
<select class="form-control" id='Selection' name="myselect[]" multiple>
    <option value="3">Selection1</option>
    <option value="4">Selection2</option>

</select>

Printing value of myselect on server:
print_r($_POST['myselect']);

you will see that you have an array with selected values.

A: If your third option acts as Select all option use Bootstrap frame work for select all functionality and for also better look and feel.

        <select id="Selection" class="multiselect-ui form-control" multiple="multiple">
            <option value="3">Selection1</option>
            <option value="4">Selection2</option>

        </select>

"Select All" will act as your third option