text:
Q: How to get a random item from a list with some preference I want to randomly select an item from a list with some sort of preference that will increase the probability of some items to be picked over others in Java. I have done the normal random selection but now I want to include this. I was thinking of increasing the number of a particular item, like duplicating it multiple times in the list, but I don't feel it's the right way to go.
My other idea might involve a 2 dimensional array, so maybe apples will have an integer point of 6, then orange will have a point of 3. This way apples will have more preference than orange. I'm just suggesting, I don't even know how to use multidimensional arrays.
Any ideas are welcome.

A: Assuming the by preference you mean setting some itmes to get selected more number of times in several runs.
lets say you have items 0,1,2,3,4,5,6,7,8,9
do grouping like
group 1(preference 2 - low preference)  0,1,2,3,4,5,6,7,8,9
group 2(preference 1 - medium preference) 0,1,2,3,4,5,6
group 3(preference 0 - high preference) 0,1,2,3
now first select the random group (1,2,3) then select the item in the group.
as you see high preference 0,1,2,3 has more chances then medium and low.


text:
Q: tkinter seems to have changed its default style for showing selected text I've just rebuilt my linux desktop, now Mint 20.1 Mate. I have python 3.8.5, and Tk 8.6. Unfortunately I don't know for certain what version of Tk I was using last week, I'm sure it's been 8.6 for a long time, but was using Mint 20.1 xcfe with python 3.8.5. Tk was installed via apt install python3-tk
Programs using the Tk GUI, with text widgets like Entry and Text, for the last decade until last week, used to show selected text with a clearly contrasting highlight, just using the default settings. I'm not sure whether it was identical to that used by Mint, but it didn't cause any surprise.
Now I've rebuilt, the selection highlighting is more or less invisible. I can tell it's been highlighted if I look very carefully (a very light grey), but it's now a pain to use. I can make it more visible by altering the background to something contrasting like green or orange, which is not very aesthetically satisfactory.
How can I change Tk's defaults back again? How can I find out what they should be? Does it have user accessible defaults?
Looking over the docs, I can find that there are options to change most things, except for text selection highlight.
It's probably telling me I ought to progress to ttk and styles. But that's a bit to learn, and a lot of programs to change.

A: tkinter uses what it calls an option database for its defaults. Different platforms will define this database differently. It could be that your OS changed it, or your specific desktop environment caused it to change.
The text selection is controlled by the selectbackground and selectforeground options. For every option there is a corresponding value in the option database. There are also values for each widget class, so you could set one value for text widgets and a different value for entry widgets.
For selectbackground the name in the option database is selectBackground. You can change the value in the database with the option_set method. Any widgets created after this value has been set will use the new value.
For example, if you want to set the Entry selection background to pink, you could do something like this:
import tkinter as tk

root = tk.Tk()
root.option_add("*Entry.selectBackground", "pink")

Any Entry widget created after that line of code will have pink as the default for the selection background. To change it for all widgets, you can just remove Entry.:
root.option_add("*selectBackground", "pink")

The option database is a bit arcane. It has its roots in the way widget options were specified back when tk only worked on X11-based systems. It's very powerful, but not particularly intuitive.
The most detailed online documentation that I know of is a document titled Options and Tk - A Beginner's Guide. It is written from the perspective of tcl/tk rather than python/tkinter, but the concepts are identical. The Tkinter Life Preserver in the python docs can help with the translation to python.

A: After some searching, I came across this command
root.tk_setPalette(background='#40E0D0', foreground='black', etc, ...

It changes all the existing widgets across the application, and sets the defaults for new ones. According to this page it can set the following options ...
foreground / background
activeForeground / activeBackground
selectForeground / selectBackground
highlightColor / highlightBackground
disabledForeground
insertBackground
troughColor
selectColor
Most of those did what I would expect. However insertBackground seems to control the colour of the insert cursor only, and selectColor the background of CheckButtons. The highlightColor and highlightBackground control the outline of widgets with and without focus respectively.

redpajama_set_name: RedPajamaStackExchange


text: Q: Send trigger email when someone connects to a database How do I set up a trigger or alert so that when anyone connects to a specific database, an email will get send with that user's login credentials?


text:
Q: Using different mysql users within same class while maintaining same connection? I'm in a situation where I need to use MYSQL's LAST_INSERT_ID(), which is obviously only possible when maintaining the same connection. But as I was thinking about the way I establish my PDO connections, it occurred to me that I am probably going to run into problems.
I've got a database class with various types of connections. Inside this class, I've created different PDO connection methods based on user permissions which I call inside the PDO query methods like so...
class dbFunctions {

    private $userSelect = "userSelect";
    private $passSelect = "XXXXX";
    private $userDelete = "userDelete";
    private $passDelete = "XXXXX";

    protected function connectSelect() {
        $dsn = $this->dsn();
        $this->pdo = new PDO($dsn, $this->userSelect, $this->passSelect, $this->options);

        return $this->pdo;
    }

    protected function connectDelete() {
        $dsn = $this->dsn();
        $this->pdo = new PDO($dsn, $this->userDelete, $this->passDelete, $this->options);

        return $this->pdo;
    }

    public function selectCount($query, $values = []) {

        $result = $this->connectSelect()->prepare($query);
        $result->execute($values);
        $exec = $result->fetch();

        $count = (int)$exec['total'];

        return $count;
    }
}

My questions are...

*

*Am I better off creating one global connection object with the same account/password for all queries? I did it this way for security purposes but I believe it may have drawbacks.

*Even though these are different PDO connection objects, is PHP able to determine they are part of the same session within the same script? In which case the separate methods will be ok.

*How can I keep separate mysql users with my current class?

Obviously I can test this on my own, but I'm unsure what the results will be when I get multiple users accessing the site.

A: The best is to have only one DB connection per page. Maybe by using a singleton.
First for performance, because a connection have a cost.
In my opinion, there isn't any security issue.

A: *

*Am I better off creating one global connection object with the same account/password for all queries? I did it this way for security purposes but I believe it may have drawbacks.

I'm no security expert. I think that if I can manage mysql users and permissions in a way that only some human accounts can delete stuff, that's some kind of security. I also think this has many complex ramifications. On the other hand, people can update to a blank string if need be...

*

*Even though these are different PDO connection objects, is PHP able to determine they are part of the same session within the same script? In which case the separate methods will be ok.

PHP objects do not seem to be persistent. We can serialize them and use __sleep() to manage their storage.

It [sleep] can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized.

this part might interest you:

The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

*

*How can I keep separate mysql users with my current class?

With the same pattern, but make sure not to create pdo instances for each select or delete query. I tweaked it a bit to reuse the same function for both connections. Adding more is as easy as... naming new class members.
class dbFunctions {

    // other members

    // add these
    private $instanceSelect = null; // they default to null anyway
    private $instanceDelete = null;
    private $instanceFoosball = null;

    protected function connect($what) {
        if ($this->{"instance".$what} === null) { // true the first time
            $this->{"instance".$what} = new PDO($this->dsn(), $this->{"user".$what}, $this->{"pass".$what}, $this->options);
        }
        return $this->{"instance".$what}; // always reused
    }

    public function selectCount($query, $values = []) {}
}

$result = $this->connect('Select')->prepare($query);
$result = $this->connect('Foosball')->prepare($query);


text:
Q: SQL Time Conversion I am having trouble with a conversion of time.
I have a table called 'TotalTime' which is set to INT and holds the time in seconds only. I want to convert these seconds to days, hours, minutes, seconds e.g. 01d 09:26:43.
Now I will show you the code I am using:
SELECT [BuildID],[Product],[Program],

SUM(CASE WHEN [State] = 'Running' THEN cast(TotalTime as INT) ELSE 0 END) AS [Running],
SUM(CASE WHEN [State] = 'Break' THEN cast(TotalTime as INT) ELSE 0 END) AS [Break]

FROM [line_log].[dbo].[Line1Log]

GROUP BY [BuildID], [Product], [Program]

So as you can see I am grouping the [State] column and would like to display the results of 'TotalTime' in the format I mentioned above.
Now I have tried this code but it will not work as I cannot convert INT to VARCHAR
SELECT [BuildID],[Product],[Program],

SUM(CASE WHEN [State] = 'Running' THEN CAST(FLOOR(TotalTime / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(5), DATEADD(SECOND, TotalTime, '19000101'), 8) ELSE 0 END) AS [Running]

FROM [line_log].[dbo].[Line1Log]

GROUP BY [BuildID], [Product], [Program]

The above would not display it in the exact format I wanted either.
Just wondering if someone would be willing to help me on this one?
Thanks for taking the time to read this :)

A: You should convert calculated seconds after summing and grouping:
And use VARCHAR(8) instead of VARCHAR(5).
SELECT [BuildID],[Product],[Program],
    CAST(FLOOR([Running] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Running], '19000101'), 8) AS [Running],
    CAST(FLOOR([Break] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Break], '19000101'), 8) AS [Break]
FROM (
    SELECT [BuildID],[Product],[Program],
        SUM(CASE WHEN [State] = 'Running' THEN cast(TotalTime as INT) ELSE 0 END) AS [Running],
        SUM(CASE WHEN [State] = 'Break' THEN cast(TotalTime as INT) ELSE 0 END) AS [Break]
    FROM [line_log].[dbo].[Line1Log]
    GROUP BY [BuildID], [Product], [Program]
) T


text:
Q: Labels and Buttons in Tkinter Menu I created with Tkinter a Menubutton with an image. And I added in the Menubutton a label and two buttons.When I run my application, it works fine until I click two times the Menubutton. It starts to lag and it crashes.
Here is my code :
from Tkinter import *
from PIL import ImageTk

def donothing():
    print("NOTHING")

root = Tk()
root.geometry("300x300")

Menu_Photo = Menubutton(root)
Photo = ImageTk.PhotoImage(file="image.png")
Menu_Photo.config(image=Photo)
Menu_Photo.image = Photo
Menu_Photo.menu = Menu(Menu_Photo, tearoff=0, relief=FLAT)
Menu_Photo["menu"] = Menu_Photo.menu
Menu_Photo.menu.label = Label(Menu_Photo.menu, text="Menu")
Menu_Photo.menu.Settings = Button(Menu_Photo.menu, text="Settings", relief=FLAT, command=donothing)
Menu_Photo.menu.Sign_Out = Button(Menu_Photo.menu, text="Sign Out", relief=FLAT, command=donothing)
Menu_Photo.menu.label.pack()
Menu_Photo.menu.Settings.pack(fill=BOTH)
Menu_Photo.menu.Sign_Out.pack(fill=BOTH)
Menu_Photo.pack(side=RIGHT, anchor=N)

root.mainloop()

I really don't understand what is the problem ?
This is what happens for me :

The menu opens and closes every second.


text:
Q: Chisel testing error in sodor/ rocket core ALU I am trying to customize and use the ALU source file of Sodor processor/Rocket core in a different project using chisel3. Running sbt test gives me the following error.
[info] - should carry out proper arithmatic and logical operations (with verilator) *** FAILED ***

[info]   chisel3.core.Binding$BindingException: 'this' (chisel3.core.UInt@7): Missing IO() wrapper

[info]   at chisel3.core.Binding$.checkSynthesizable(Binding.scala:185)

[info]   at chisel3.core.Bits.do_apply(Bits.scala:97)

[info]   at chisel3.core.Bits.do_apply(Bits.scala:109)

[info]   at RiscvIoT.ALU$.isSub(alu.scala:44)

[info]   at RiscvIoT.ALU.<init>(alu.scala:68)

[info]   at RiscvIoT.ALUTester$$anonfun$2$$anonfun$apply$1$$anonfun$apply$mcV$sp$1.apply(aluTest.scala:41)

[info]   at RiscvIoT.ALUTester$$anonfun$2$$anonfun$apply$1$$anonfun$apply$mcV$sp$1.apply(aluTest.scala:41)

[info]   at chisel3.core.Module$.do_apply(Module.scala:29)

[info]   at chisel3.Driver$$anonfun$elaborate$1.apply(Driver.scala:191)

[info]   at chisel3.Driver$$anonfun$elaborate$1.apply(Driver.scala:191)

Following the guide on chisel 3 wiki on testing and debugging I believe that the initial error is at the line 44 (isSub function definition). But I can't figure out the problem and nothing I did solves the problem. I am posting my complete source file below for convenience.
import chisel3._
import chisel3.util._
import Common._

object ALU
{
  val SZ_ALU_FN = 4
  val ALU_X    = Bits(0)
  val ALU_ADD  = Bits(0)
  val ALU_SLL  = Bits(1)
  val ALU_XOR  = Bits(4)
  val ALU_OR   = Bits(6)
  val ALU_AND  = Bits(7)
  val ALU_SRL  = Bits(5)
  val ALU_SUB  = Bits(10)
  val ALU_SRA  = Bits(11)
  val ALU_SLT  = Bits(12)
  val ALU_SLTU = Bits(14)
  val ALU_COPY1= Bits(8)

  def isMulFN(fn: Bits, cmp: Bits) = fn(1,0) === cmp(1,0)
  def isSub(cmd: Bits) = cmd(3)
  def isSLTU(cmd: Bits) = cmd(0)
}
import ALU._

class ALUIO extends Bundle {
  val xprlen = 32
  val fn = Bits(INPUT, SZ_ALU_FN)
  val in2 = UInt(INPUT, xprlen)
  val in1 = UInt(INPUT, xprlen)
  val out = UInt(OUTPUT, xprlen)
  val adder_out = UInt(OUTPUT, xprlen)
}

class ALU extends Module
{
  val io = new ALUIO
  val xprlen = 32
  val msb = xprlen-1

  // ADD, SUB
  val sum = io.in1 + Mux(isSub(io.fn), -io.in2, io.in2)

  // SLT, SLTU
  val less  = Mux(io.in1(msb) === io.in2(msb), sum(msb),
              Mux(isSLTU(io.fn), io.in2(msb), io.in1(msb)))

  // SLL, SRL, SRA
  val shamt = io.in2(4,0).toUInt
  val shin_r = io.in1(31,0)
  val shin = Mux(io.fn === ALU_SRL  || io.fn === ALU_SRA, shin_r, Reverse(shin_r))
  val shout_r = (Cat(isSub(io.fn) & shin(msb), shin).toSInt >> shamt)(msb,0)
  val shout_l = Reverse(shout_r)

  val bitwise_logic =
    Mux(io.fn === ALU_AND, io.in1 & io.in2,
    Mux(io.fn === ALU_OR,  io.in1 | io.in2,
    Mux(io.fn === ALU_XOR, io.in1 ^ io.in2,
                       io.in1))) // ALU_COPY1

//  val out64 =
  val out_xpr_length =
    Mux(io.fn === ALU_ADD || io.fn === ALU_SUB,  sum,
    Mux(io.fn === ALU_SLT || io.fn === ALU_SLTU, less,
    Mux(io.fn === ALU_SRL || io.fn === ALU_SRA,  shout_r,
    Mux(io.fn === ALU_SLL,                       shout_l,
    bitwise_logic))))

  io.out := out_xpr_length(31,0).toUInt
  io.adder_out := sum
}

A: The exception thrown:  chisel3.core.Binding$BindingException: 'this' (chisel3.core.UInt@7): Missing IO() wrapper is due to the fact that in chisel3, io must be wrapped in IO(...)
It is perhaps a little hidden in the documentation (see https://github.com/ucb-bar/chisel3/wiki/Chisel3-vs-Chisel2#deprecated-usage)
To fix, change the io declaration in ALU to:
val io = IO(new ALUIO)

You should also change the ALUIO to:
class ALUIO extends Bundle {
  val xprlen = 32
  val fn = Input(Bits(SZ_ALU_FN.W))
  val in2 = Input(UInt(xprlen.W))
  val in1 = Input(UInt(xprlen.W))
  val out = Output(UInt(xprlen.W))
  val adder_out = Output(UInt(xprlen.W))
}

Although I believe the old way is deprecated rather than an error.


text:
Q: Socket connect timeouts differ between networks I have a rather interesting problem. We have 2 networks at work that are physical duplicates of each other (network A and network B). They just run on different subnets.
I am working on some fault tolerance improvements for our devices that cluster with each other on the network. One of the test cases that I am exercising is the behaviour of these devices when a misconfiguration is introduced. For example, lets say I have two devices with the following interface configurations:
Device X
IP: 10.200.234.127
Subnet Mask: 255.255.254.0
Default Gateway: 10.200.234.1
Device Y
IP: 10.200.234.127
Subnet Mask: 255.255.254.0
Default Gateway: 10.200.234.1
These 2 devices discover each other via the broadcast of cluster heartbeats. The heartbeats contain the devices ip address, etc which allows them to then establish communication with each other. Pretty standard stuff. Now, lets say I introduce a network misconfiguration such that one of these devices is configured for a different sunbet:
Device X
IP: 192.168.1.115
Subnet Mask: 255.255.255.0
Default Gateway: 192.168.1.1
What happens here is that both devices still learn about each other from the cluster broadcasts (they are physically connected together on the same switch). However, as you would expect, they cannot communicate with each other as expected. However, I am seeing some strange behaviour with respect to connect timeouts when these devices attempt to communicate with each other. For example, if the devices are connected on network A, the connection attempts timeout within a few seconds which is great. Now, if I place both devices on network B I see a completely different behaviour. On network B, the connect() calls to establish socket connections between the devices do not fail quickly. Rather, they fall into this backoff and retransmit cycle that takes 189 seconds to finally give up ( retransmits at 3, 6, 12, 24, 48, and 96 seconds as verified with wireshark).
So what I am wondering is, why does the connect() call fail so rapidly in network A and not in network B. I have tried using blocking sockets and a call to connect() as well as non-blocking sockets and a call to connect() followed by a call to select(). In both cases I cannot get the connect to give up any sooner than 189 seconds. I know that I can impose a shorter timeout in the call to select and give up much sooner but that is not the point here. I am trying to understand what could possibly be different on these 2 networks that is causing this issue.

A: Maybe you should give more addresses? It's not clear exactly what the IPs are.
My guess is that:

*

*In the slow case you're getting ARP failures (no response because target has incorrect netmask)

*In the fast case you're getting a routing failure. If the host has an incorrect smaller netmask it won't even attempt ARPs.

Please try to strace blocking sockets, error code should be different.


text:
Q: Azure Functions: A few http requests throws socket exception I have a Azure function that is doing HTTP calls to another Azure Function endpoint, both are running in the consumption plan. The HTTP Client is setup via HttpClientFactory. In 99 of 100 times the call gets through successfully, but there are a few requests that throws the SocketException with the error message "Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request.."
Stack trace:
System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Int32>.GetResult(Int16 token)
   at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](TIOAdapter adapter)
   at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory`1 buffer)
   at System.Net.Http.HttpConnection.InitialFillAsync(Boolean async)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

This is how the client that does the request look like:
public class ReadClient : BaseClient, IRClient
{
    private HttpClient Client { get; }

    public ReadClient(IConfiguration config, IHttpClientFactory httpClientFactory) : base(config)
    {
        Client = httpClientFactory.CreateClient(nameof(ReadClient));
    }

    public async Task<TResponse> Get<TResponse>(string url)
    {
        var authenticationToken = GetAuthenticationToken();
        Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authenticationToken.Type, authenticationToken.Token);
        var response = await Client.GetAsync(url);
        return ProccessResponse<TResponse>(response);
    }
}

My first thought was that perhaps there were too many requests coming in at the same time and that the function didn't have time to scale up with a new instance, but these occurs randomly at times when there aren't that much traffic. Do you have any idea on how to investigate why these errors occurs?

A: The problem is because you're not reusing HttpClient properly and it's leading to port exaustion.
This is not an azure function but http client issue and you can read more about it in here:
https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
To solve it when using Azure Functions, please check the following:
https://learn.microsoft.com/en-us/azure/azure-functions/manage-connections?tabs=csharp#http-requests
https://learn.microsoft.com/en-us/azure/azure-functions/errors-diagnostics/sdk-rules/azf0002


text:
Q: Wait for JavaFX Application Thread to finish handling events? Lots of questions on here are asking about how to pause the JavaFX Application thread for a background thread, but I want the opposite!
I'm trying to test how long it takes for a series of key inputs to be fully handled. I am using the Automaton testing library for JavaFX, and editor.type(key) generates a keypress event that gets processed by the application. Here is one of many attempts:
long start = System.nanoTime();

editor.type(AGUtils.LEFT_ARROW);
editor.type(AGUtils.LEFT_ARROW);
editor.type(AGUtils.RIGHT_ARROW);
editor.type(AGUtils.RIGHT_ARROW);

FutureTask<Callable> t = new FutureTask<>(...);
Platform.runLater(t);

while (!t.isDone()) { } // wait for the FutureTask to be called

long end = System.nanoTime();

However, it seems the FX Application Thread might be handling the FutureTask before it handles the rest of the keypress events.
TLDR: I want to precisely measure when the JavaFX Application Thread has finished handling the four keypress events I generate.
How can I go about this? Thank you!

A: Use  ExecutorService and wait until your threads are done. Store a timestamp of when you started the service and then compare the difference between the two times to get your answer.
A simple example on how to use the ExecutorService:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}


text:
Q: Spring MVC + Security testing with CSRF I know that the question already exists on topic, but still not working for me. I'm using Spring 4 MVC / Security stack with CSRF protection enabled. I follow the spring blog http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html, but still getting the 403 forbidden code.
Here is the setup of my test;
@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setUp() {
    this.mockMvc = MockMvcBuilders
            .webAppContextSetup(this.wac)
            .apply(springSecurity())
            .build();
}

The method to test is a post method dealing with a formBean, here is how i perform the test method request;
this.mockMvc.perform(
    post("/uploadFile")
    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
    .with(user("user").authorities(authorities))
    .with(csrf())
    .flashAttr("filesUploadForm",filesUploadForm)
)
.andExpect(status().isOk())
.andExpect(view().name(FileController.VIEW_SHOW_FILES));

i set a user with the RequestPostProcessor, with specific authorities;
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
authorities.add(new SimpleGrantedAuthority("PERM_UPLOAD_FILE"));

Because my method controller is as follow;
@PreAuthorize("hasAuthority('PERM_UPLOAD_FILE')")
@RequestMapping(value = ROUTE_UPLOAD_FILE, method = RequestMethod.POST)
public ModelAndView uploadFile(Model model,
        @Valid @ModelAttribute("filesUploadForm") FilesUploadForm       filesUploadForm,
        BindingResult result,
        HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) {
...

This is working like a charm when all security is up EXCEPT CSRF (csrf disable=true). When i enable CSRF protection, even if i'm using the .SecurityMockMvcRequestPostProcessors.csrf(), i'm still getting a java.lang.AssertionError: Status expected:<200> but was:<403>.
I also try to explicitly inject the token as param, nothing changed.
I'm quite lost, Thanks a lot for your help guyz!
Phackt.


text:
Q: Upnp specifications Hi there i have written a media service that currently supports nfs and was now thinking about adding support for upnp but i don't know where to start is there any rfc or some thing i could read up on as the rfc for nfs where super helpful..
and just to clarify i want to implement it on my own or if there is a pure .net library out there that would also work.
I have no idea where to start?
Edit: i found a few documents Here is there any other source of information out there?

A: You could start at http://www.upnp.org/ and http://upnp.org/sdcps-and-certification/standards/sdcps/ and also http://msdn.microsoft.com/en-us/library/aa382303(v=VS.85).aspx

A: You can also look at the source code for Coherence (http://coherence.beebits.net/) or ps3mediaserver (http://code.google.com/p/ps3mediaserver/) to get a good idea of how it is implemented.

A: You may also find the following links helpful:

*

*A open-source media server - http://mediatomb.cc/pages/download

*libupnp - Linux SDK for upnp devices - http://upnp.sourceforge.net/
I would also recommend the book UPnP Design By Example


text:
Q: Library to create videos from pictures and text? Is there some library to generate a video from pictures and text? Something like animoto.com does but much simplier.
I basically want to set one picture, and fade in and out text over that picture and make a video out of that.
I am looking for something to run from php or python, video format is not so important.

A: Would you consider an animated GIF to be a video?  If so use imagemagick!

A: There is a pyffmpeg module at http://code.google.com/p/pyffmpeg/ which ought to be able to do this; I'll see if I can bash together an example.
Edit: ok, I take it back. It doesn't look like pyffmpeg is being actively maintained, and I've just about had an aneurysm trying to get the son-of-a-gun to build on Windows (there's a binary download for 2.6, but none for 2.7). Apparently the preferred method is to cross-compile it from Ubuntu (?!) It may be fine if you're on Linux, but on Windows I'm throwing in the towel.


text:
Q: Is there a way to automate the creation of a file needed by a container in VS Code Remote-Containers before it runs? This relates specifically to Remote-Containers with VS Code using a docker-compose file to define the services. One of those services in this case is MariaDB which takes an environment variable to specify the location of a file which contains the password for the DB user. The file must exist when the container starts or it will throw an error which could be difficult for a novice to diagnose. There is a default value which the file can contain but if I commit it to the public repository developers can no longer change it locally without the risk of the change being committed. When a developer builds a local environment from the repository, it's okay to use the default value and they shouldn't be required to create files in special locations before opening the container.
According to the documentation, inside devcontainer.json there is a property called initializeCommand which seems like it would be the place to run some code to copy a default file to the right location, but the developer could be running VS Code in Mac or on Windows. Is there a cross-platform way of making sure the environment is prepared before it gets launched? I want this automated so developers don't have to remember or know to do this before getting started.
Basically, it should automatically test if secrets/sql-password.txt exists and copy secrets/sql-default-password.txt there only if the file is missing.
Any suggestions?


text:
Q: reference the script tag that loaded the currently-executing script in an ajax form Following code run fine in a non-ajax environment.

If I then reload the div 'target' with the same content using Ajax, $('script').filter(':last') references the last script of the page and not the current one anymore.

 // reloaded using Ajax

It's like the current script is inserted where the old one was (I'm guessing) though is correctly executed on load time.
How could I have the requested behavior on an Ajax environment ?

A: Here's what i think is happening. When you're not performing an ajax request, this script runs first

And at the time this line is executed var thisScript1 = $('script').filter(':last'); the only script is the script in the div target hence the selector picks it up. But when performing an ajax request, the content is reloaded.

 // reloaded using Ajax

So when this line is executed var thisScript1 = $('script').filter(':last'); there's more than one script in the document. Hence you really need to select the first script here and not the last one.
You should use the :first to select the first script and :last to get the second script. So changing it around should work in both environments.

Or like frederic suggested, give them id's to uniquely identify them, then use those id's to select those scripts.


text:
Q: Convert paged columns to rows with a regular expressions So first a sample of the actual data mangled (data is originally a mix of text and numbers, there's no significance to any of the data at this point and some of the patterns are just because I replaced most of the characters with 0s, 1s and Zs because the random number generator in my brain is broken):
011.0ZN1ZZ                 001.F5ZS1Z                 001.ZO5ZY0
014.5ZZZ1Z                 001.1SZZOZ                 001.ZLMZY0
016.01NM1SU54              001.EX0Z1Z                 001.LIZZOZ
018.01NM1SS41              001.F83Z1Z                 001.0011M1SU54
014.ZZ1YZZ                 001.ZZZ1IZ                 001.0011M1SS41
013.2EBSIZ                 001.ZZZ11Z                 001.0011SE4

01N.ZINSIZ                 001.ZZZZ1Z                 P01.ZZZZ1Z
01N.01NSE4                 001.LSZZHG                 N01.ZZZZ1Z
001.01ON5O                 001.5Z21OL                 F01.ZZZZ1Z
001.NE5ZO1                 001.ZOM05O                 D01.ZZZZ1Z
001.ZO5ZOZ                 001.01NO1G                 Z01.ZZZZ1Z
001.ZO5ZOZ                 001.01NO1G                 Z01.ZZZZ1Z

001.011ZOZ                 001.01NZ0Y

Some additional comments.. I can clean up whitespace and deal with record length with no issues, so I'd like to simplify the question to this, I'm just including the above in case there's a solution to the simplified version that can't be easily extended to a more complex version.
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17
6 12 18

19 25
20 26
21 27
22 28
23 29
24

So there will be a variable number of pages, but the same number of columns and rows on each page (although, in case it matters significantly, it's actually 12x3 instead of 6x3 but I wanted to keep it simple if possible), although the last page may be some empty rows/columns.
I'm using notepad++ but I have access to various gnutilities so if there's a solution that's way, way better than a regular expression I don't mind, although since I'll be using this a lot and use notepad++ a lot I'd appreciate a regex solution if it isn't too insane.

A: If you've got Git installed on your Windows machine, you may use Perl bundled with it from Git bash. Provided your input file is named data, try the following command (caution: it will orverwrite the input file):
echo >>data ; \
perl -i -lane'
    $i=0;
    push @{$c[$i++]}, $_ foreach @F;
    if (/^\s*$/) {
        push @l, @{$_} foreach @c;
        print "@l\015";
        @l=@c=();
    }' data

The Perl command treats each line of input as space delimited fields and accumulates the fields in the @c matrix. When encounters an empty line (if (/^\s*$/) ...), it prints the matrix columns concatenated in a list.
The input file is changed in-place. A backup copy data.bak is created.
The input file may not end with an empty line so I add one with echo >>data. This makes the Perl script shorter and easier.
Another trick is the trailing \015 in print "@l\015";. This allows us to get Windows CRLF line endings in Unix-flavoured Git bash environment.
A demo can be found here: https://ideone.com/vnYoOd. But since Ideone forbids file read/write, the original command has been modified to make the code run there.


text:
Q: Yii Framework CDetailView "No set" label When there is no any data in one column the words "No set" are displayed, i want to change this message but i don't know where o how to do it, i have try extending CDetailView but it didn't work, any sggestion?

A: Instead of using
array(
  'attributeName1',
  'attributeName2',
)

when defining the data to display in your detail view, use
array(
  array(
    'label'=>'Whatever you want',
    'value'=>null===$model->attributeName1?
      "custom message":
      $model->attributeName1,
  ),
  'attributeName2',
)

This gives you the power to format the content however you want it.


text:
Q: Can i create a url like google mail in cake php? Hi The master CakePHP! I want to ask something.
I think the probem is so simple, Is it possible to generate a url in cakephp application like this? (This is google mail like url - http://mail.google.com/a/domain.com)
http://www.domain.com/a/[something]/[member]/[controller]/[action]

Where [something] is a dynamic variable, [member] is a prefix, [controller] and [action] is usual cakephp url element.
so I want to shift the usual CakePHP url to the right, or insert /a/something/ in the initial url.
In addition, [something] should be read from the controller action
thanks, your help would be very valuable to me and will really help me
QUESTION v2:
I have tried to add this routing into routes.php
Router::connect('/:code/:something/:controller/:action',
    array(),
    array('code'=>'a','pass'=>array('something'))
);

when i try to access a http://domain.local/a/pte/users/view, it's work, but it display an error when i try to access http://domain.local/a/pte/users
QUESTION v3:
So the simple question is:

How do I have a url like google (example above) without breaking the
  default CakePHP routing?

QUESTION v4: (Thank's for @Rui)
I tried to create this routing:
Router::connect('/:code/:something/:prefix/:controller/*',
    array(),
    array('code'=>'a','pass'=>array('something'))
);

It's ok when i try to access
http://domain.local/a/pte/member/users (The result is cake render member_index view, It's a great progress :-) ),
but there are several issue:

*

*when i try to access http://domain.local/a/pte/users (without prefix member, i decided to display index function) it's failed (display an error AController did not defined)

*When i create a link
echo $html->link('test link',array('code'=>'a','something'=>'pte','member'=>true,'controller'=>'users','action'=>'another_view'));
it generate a link like this
http://domain.local/member/users/another_view/code:a/something:pte

A: Please try in /app/config/routes.php:
<?php
   Router::connect('/a/:something/:member/:controller/:action/*');
?>

And the action should be:
<?php
    public function action($something = null, $member = null) {
    /* action code */
    }
?>

Hope it helps.


text:
Q: Eliminate immediate array values using Javascript I'm working on project where I have array simmilar to this
var sortBp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];

I want to eliminate any immediate numbers array & only show higher number between them
for example, from above array width767px & width768px are immediate numbers array.
I want to eliminate width767px & keeping width768px as it is higher number.
So final result will be
var sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px' ];

Is that possible with pure javascript function ??
EDIT :
I have sorted array using follwoing function but I'm not clear how to remove immediate array.
  var sortBp = bpArrays.sort(function(a, b) {
                    a = a.replace(/[a-z]/g, '');
                    b = b.replace(/[a-z]/g, '');
                    return a - b;
                });

A: Of course it's possible. Just sort the array, then iterate through and collect first and last "apperance" of each attribute.

A: You can do something like
var sortBp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];
var x = [];
var regex = /\d+/;
for(var i = 0; i < sortBp.length; i++){
    var c = sortBp[i], n = sortBp[i + 1];

    if(c && n && c.substring(0, 3) == n.substring(0, 3)){
        var cn = regex.exec(c)[0];
        var nn = regex.exec(n)[0];
        if(cn != nn - 1){
            x.push(c);
        }
    } else {
        x.push(c);
    }
}

console.log(x);

Demo: Fiddle

A: Try this:
var sortBp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];
var arr=[];
for(var i=0;i<sortBp.length;i++)
{
    num=sortBp[i].replace(/\D/g,'');
    arr.push(num);
}
var newarr=[];
for(var i=0;i<arr.length;i++)
{
    if(arr[i+1] && arr[i]!=arr[i+1]-1)// for sorted array only
    //or you can use sort method of javascript
    //From http://www.javascriptkit.com/javatutors/arraysort.shtml
    {
        newarr.push(arr[i]);
    }
}
newarr.push(arr[arr.length-1]);// for last Element
console.log(newarr);

Fiddle http://jsfiddle.net/R75bd/


text:
Q: One image in a table with many rows I am trying to create a responsive  with bootstrap with many rows but a single image in it (see attached). I am stuck. Any help is appreciated.

A: the property you are looking for is rowspan

td {
  width: 10vw;
  text-align: center;
  font-size: 4vw;
}

img {
  width: 10vw;
}

    a

    b

    c
    d

    e
    f


text:
Q: Integrate Robolectric and JDave I would like to know if there is an easy way to have these two frameworks work together, really like the JDave BDD syntax and the Robolectric framework to do test outside android environment.
Is this possible, each have their custom TestRunner, have anyone else tried to do this? Is it doable in a simple way?


text:
Q: How to limit number of characters of 2 text Views in Swift at the same time? I'm having some problems trying to set the numbers of the characters of 2 different UITextViews to 12 (for example).
It works OK with only one UITextView but it becomes hard with both.
There are actually some errors while writing text in them. It doesn't type anything now. I have been trying different ways to get it done but everything seems wrong in the shouldChangeTextInRange method.
How do I set the number of characters of both textViews properly?
class viewControllerCuatro: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textViewInteriorUno: UITextView!
    @IBOutlet weak var textViewInteriorDos: UITextView!

    @IBOutlet weak var textViewExteriorUno: UITextView!
    @IBOutlet weak var textViewExteriorDos: UITextView!

    @IBOutlet weak var foto1: UIImageView!
    @IBOutlet weak var foto2: UIImageView!

    @IBOutlet weak var imagenFondo: UIImageView!

    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {

        textViewExteriorUno.delegate = self
        textViewExteriorDos.delegate = self
        textViewInteriorUno.delegate = self
        textViewInteriorDos.delegate = self

        textViewExteriorUno.layer.masksToBounds = true
        textViewExteriorUno.layer.borderWidth = 6
        textViewExteriorUno.layer.cornerRadius = textViewExteriorUno.layer.frame.height/6
        textViewExteriorUno.layer.borderColor = UIColor.purpleColor().colorWithAlphaComponent(0.2).CGColor

        textViewExteriorDos.layer.masksToBounds = true
        textViewExteriorDos.layer.borderWidth = 6
        textViewExteriorDos.layer.cornerRadius = textViewExteriorDos.layer.frame.height/6
        textViewExteriorDos.layer.borderColor = UIColor.purpleColor().colorWithAlphaComponent(0.2).CGColor

        foto1.layer.masksToBounds = true
        foto1.layer.borderWidth = 6
        foto1.layer.cornerRadius = foto1.layer.frame.height/6
        foto1.layer.borderColor = UIColor.purpleColor().colorWithAlphaComponent(0.2).CGColor

        foto2.layer.masksToBounds = true
        foto2.layer.borderWidth = 6
        foto2.layer.cornerRadius = foto2.layer.frame.height/6
        foto2.layer.borderColor = UIColor.purpleColor().colorWithAlphaComponent(0.2).CGColor

        foto1.image = fotoUnoEscogida
        foto2.image = fotoDosEscogida

        imagenFondo.image = UIImage (named: tipoDeHojaElegida)
    }

    override func viewDidAppear(animated: Bool) {

        let alertNotSuccessRegister = UIAlertController(title: "¡Casi hemos terminado!", message: "Modifica los textos a tu gusto para que sea lo más personal posible.", preferredStyle: .ActionSheet)

        alertNotSuccessRegister.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))

        self.presentViewController(alertNotSuccessRegister, animated: true, completion: nil)
    }

    @IBAction func botonSiguiente(sender: AnyObject) {
        if textViewInteriorUno.text != " " || textViewInteriorDos.text != " " {

            textoPersonalUno = textViewInteriorUno.text!
            textoPersonalDos = textViewInteriorDos.text!

            performSegueWithIdentifier("hey3", sender: self)

                  print("Se acaba de guardar el texto \(textoPersonalDos)")

        } else {

            let alertaError = UIAlertController(title: "Por favor, rellena los campos de texto.", message: "Dedica unas bonitas palabras :D", preferredStyle: .ActionSheet)

            alertaError.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))

            self.presentViewController(alertaError, animated: true, completion: nil)
        }
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if textViewInteriorUno.text == ""  || textViewInteriorUno.text.isEmpty == true || textViewInteriorDos.text == "" || textViewInteriorDos.text.isEmpty == true {

            textViewInteriorUno.text = " "
            textViewInteriorUno.resignFirstResponder()

            textViewInteriorDos.text = " "
            textViewInteriorDos.resignFirstResponder()
        }
        else{

            self.textViewInteriorUno.resignFirstResponder()

            self.textViewInteriorDos.resignFirstResponder()
        }
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{

        let newLength = textViewInteriorUno.text.utf16.count + text.utf16.count - range.length

        let otherLength = textViewInteriorDos.text.utf16.count + text.utf16.count - range.length

        if (newLength <= 12) && (otherLength > 6) {
            return true
        } else {
            return false
        }
    }

A: The delegate method is told which text view's delegate is being called. So, look at the textView argument in the method and then return based on that. For example:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{

    var shouldReplace = true // For most cases, return true, only modify if we have a special case
      let newLength = textView.text.utf16.count + text.utf16.count - range.length
    // If the textView is 'textViewInteriorUno'
    if textView.isEqual(textViewInteriorUno
    {
      shouldReplace = newLength <= 12           // will be true if the length is less than or equal to 12
    }
    // If the textView is 'textViewInteriorDos'
    else if textView.isEqual(textViewInteriorDos)
    {
      shouldReplace = newLength < 6 // Will be true if the length is less then 6
   }

    return shouldReplace
}

This way, you base your delegate's response on what the textView is, and you don't modify the behavior of other views.


text:
Q: Comparing demographics between 3 groups I'd like to check on differences between 3 diagnostic categories in the demographics (for instance if one disorder is more prevalent in females or males), so I'd like to make comparisons on nominal & ordinal variables.
Which is the best method to use on SPSS?


text:
Q: What is the point of using *args when a list of arguments can be used? Would passing in a list or dictionary of variables be more concise than passing in *args in Python methods?
For example,
def function(a, *argv):
   print('First variable:', a)
   for k in argv:
      print('Additional variable:',k)

is the same as
def function(a, list):
   print('First variable:', a)
   for k in list:
      print('Additional variable:',k)

except a list is passed in the second argument. What I think using *args would often do is to cause additional bugs in the program because the argument length only needs to be longer than the mandatory argument length. Would any please explain situations where *args would be really helpful? Thanks

A: The first function accepts:
function('hello', 'I', 'am', 'a', 'function')

The second one won't. For the second you'd need:
function('hello', ['I', 'am', 'a', 'function'])

In principle, the first one is used when your function can have an arbitrary number of parameters (think: print), while the second one specifies that there's always a second parameter, which is an iterable (not necessarily a list, despite the name)

A: Passing *args is useful when you have to extract only some (or none) arguments in first level function and then pass others to other inner function without knowing about the details. e.g.
def inner_func(x, y, z, *args, **kwargs):
    # do something with x, y, and z
    return output

def outer_func(a, b, *args, **kwargs):
    # do something with a and b
    # pass the rest arguments to inner function without caring about details
    output = inner_func(*args, **kwargs)

    # do something with output
    return

A: That is a fair ask as to why *args (or **kwargs) is essentially required when a list (or dict) could do the same task. The key reason to that is when a ** caller of a function does not know the number of arguments beforehand**. I'll try to explain this with reference to the particular scenario you have shared.
Lets suppose that we have the below function which finds the sum of all integers passed in. (I'm giving up sum builtin function for demonstration purpose, please bear with me :) )
def do_add(*int_args):
    total = 0
    for num in int_args:
        total += num
    return total

And you want to call this for an unknown number of arguments with an unknown number of times.
If in case you need to send a list argument, the do_add function might look like below:
def do_add(int_list):
    total = 0
    for num in int_list:
        total += 0
    return total

l1 = [1, 2, 3, 4, ... n]    # memory loaded with n int objects
do_add(l1)

l2 = [10, 20, ... n]
do_add(l2)

Firstly, you are loading the memory with an additional list object created just for the sake of function call. Secondly, if you have to add some more items to the list we may need to call another list method such as append or extend.
But if you follow the *args approach, you can avoid creating an extra list and focus only on the function call. If you need to add more arguments you can just add another argument separated by a comma rather than calling append or extend methods.
Assume that you want to call this function n times with 1000 arguments. It will result in n * 1000 new list objects to be created every time. But with the variable arguments approach, you can just call it directly.
do_add(1, 2, 3)            # call 1
do_add(10.0, 20.0, 30.0)   # call 2
...
do_add(x, y, z, ..., m)    # call n


text:
Q: Bootstrap CDN not applying So I'm not sure if it's just because I'm a noob at this or what, but I can't get the bootstrap CDN to work. I copied the CDN from their website and pasted it into the code I was working on, and then a fresh page, as shown below and it's not applying on either. The weird thing is that the CDN from freecodecamp on their bootstrap portion works. What am I doing wrong?
Heres the code
<!doctype HTML>

    <title>Bootstrap</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"/>

A: You need to import jQuery as well (bootstrap uses it) and its best to load it just before your closing  tag so that it doesn't block other loading and is then called with a $(document).ready() wrapper.

<!DOCTYPE html>

    <title>Bootstrap 4 Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

My First Bootstrap Page

This is some text.


text:
Q: Not able to retrive control from Listview in asp.net Basically, I am trying to put validation control in  of Listview. But, I am not able to specify ControlToValidate = "grpNameTextBox".
I tried to put
((RequiredFieldValidator)ListView1.FindControl("RequiredFieldValidator1")).ControlToValidate = ((TextBox)ListView1.FindControl("grpNameTextBox")).ID;
in different Events, but not able to do it.
Afterwards, I deleted Validation Control, and put simple Label. Then in 'ItemInserting' event I put this code :
protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        TextBox t1 = (TextBox)ListView1.FindControl("grpNameTextBox"); // Getting Null Exception here
        if (t1.Text.Trim() == null)
        {
            throw new System.Exception("Field cannot be empty");

        }
    }

But getting "Object reference not set to an instance of an object." error.
Can any one tell me, where I am wrong?
.aspx part is given below :
<InsertItemTemplate>

                <asp:Button ID="InsertButton" runat="server" CommandName="Insert"
                    Text="Insert"  />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
                    Text="Clear" />

                <asp:TextBox ID="grpNameTextBox" runat="server" Text='<%# Bind("grpName") %>' />
                <asp:Label ID="lblError" runat="server" Text=""></asp:Label>

    </InsertItemTemplate>

Thanks.

A: Try to modify your code
  protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
  {
    TextBox t1 = (TextBox)e.Item.FindControl("grpNameTextBox");
    if(t1==null) return; // or exception
    Button btn = (Button)e.Item.FindControl("InsertButton");
    RequiredFieldValidator rfv = (RequiredFieldValidator)e.Item.FindControl("rfvId");
        if (rfv != null&& btn!=null)
        {
            rfv.ControlToValidate = t1.ClientID;
            rfv.ValidationGroup = rfv.ClientID + "ValidationGroup";
            btn.ValidationGroup = rfv.ClientID + "ValidationGroup";
        }

  }

A: You are not generating textbox id dynamically in listview, so you can directly give controlTovalidate value to "grpNameTextBox" in aspx page.
Assign same ValidationGroup to RequiredFieldValidator as well as Insert button in aspx code, no code require for validation.

A: TextBox txt_btn = (TextBox)e.Item.FindControl("grpNameTextBox");


text:
Q: Getting methods from base class? I am brand new to base classes so please correct me if I am wrong or I should be doing this another way, but I have coded a simple code snippet below that explains what I want to do.
class A : B
{
    private int _classId;

    public A (int id) : base(id)
    {
        _classId = id;
    }

    public string GetString()
    {
        return "This will eventually be an important string.";
    }
}

class B
{
    private int _classId;

    public B (int id)
    {
        // here I want to be able to get access to class A's methods
        // such as GetString() ...
    }

    public void SomeMethod()
    {

    }
}

So what I want to do is allow B to get A's methods.
Reason for doing this?
I don't want to populate the class A because B is going to have a lot of methods so it would be cleaner to keep them in B then just get them from A in other code. Am I doing this wrong? is this not what base classes do? I simply just want to be able to still do this:
A.SomeMethodInB();

Without populating class A with junk and making it cleaner by storing it in class B

A: Let me summarize your question:

*

*You want a method that is only implemented in a descendant class (A)

*You want this method to be available to both the base class (B) and the descendant class (A)

*You want the base class to be able to call the descendant class' implementation of the method

This is the original definition of polymorphism  (lately people have been using the term much more generally) and is bread-and-butter when it comes to OOP. It is also the hardest area of OOP to grasp for newcomers.
Write a base class with a virtual method
Let us start with the base class.  Notice I have changed your example slightly, for a reason I will explain in a moment.
class B
{
    virtual protected string GetString()
    {
        return "I am a B";
    }

    public void DoSomethingWithGetString()
    {
        Console.WriteLine(GetString());
    }
}

In this example, DoSomethingWithGetString calls GetString.  Note that GetString is virtual. This tells the compiler that we don't want to decide where the implementation of GetString is until runtime.  This means it can't be bound at compile time: instead, its location is identified by a runtime Virtual Method Table that is set up when the object is created.  If this code is running as part of a instance of class B, then it will call class B's implementation of GetString.  But if this code was inherited, and is actually being called by some other object that descends from class B, it will call that class' version of GetString.  This is called late binding.
Write the descendant class
So now let's write class A:
class A : B
{
    protected override GetString()
    {
        return "I am an A.";
    }
}

Because A descends from B, we don't need to implement anything else.  If we call A.DoSomethingWithGetString it'll actually call B's implementation because it is inherited.
Execute it
If you run this code
var a = new A();
a.DoSomethingWithGetString();  //Output = "I am an A"

...the following will happen:

*

*An instance of A, which descends from B, is created

*The VMT of A is configured so that calls to GetString are sent to A.GetString.

*You call A.DoSomethingWithGetString

*This call is directed to B's code base, because A doesn't implement it.

*The code base in B detects that GetString is a virtual method, and calls it using the VMT.

*The VMT points to A's implementation of GetString.

*A.GetString is executed.

Thus you have an situation where code in class B is calling code in class A, which is what you asked for.
You can also run it this way:
B b = new A();
b.DoSomethingWithGetString(); //Output = "I am an A"

Thus you have a pointer to a B that says it's an A, because it is using a VMT set up for class A.
But I don't want any implementation in class B
Now, let's say you don't want class B to have any implementation at all for GetString, but you still want to be able to call the implementation in A. There is a way to do this using an abstract virtual method.  Simply add the abstract keyword and remove the implementation:
abstract class B
{
    abstract protected string GetString(); //Notice no implementation

    public void DoSomethingWithGetString()
    {
        Console.WriteLine(GetString());
    }
}

Of course, now you can't use class B by itself, because it requires an implementation of GetString that will only be present in a descendant class. So you can no longer create an instance of B directly; you have to subtype, and use the subtype.
Can't use constructor
Now, you'll notice in my example I removed your constructor calls.  There is a reason for this.  A constructor should not ever call a method that is defined on a descendant class.  The reason: during construction, constructors are called up and down the inheritance hierarchy, starting with the base class and moving down the descendant chain. That means, when you call B's constructor, A's constructor has not been called yet.  if A's constructor hasn't run yet, we can't be sure that A has been properly set up yet, and therefore it is a really bad idea to call any of its methods.
There are some workarounds for this, but that is a topic for a different question.

A: If the method is only defined in Class A, then there is no way to access it through Class B.
If the method exists in both Class A and Class B, then you can use virtual method and override.

A: Think it is better to use the names BaseClass and DerivedClass in an example. The names A and B are kind of arbitrary. Although A comes before B, the names don't imply the direction of inheritance intended.
class Program
    {
        static void Main(string[] args)
        {
            var bc = new BaseClass(3);
            var dc = new DerivedClass(5);

            Console.WriteLine("Base Class Method A: " + bc.MethodA());
            Console.WriteLine("Derived Class Method A: " + dc.MethodA());
            Console.WriteLine("Base Class Method B: " + bc.MethodB());
            Console.WriteLine("Derived Class Method B: " + dc.MethodB());
            Console.ReadLine();
        }
    }

    public class BaseClass {
        protected int _classId;

        public BaseClass(int classId) {
            _classId = classId;
        }

        public virtual string MethodA() {
            return "Method A in base class: " + _classId.ToString();
        }

        public string MethodB()
        {
            return "I am a method B in the base class: " + _classId.ToString();
        }
    }

    public class DerivedClass : BaseClass {
        public DerivedClass(int classId)
            : base(classId)
        {

        }

        public override string MethodA() {
            return "Method A in derived class: " + _classId.ToString();
        }
    }

A: There are two ways you can go about this. Let me first set out an example.
Here we have the base class that contains a method:
public class Base
{
    public void BaseMethod()
    {
        // Some method.
    }
}

Here is the derived class, where we want to call the method:
public class DerivedClass : BaseClass
{
    // We want to use BaseMethod() here.
}

In order to call a method from the base class, we use the base keyword.
public class DerivedClass : BaseClass
{
    base.BaseMethod();
}

This is fine if you want to just call the base method. However, if we want to change the method and define it with a different function, we have to declare it as virtual in the base class, as so:
public class Base
{
    public virtual void BaseMethod()
    {
        // Some method.
    }
}

In the derived class, we can now use the keyword override to override the virtual method of the base class, which redefines it to do something else:
public class DerivedClass : BaseClass
{
    public override void BaseMethod()
    {
        // Some new function.
    }
}


text:
Q: How to fetch a particular record from three tables Table Name :: Feedback_master
Fields 1. feed_id 2. roll_id 3. batch_id 4. sem_id (semester ID) 5.f_id (faculty Id) 6. sub_id (subject Id) 7. remark. 8. b_id
Table Name :: subject_master
Fields

*

*sub_id (subject Id)

*sub_name (Subject Name0

*f_id ( Faculty ID)

Table Name :: faculty_master
Fields

*

*f_id (Faculty Id)

*f_name (Faculty Name)

*l_name (Faculty Name)

*b_id

This are the three tables. Now I want to fetch the detail from this three table.
I want the output as
f_Name (faculty name), Sub_name (Subject Name ) , and remark (Remark ) when i give the (faculty id) f_id
could some one help me to over come this problem.

A: Using Objects
Select T1.f_name, T2.sub_name, T3.remark from faculty_master as T1,
subject_master as T2, Feedback_master as T3 where T1.f_id = 'your faculty_id'
and T1.f_id = T3.f_id and T2.sub_id = T3.sub_id

A: heu, MySQL I presume?
SELECT f_name, sub_name, remark
FROM faculty_master
LEFT JOIN subject_master USING(f_id)
LEFT JOIN Feedback_master USING(f_id)
WHERE f_id = the_id_you_want

A:
select fm.f_name, sm.sub_name, remark from faculty_master fm left
  join sub_master sm on fm.f_id=sm.f_id
  left join feedback_master fbm on
  sm.sub_id = fbm.sub_id
  where fm.f_id= 123

A: You can build up the query in stages. The first thing is that you're after a list of feedback remarks, so start with this simple select query:
SELECT * FROM Feedback_master

That's listing all the feedback from all over, but you want to limit it to only feedback on a particular faculty, so let's add a Where clause:
SELECT * FROM Feedback_master
  WHERE Feedback_master.f_id = @f_id

Now we've got the right list of records, but the list of fields is wrong. You want the faculty name and subject name, which aren't there in the Feedback_master table; the subject_master and faculty_master tables are linked and assuming that every remark has a subject ID and a faculty ID, we can use a simple inner join to link the tables:
SELECT * FROM Feedback_master
  INNER JOIN subject_master ON Feedback_master.sub_id = subject_master.sub_id
  INNER JOIN faculty_master ON Feedback_master.f_id = faculty_master.f_id
  WHERE Feedback_master.f_id = @f_id

Now it's pulling out all the fields from all three table; this includes all the fields we need, so we can now simply name them in the Select clause:
SELECT
  faculty_master.f_name, subject_master.sub_name, Feeback_master.remark
FROM Feedback_master
  INNER JOIN subject_master ON Feedback_master.sub_id = subject_master.sub_id
  INNER JOIN faculty_master ON Feedback_master.f_id = faculty_master.f_id
WHERE Feedback_master.f_id = @f_id


text:
Q: How to enable ssl authentication for a new Kafka consumer in Flink? Flink enthusiasts,
I'm consuming from a kafka broker in a remote server that has ssl authentication enabled. How do I config my FlinkKafkaConsumer to comply with ssl authentication? Which flags/properties and values need to be set in the Properties objects for the Consumer? Any pointers to either documentation or sample code is welcome.
Disclosure: this is not Kerberos server ssl authentication.
Many thanks
Alex


text:
Q: Correct way to check the existance of a user in a database after OAuth2 authentication i am working on a web application using SpringBoot and OAuth2 that requires just the authentication by google. It can allow acces just to the members of my uni but not any member, they have to be registered in a database, specifically their emails. So i created an entity class User:
User(id, email, role)

In this table the user with the role ADMIN could add users, delete them and update their role so it must have a different dashboard than a regular user. I started creating my custom OAuthUser, in this i just store the name and the email from the authenticated user. With the Google restrictions it allows just members of my organization so here i have to implement the function that is going to check if the email of that authenticated user is in the database, after that check his role and allow acces to the different functionalities. And this is the part where i'm stucked, I don't know how to check the existence of that email in the database.
This is my CustomOAuthUser:
    private OAuth2User oAuth2User;

    public CustomOAuth2User(OAuth2User oAuth2User) {
        this.oAuth2User = oAuth2User;
    }

    @Override
    public Map<String, Object> getAttributes() {
        return oAuth2User.getAttributes();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return oAuth2User.getAuthorities();
    }

    @Override
    public String getName() {
        return oAuth2User.getAttribute("name");
    }

    public String getFullname(){
        return oAuth2User.getAttribute("name");
    }

    public String getEmail(){
        return oAuth2User.<String>getAttribute("email");
    }
}

And this is my WebSecurity configuration:
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/index", "/login", "/oauth/**").permitAll()
                .and()
                .oauth2Login()
                .loginPage("/login")
                .userInfoEndpoint()
                .userService(customOAuthUserService);
    }

    @Autowired
    private CustomOAuthUserService customOAuthUserService;
}

I have not found any way to check the existence of the email in the database after getting the google info using this function. I would appreciate any kind of help, maybe there's a better way to do what im trying to do here.
This would be my user entity:
public class User {

    @Id
    @Column(nullable = false, updatable = false)
    private Long id;

    @Column(nullable = false, updatable = false)
    private String email;

    @Column(nullable = false)
    private String role;
}

In my user repository i implemented the next query:
    @Query("SELECT s FROM User s WHERE s.email=?1")
    Optional<User> findUserByEmail(String email);

Thanks in advance.

A: Not sure if you're still looking for a solution but this is how I checked if email exists in the database.
Edit your CustomOAuth2UserService.java as follows:
    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException
    {
        String clientName = userRequest.getClientRegistration().getClientName();
        OAuth2User user = super.loadUser(userRequest);

        CustomOAuth2User customOAuth2User = new CustomOAuth2User(user, clientName);
        String email = customOAuth2User.getEmail();

        Optional<User> optionalUser = userRepository.findUserByEmail(email);
        boolean userExists = optionalUser.isPresent();

        if (userExists)
        {
            //Your code here
        }

        return customOAuth2User;
    }


text:
Q: Reliability and Performance Monitor Data Collector Set : Logon failure: unknown user name or bad password When I try to start a Data Collector Set in the Reliability and Performance Monitor in Windows Vista Business I receive the following error:

When attempting to start the Data
  Collector Set the following system
  error occured:
Logon failure: unknown user name or
  bad password.

What could be causing this ?

A: On the "General" tab for the set properties there's a "Run as" buttonm that you can use to set what account it runs as. Try running as the local Administrator and confirm that works, then try using a less privileged account as appropriate.
JR


text:
Q: Android WebView Conservar contenido cuando se cambia de fragmento Les consulto si es posible resolver lo siguiente:

*

*mantener el contenido de un webview contenido en un fragment al cambiar a otro fragment

Lo que tengo implementado y copio abajo, reinicia el contenido cada vez que se muestra el fragment. por ej: si se esta completando un formulario, se vuelve al home (gooogle.com) y se pierde esto.
public class GalleryFragment extends Fragment {

WebView miVisorWeb;

String url = "https://www.google.com/";

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_gallery, container,false);

    // Bloque 1
    miVisorWeb = (WebView) root.findViewById(R.id.webViewGoogle);
    miVisorWeb.requestFocus();
    WebSettings webSettings = miVisorWeb.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setCacheMode(LOAD_CACHE_ELSE_NETWORK);
    webSettings.setAppCacheEnabled(true);

        miVisorWeb.loadUrl(url.toString());
         CookieManager.getInstance().setAcceptCookie(true);
        // Bloque 2
        miVisorWeb.setWebViewClient( new WebViewClient(){
           public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }
    });

    miVisorWeb.setOnKeyListener(new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
            {
                WebView webView = (WebView) v;

                switch(keyCode)
                {
                    case KeyEvent.KEYCODE_BACK:
                        if(webView.canGoBack())
                        {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });

    return root;
}
}

Supongamos que se reproduce un video en el fragment A, cuando cambio al B y retorno al A la idea es que siga viendose la reproducciòn.
Similar a las pestañas de los navegadores, la idea seria esa.
Saludos!!!

A: Lo que puedes intentar es lo siguiente:
Recordando un poco el ciclo de vida del fragment, bajo la idea que quieres realizar, puedes mover el código que tienes el método onCreate(). Recordemos que este método te permite inicializar algunas cosas y cuando vuelvas a este fragment no volverás a ejecutar esté método si y solo si este ya fue creado. Con la idea que tienes como tu fragment ya fue creado, no se volverá a ejecutar (reiniciar). Por ahora lo tienes en el método onCreateView() Recomendaría que lo muevas al método onCreate(). Luego cuando vas a llamar algún fragment, recuerda que podemos reemplazar (método replace()) del fragmentManager y podemos agregar ( método add() ) del fragmentManager. Para tu caso lo que más te conviene es realizar un add(). Te dejo un ejemplo:
Para agregar :
getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();

Para reemplazar :
getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, firstFragment).commit();

Update
Ejemplo :
public class GalleryFragment extends Fragment {

    WebView miVisorWeb;

    String url = "https://www.google.com/";

   @Override
   public void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       //inicializar variables, como la url que quieres cargar.
       // Algunas otras cosas que quieres que solo se llame una vez
       url = "https://www.google.com/";
   }

   public View onCreateView(@NonNull LayoutInflater inflater,
                     ViewGroup container, Bundle savedInstanceState) {
       // Aqui inicializar tu vistas y componentes
       View root = inflater.inflate(R.layout.fragment_gallery, container,false);

       miVisorWeb = (WebView) root.findViewById(R.id.webViewGoogle);

       return root;
    }

@Override
public void onViewCreated(View view, @Nullable Bundle     savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

     //Aqui va todo el código restante
     miVisorWeb.requestFocus();
     WebSettings webSettings = miVisorWeb.getSettings();
     webSettings.setJavaScriptEnabled(true);
     webSettings.setCacheMode(LOAD_CACHE_ELSE_NETWORK);
     webSettings.setAppCacheEnabled(true);

     miVisorWeb.loadUrl(url.toString());
     CookieManager.getInstance().setAcceptCookie(true);
     // Bloque 2
     miVisorWeb.setWebViewClient( new WebViewClient(){
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return false;
       }
     });

      miVisorWeb.setOnKeyListener(new View.OnKeyListener(){
          @Override
          public boolean onKey(View v, int keyCode, KeyEvent event){
              if(event.getAction() == KeyEvent.ACTION_DOWN){
                WebView webView = (WebView) v;
                switch(keyCode){
                    case KeyEvent.KEYCODE_BACK:
                        if(webView.canGoBack()){
                            webView.goBack();
                            return true;
                        }
                        break;
                 }
              }

              return false;
           }
       });

    }
}

Ahora cuando quieres llamar a otro fragmento lo que tienes que hacer es lo siguiente:
// Add the fragment to the 'fragment_container' FrameLayout
            supportFragmentManager.beginTransaction()
                    .add(R.id.fragment_container, firstFragment).addToBackStack(null).commit()

Recuerda que el parámetro R.id.fragment_container es el id de tu contenedor de fragments y firstFragment es el fragment hacia donde quieres ir. Solo reemplaza esos valores con los que tienes en tu proyecto
Luego, citando tu ejemplo. Si vuelves de B hacia A, el código que tienes en A ya no se ejecutará. Porque solo está en el método onCreate
Otra manera de solucionar para que no estes manejando fragments es hacerlo con activities. Siguiendo el mismo ejemplo de fragments. En tu activity, llamémosle A. Agregas todo el código que tienes. Luego simplemente para pasar a a un activity B. llamas a startActivity. Cuando haces back tampoco se ejecutara el código que tienes en el método onCreate del activity A.
Referencias:
FragmentManager
Espero te ayude :)


text:
Q: Locked .csproj file breaking Mercurial respository I am using VisualHG inside Visual Studio. On occasion when pulling (with Fetch) I get this error message:
[Errno 13] C:\inetpub\Websites\SomeProject.csproj: The process cannot access the file because it is being used by another process
This in turn makes a mess of my repository causing me to have to delete everything and pull again. Is there anything I can do to prevent this? It seems this issue never happens when pulling from TortoiseHG or from the command line, only when the project is opened in Visual Studio and pulling with VisualHG.

A: We're seeing something very similar on a machine here with TortoiseHg 2.0.4 and VS2008. It looks like Visual Studio it briefly locking the file as it detects a file modification event, and this is causing Hg to fail. We're seeing this with both TortoiseHg and the command-line client.
Whilst it's pretty frustrating when it happens during a pull, it also happens during a merge too, which can be pretty catastrophic.

A: It may be the only thing you can do is to not have Visual Studio open when you fetch. It's not the pull part of fetch that's causing it, but the update. Visual Studio seems to have a lock on your project file and won't let Mercurial change it while it's open.
You didn't specify, however, if the project was open when you used fetch through TortoiseHG or the commandline. You could also try just pulling and updating separately rather than using fetch.
Edit: It could also be the TortoiseHg version. I tried doing an update to a different revision earlier with an open project and Visual Studio 2008 just wanted to reload it (no file lock error), but I'm using TortoiseHg 2.0.5. You can always go back to 1.1.* if you don't like it or it doesn't work.

A: We have seen the same issue with file locking with Mercurial and VS2008, but unrelated to the .csproj files. We don't even version control our project files as they are generated by cmake and we version control our cmake files instead.
This problem has caused me to lose a days worth of work in one case and caused improper merges in other cases in that older files were overwriting newer files.
I was using the fetch extension when these things happened.

Z:>hg --version Mercurial Distributed SCM (version 1.9.2) (see
  http://mercurial.selenic.com for more information)
Copyright (C) 2005-2011 Matt Mackall and others This is free software;
  see the source for copying conditions. There is NO warranty; not even
  for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


text:
Q: Keycloak WFLYCTL0362: Capabilities required by resource I'm trying to run rh-sso-7/sso74-openshift-rhel8 container in Openshift and it says the following:
13:03:20,612 ERROR [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0362: Capabilities required by resource '/subsystem=infinispan/cache-container=web/transport=jgroups' are not available:
    org.wildfly.clustering.jgroups.default-channel-factory; Possible registration points for this capability:
        /subsystem=jgroups
13:03:20,613 ERROR [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0362: Capabilities required by resource '/subsystem=infinispan/cache-container=server/transport=jgroups' are not available:
    org.wildfly.clustering.jgroups.default-channel-factory; Possible registration points for this capability:
        /subsystem=jgroups
13:03:20,614 ERROR [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0362: Capabilities required by resource '/subsystem=infinispan/cache-container=keycloak/transport=jgroups' are not available:
    org.wildfly.clustering.jgroups.default-channel-factory; Possible registration points for this capability:
        /subsystem=jgroups
13:03:20,614 ERROR [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0362: Capabilities required by resource '/subsystem=infinispan/cache-container=ejb/transport=jgroups' are not available:
    org.wildfly.clustering.jgroups.default-channel-factory; Possible registration points for this capability:
        /subsystem=jgroups
13:03:20,614 ERROR [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0362: Capabilities required by resource '/subsystem=infinispan/cache-container=hibernate/transport=jgroups' are not available:
    org.wildfly.clustering.jgroups.default-channel-factory; Possible registration points for this capability:
        /subsystem=jgroups
13:03:20,716 FATAL [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0056: Server boot has failed in an unrecoverable manner; exiting. See previous messages for details.

Please, help.


text:
Q: Is there a way to create and return new variables from a method in C#? Basically like using the out keyword. But the problem is with the out keyword, you still have to declare a variable outside the method call, like:
double result;
Double.TryParse ( "76", out result );

where as I want something like:
Double.TryParse ( "76", out result );

and there I get a new variable called result.
Is there a way to do this (by using out or not)?

A: No, you have to declare the variable first because you are passing it to the method, the only difference is that you are explicitly requiring the method to fill it out before returning.

A: Also, you can "rethrow" it, that is, you pass it up the stack as an out again. For example:
public void MyMethod(out int MyParam)
{
    SomeMethod(out MyParam);
}

A: You can use C# tuples to compose multiple variables into one.

A: A variable must be declared before it is used and a method with more than a few parameters gets smelly quick. Output parameters especially.
I think what you want to do is declare a class that contains your five or six variables and pass that as the argument to the method:
class Args
{
  public int One { get; set; }
  public int Two { get; set; }
  public int Three { get; set; }
  public int Four { get; set; }
  public int Five { get; set; }
}

Then a method taking it as an argument:
public void Foo(Args args)
{
  // Modify members of args here.
}

And use it like this:
Args args = new Args();

Foo(args);

// Do stuff with results in args.

A: What's the problem with declaring it before the call?

A: Why are you trying to do this? There's no reason not to declare it before the method call, save the few keystrokes.

A: Is there any case with a sence for your szenario?
In order to use the variable after the call to your function, you have to know the type of the variable. Otherwise you would ignore the type-safety of the compiler and could easily run into runtime-errors.

A: No, you have to wrap it in another method that declares a local variable and then returns it.
With the specific example you gave, you can just use:
Double d = Double.Parse( "76" );

A: variables live on the stack, not the heap, so the notion of calling a function to create new variables - while an interesting idea and not impossible in other languages - implies that you don't understand the difference between a variable and an object in C#.

*

*a variable's storage is allocated on the stack, and the variable only exists for the duration of the execution of the function that declares the variable

this is distinct from a 'member variable' which is a field belonging to an object.
the 'out' keyword in C# means that a variable will be passed into the function 'by reference', and the function is expected to (required to) set the variable's value.
in general, 'out' parameters should be avoided; if you need to pass several values out of a function, they probably belong to a missing object!
EDIT: in C# an 'out' parameter is similar to a 'ref' parameter in that they are both call-by-reference parameters, as opposed to the more typical call-by-value parameter.


text:
Q: Kubernetes MySQL pod stuck with CrashLoopBackOff I'm trying to follow this guide to set up a MySQL instance to connect to. The Kubernetes cluster is run on Minikube.
From the guide, I have this to set up my persistent volume:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

I ran kubectl describe pods/mysql-c85f7f79c-kqjgp and got this:
Start Time:   Wed, 29 Jan 2020 09:09:18 -0800
Labels:       app=mysql
              pod-template-hash=c85f7f79c
Annotations:  <none>
Status:       Running
IP:           172.17.0.13
IPs:
  IP:           172.17.0.13
Controlled By:  ReplicaSet/mysql-c85f7f79c
Containers:
  mysql:
    Container ID:   docker://f583dad6d2d689365171a72a423699860854e7e065090bc7488ade2c293087d3
    Image:          mysql:5.6
    Image ID:       docker-pullable://mysql@sha256:9527bae58991a173ad7d41c8309887a69cb8bd178234386acb28b51169d0b30e
    Port:           3306/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    137
      Started:      Wed, 29 Jan 2020 19:40:21 -0800
      Finished:     Wed, 29 Jan 2020 19:40:22 -0800
    Ready:          False
    Restart Count:  7
    Environment:
      MYSQL_ROOT_PASSWORD:  password
    Mounts:
      /var/lib/mysql from mysql-persistent-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-5qchv (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  mysql-persistent-storage:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  mysql-pv-claim
    ReadOnly:   false
  default-token-5qchv:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-5qchv
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                   From               Message
  ----     ------     ----                  ----               -------
  Normal   Scheduled  <unknown>             default-scheduler  Successfully assigned default/mysql-c85f7f79c-kqjgp to minikube
  Normal   Pulled     10h (x5 over 10h)     kubelet, minikube  Container image "mysql:5.6" already present on machine
  Normal   Created    10h (x5 over 10h)     kubelet, minikube  Created container mysql
  Normal   Started    10h (x5 over 10h)     kubelet, minikube  Started container mysql
  Warning  BackOff    2m15s (x50 over 10h)  kubelet, minikube  Back-off restarting failed container

When I get the logs via kubectl logs pods/mysql-c85f7f79c-kqjgp, I only see this:
2020-01-30 03:50:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.6.47-1debian9 started.
2020-01-30 03:50:47+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2020-01-30 03:50:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.6.47-1debian9 started.

Is there a better way to debug? Why are the logs empty?

A: I've faced the same issue and I solved it by increasing mysql container resources from 128Mi to 512Mi. Following configuration works for me.
containers:
  - name: cant-drupal-mysql
    image: mysql:5.7
    resources:
      limits:
        memory: "512Mi"
        cpu: "1500m"

A: Hmm really odd, I changed my mysql-deployment.yml to use MySQL 5.7 and it seems to have worked...
  - image: mysql:5.7

Gonna take this as the solution until further notice/commentary.

A: Currently 5.8 works

*

*image: mysql:5.8

Update above in Deployment file.


text:
Q: Incoming cellular calls ring on all my iOS devices When I receive an incoming cellular call on my iPhone 5 (iOS 8.3), it is propagated to all my other devices (including a wifi only iPad) connected to the same wifi network.
I guess that's an activated by default functionality, can it be deactivated ?

A: To disable on specific iDevices, go to Settings > FaceTime > iPhone Cellular Calls & switch off.
On a Mac, launch Facetime, then Preferences > iPhone Cellular Calls - uncheck.


text:
Q: How to rewrite google Tag Manager Args from typescript to react I am trying to insert google tags into my react site so I copied a code from a typescript code I have but I get the error Type annotations can only be used in TypeScript files. so now I have no idea on how to rewrite this code in an acceptable format in reactjs. Please help using the code below
_app.js
import React, {useEffect} from 'react'
import TagManager, {TagManagerArgs} from 'react-gtm-module'
import { Toaster } from 'react-hot-toast'
import './Product.scss'
import {Layout} from '../components'
import '../styles/globals.css'
import { StateContext } from '../context/StateContext'

function MyApp({ Component, pageProps }) {
  const gtmId = process.env.NEXT_PUBLIC_GTM_ID || "";

  const tagManagerArgs: TagManagerArgs = {
    gtmId,
  }

  useEffect(() => {
    TagManager.initialize(tagManagerArgs)
  }, [])

  return (
    <StateContext>
      <Layout>
        <Toaster />
        <Component {...pageProps} />
      </Layout>
    </StateContext>
  )
}

export default MyApp

A: You can remove the type annotation and update like the following code.
const tagManagerArgs = {
    gtmId,
  }

You can go through this link.


text:
Q: What is the purpose of using TThread.Synchronize inside a AnonymousThread? I came across this piece of Delphi code while searching for background methods to execute tasks in firemonkey.
TThread.CreateAnonymousThread(
            procedure()
            begin
                Sleep(10000);
                TThread.Synchronize(TThread.CurrentThread,
                procedure
                begin
                    Button2.Text := 'OK';
                end);
            end).Start;

Is TThread.Synchronize at this case really necessary?

A: TButton.Text changes a property of a Window object, which is inherently non-thread-safe, and is only to be accessed directly from the thread which created it OR via message sends/posts.
What TThread.Synchronize does is - it wraps the procedure together with a waitable object, places this to a queue, and waits on the handle - it may post a message to the main thread to wake it up.
If the code behind TButton.Text was implemented via posted message - and is is not - it would be safe to call from other threads, but it would not take effect immediately.
Long story short - you definitely have to call this via Synchronize, for good reasons.


text:
Q: Reactjs flux without npm I want to write my application using flux architecture, but I want to do this without any external libraries, npm, etc. Is this possible?

A: Yes, indeed it's possible
You could either:

*

*Write your own flux implementation, it's really quite simple.

*OR - if it's the idea of referencing external NPM packages that you don't like, just download the package once only and then copy the code into your source code so that you're not relying on NPM.


text:
Q: Total Stock by product category In Woocommerce reports I am trying to get Total Stock Valuation by Category in Woocommerce.
Anyone have a clue how this can be done?
I know it's a simple code but I just can't figure it out.

Thanks

A: UPDATED:
Not simple at all… but I get it. See the screenshot below:

1) GET THE DATA AND CALCULATE:
Here is a custom function with a bit complex SQL query that will get for each product category all the related products stock quantity. Then in a foreach loop, I add the stock quantities by product category to get the Total Stock Valuation by Category.
/**
 * Get the Total Stock Valuation by Category.
 *
 * @param integer $category_id (optional)
 * @return an array with the category ID (int) as key and total stock quantity (int) as value
 */
function get_product_cats_stock_qty( $category_id = 0 ){
    global $wpdb;

    // The DB tables involved
    $term_tax = $wpdb->prefix . "term_taxonomy";
    $term_rel = $wpdb->prefix . "term_relationships";
    $postmeta = $wpdb->prefix . "postmeta";

    if( 0 != $category_id )
    { // get one defined category
        $one_category_only = "AND $term_tax.term_id LIKE $category_id";
    } else
    { // get all categories
        $one_category_only = '';
    }

    // Query all detailed categories and related product stock quantity
    $results_obj = $wpdb->get_results("
        SELECT  $term_rel.term_taxonomy_id as cat_id,
        $term_rel.object_id as prod_id, $postmeta.meta_value as stock_qty
        FROM  $term_rel, $postmeta, $term_tax
        WHERE  $term_rel.object_id = $postmeta.post_id
        AND $term_rel.term_taxonomy_id = $term_tax.term_id
        $one_category_only
        AND $term_tax.taxonomy LIKE 'product_cat'
        AND $term_tax.count > 0
        AND $postmeta.meta_key LIKE '_stock'
        AND $postmeta.meta_value != ''
        ORDER BY $term_rel.term_taxonomy_id ASC
    ");

    // Iterating though each categories / products relationships stock quantity
    foreach($results_obj as $result){
        // Initialising each different category stock
        if( empty( $stock_qty_by_cat_id[ $result->cat_id ] ) )
            $stock_qty_by_cat_id[ $result->cat_id ] = 0;
        // category stock quantity calculation
        $stock_qty_by_cat_id[ $result->cat_id ] += intval( $result->stock_qty );
    }
    return $stock_qty_by_cat_id
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
2) ADMIN REPORTS STOCK SECTION CUSTOM TAB:
Here are the functions that will add a custom tab with the corresponding custom content: You will get a list of all product categories and for each of them all the related products stock quantity sum.
// Add a Custom tab to admin repport stock section
add_filter( 'woocommerce_admin_reports', 'add_my_custom_stock_admin_report', 10, 1 );
function add_my_custom_stock_admin_report( $reports ){
    $reports["stock"]["reports"]["category_stock_valuation"] = array(
        'title'       => __( 'Category Stock Valuation', 'woocommerce' ),
        'description' => '',
        'hide_title'  => true,
        'callback'    => 'content_custom_stock_admin_report',
    );
    return $reports;
}

// The content for the Custom tab to admin repport stock section
function content_custom_stock_admin_report( ){

    ?>

                    <?php _e('Term ID','woocommerce'); ?>
                    <?php _e('Category Name','woocommerce'); ?>
                    <?php _e('Stock count','woocommerce'); ?>

                <?php
                    foreach( get_product_cats_stock_qty() as $cat_id => $cats_stock_qty  ):
                        $cat_name = $cats_stock_qty['cat_name']; // category name
                        $stock_qty = $cats_stock_qty['stock_qty']; // Stock quantity
                ?>

                    <?php echo $cat_id; ?>
                    <?php echo $cat_name; ?>
                    <?php echo $stock_qty; ?>

                <?php endforeach; ?>

                    <?php _e('Term ID','woocommerce'); ?>
                    <?php _e('Category Name','woocommerce'); ?>
                    <?php _e('Stock count','woocommerce'); ?>

    <?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on WooCommerce 3+ and works.


text:
Q: Memory leak in PHP worker I have workers in PHP under supervisor.
And I have memory leak.. I use "xhprof" for tacking some information.
But I still cannot find anything.
If I restart worker - it's all fine, but then the problem started again :(
Any ideas concerning how I can find any information in "xhprof"?


text:
Q: The elements of {$1,2,3,...,n$} and {$1,2,3,...,n$} are randomly paired. What is the probability distribution of $S=\text{sum of pair products}$? The elements of {$1,2,3,...,n$} and {$1,2,3,...,n$} are randomly paired. What is the probability distribution of $S=\text{sum of pair products}$ ?
For example, say $n=5$. There are $5!$ ways to pair the elements, for example $(1,3)\ (2,5)\ (3,1)\ (4,4)\ (5,2)$ which gives $S=(1)(3)+(2)(5)+(3)(1)+(4)(4)+(5)(2)=42$.
I know that, in general:
$S_{\text{min}}=\sum_{k=1}^n{(k)(n-k+1)}=\frac{1}{6}n(n+1)(n+2)$, the triangular pyramidal numbers.
$S_{\text{max}}=\sum_{k=1}^n{k^2}=\frac{1}{6}n(n+1)(2n+1)$, the square pyramidal numbers.
I suspect that the probability distribution of $S$ is well-documented but I don't know what it's called.
Context: In 2020, the IB cancelled exams due to the pandemic and gave grades (1-7) based on other factors (predicted grades, coursework, school's historical grades). When the results were released, some schools felt that some of the grades seemed random. Then I wondered, if seven students got random Math grades 1, 2, 3, 4, 5, 6, 7 and random Physics grades 1, 2, 3, 4, 5, 6, 7, what is the probability distribution of the correlation coefficient between Math grades and Physics grades? That is essentially my question here, except my question here is generalized for $n$ students and grades.

A: As I suspected, the distribution is well-documented.
Arrange this sequence into rows by cutting through pairs of consecutive 1's.
$$1$$
$$1\ 1$$
$$1\ 2\ 0\ 2\ 1$$
$$1\ 3\ 1\ 4\ 2\ 2\ 2\ 4\ 1\ 3\ 1$$
$$...$$
Divide the numbers in the $n^{\text{th}}$ row by $n!$. For example, the $4^{\text{th}}$ row becomes
$$\frac{1}{24}\ \frac{3}{24}  \frac{1}{24} \frac{4}{24} \frac{2}{24} \frac{2}{24} \frac{2}{24} \frac{4}{24} \frac{1}{24} \frac{3}{24} \frac{1}{24}$$
These are the probabilities that $S=S_{\text{min}},\  S_{\text{min}}+1,\ S_{\text{min}}+2,\ ...,\ S_{\text{max}}$, respectively.
Here is a graph related to the distribution.
It seems there is no simple formula for the probabilities.
I found the sequence by using an online permutation generator, excel, and OEIS.
(The sequence is based on work done by the late John Conway in 1993. Professor Conway was my teacher in 1993. Little did I know that he would still be "teaching" me 29 years later.)

A: You can calculate the mean at least.
Write all the permutations of $(1,\ldots n)$ in $n!$ rows:
1, 2,   3, ...,   n-1, n
1, 2,   3, ...,   n,   n-1
...
n, n-1, n-2, ..., 2,   1

Then you would need to multiply the first column by $1$, the second row by $2$... the last column by $n$, sum everything up and divide by the number of rows $n!$.
But if you consider just the first column, since every two numbers are interchangeable, each number appears exactly $n!/n=(n-1)!$ times. The same is true for every column. So the total sum:
$$
n!\bar S = \underbrace{\sum_{k=1}^{n}}_{\text{sum by cols}} \left(k\cdot\underbrace{\sum_{i=1}^{n} i(n-1)!}_{\text{sum by elements in a col}}  \right) = (n-1)!\left(\sum_{k=1}^{n} k\right)\left(\sum_{k=i}^{n} i\right) =\\
(n-1)!\left(\frac{n(n+1)}2\right)^2,\\
\bar S = \frac{n(n+1)^2}4
$$