text:
Q: String compare error in transmission over TCP I have written a program in c to send a file line by line to a server from a client in c. After the file is transmitted completely, I have provided a line endoffile in the txt file to string compare in the server to identify that the file is over and the next file is being transmitted next. The next file has to be written to another file in the server. But the problem is that the strcmp is never detecting the endoffile in the code and endoffile recieved from the file in client as equal strings amd continues to write the next file from the client to the same file in server.
char enof[]="endoffile";
...
do
{
   rewind(appcrt);
   bytes_recieved = recv(pass_arg.connected, recv_data_c, strlen(recv_data_c), 0);
   recv_data_c[bytes_recieved-1] = '\0';
   fputs(recv_data_c, appcrt);
   if(strcmp(enof,recv_data_c) == 0){break;}
}while(check<count);

The text file:
Necessary data
that is
being transmitted
to be written to the file
endoffile

The code used for reading from the txt file and sending to the server:
while (fgets(line, sizeof(line), crt) != NULL)
{
    send(sock, line, sizeof(line), 0);
}

What change I have to make in the condition so that the problem is resolved and the code exits from the do....while(); loop. Thanks in advance.
Operating platform: Linux
Edit1: Edited the do....while() as follows:
do
    {
       rewind(appcrt);
       bytes_recieved = recv(pass_arg.connected, recv_data_c, 100, 0);
       recv_data_c[bytes_recieved] = '\0';
       fputs(recv_data_c, appcrt);
       printf("%s-%s",enof,recv_data_c);
       //if(strcmp(enof,recv_data_c) == 0){break;}
    }while(check<count);

Got the following output in terminal:
endoffile-file1line1
endoffile-file1line2
endoffile-file1line3
endoffile-file1line4
endoffile-file1line5
endoffile-file1line6
endoffile-endoffile
endoffile-file2line1
endoffile-file2line2
endoffile-file2line3
endoffile-file2line4
endoffile-file2line5
endoffile-file2line6
.
.
.

Still no hope.

A: Even though the client is writing a line at a time to the socket this is not how the server will consume it as data transferred over a socket is just a stream of bytes. The server must read up to the next new line character and then compare. A simple algorithm would read a byte at a time and check if it is the newline character and if is not then append it to a string until a newline character is read:
/* Read next line. */
memset(line, 0, sizeof(line));
size_t line_len = 0;
while (line_len < sizeof(line) - 1 &&
       1 == recv(pass_arg.connected, &line[line_len], 1, 0))
{
    if ('\n' == line[line_len]) break;
    line_len++;
}

Apart from that, there are several problems with the code:

*

*you need to send what was read from the file as it may be less than the sizeof(line). Change:
send(sock, line, sizeof(line), 0);

to:
send(sock, line, strlen(line), 0);

and also check the return value of send() to determine if it was successful.

*the following is incorrect as it would only read at a maximum what was previously read (or if was initialised to an empty string nothing would be read):
bytes_recieved = recv(pass_arg.connected,
                          recv_data_c, strlen(recv_data_c), 0);

and, again, check the return value especially as the return value is being used to index an array. If recv() fails it returns -1, which will result in out of bounds access on the array causing undefined behaviour.

A: while (fgets(line, sizeof(line), crt) != NULL)
{
    send(sock, line, sizeof(line), 0);
}

Don't forget that fgets() may only read one byte, if the line is blank. Thus your send() call is sending a lot of uninitialized data every call -- either contents of previous lines or random memory free()d by your application earlier.
Thus, your receiving program would need to compare against:
endoffiletten to the file

to finally see the final string. (Assuming that the line buffer started out full of ASCII NUL characters.)


text:
Q: My PHP Manual Examples Are Tiny The example code in the PHP manuals that I downloaded recently (June 2019 and Sept? 2018) are so tiny that I cannot read them.
The 2009 manual is fine.
What could be the problem?
See attached screenshot:Help file screenshot

A: Do this:

*

*Open PHP Manual CHM file

*Go to Options > Internet Options > General Tab

*Click on the Accessibility button

*Check the option of "Ignore font sizes specified on webpages"

*Press OK.

Note that this may have effect on the display of web-pages in Internet Explorer,
but you may undo it when not reading the manual.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kops/Kubernetes instance group autoscaling I have a Kubernetes cluster running in AWS. I used kops to setup and start the cluster.
I defined a minimum and maximum number of nodes in the nodes instance group:
apiVersion: kops/v1alpha2
kind: InstanceGroup
metadata:
  creationTimestamp: 2017-07-03T15:37:59Z
  labels:
    kops.k8s.io/cluster: k8s.tst.test-cluster.com
  name: nodes
spec:
  image: kope.io/k8s-1.6-debian-jessie-amd64-hvm-ebs-2017-05-02
  machineType: t2.large
  maxSize: 7
  minSize: 5
  role: Node
  subnets:
  - eu-central-1b

Currently the cluster has 5 nodes running. After some deployments in the cluster, pods/containers cannot start because there are no nodes available with enough resources.
So I thought, when there is a resource problem, k8s scales automatically the cluster and start more nodes. Because the maximum number of nodes is 7.
Do I miss any configuration?
UPDATE
As @kichik mentioned, the autoscaler addon is already installed. Nevertheless, it doesn't work. Kube-dns is also often restarting because of resource problems.

A: Someone opened a ticket for this on GitHub and it suggests you have to install the autoscaler addon. Check if it's already installed with:
kubectl get deployments --namespace kube-system | grep autoscaler

If it's not, you can install it with the following script. Make sure AWS_REGION, GROUP_NAME, MIN_NODES and MAX_NODES have the right values.
CLOUD_PROVIDER=aws
IMAGE=gcr.io/google_containers/cluster-autoscaler:v0.5.4
MIN_NODES=5
MAX_NODES=7
AWS_REGION=us-east-1
GROUP_NAME="nodes.k8s.example.com"
SSL_CERT_PATH="/etc/ssl/certs/ca-certificates.crt" # (/etc/ssl/certs for gce)

addon=cluster-autoscaler.yml
wget -O ${addon} https://raw.githubusercontent.com/kubernetes/kops/master/addons/cluster-autoscaler/v1.6.0.yaml

sed -i -e "s@{{CLOUD_PROVIDER}}@${CLOUD_PROVIDER}@g" "${addon}"
sed -i -e "s@{{IMAGE}}@${IMAGE}@g" "${addon}"
sed -i -e "s@{{MIN_NODES}}@${MIN_NODES}@g" "${addon}"
sed -i -e "s@{{MAX_NODES}}@${MAX_NODES}@g" "${addon}"
sed -i -e "s@{{GROUP_NAME}}@${GROUP_NAME}@g" "${addon}"
sed -i -e "s@{{AWS_REGION}}@${AWS_REGION}@g" "${addon}"
sed -i -e "s@{{SSL_CERT_PATH}}@${SSL_CERT_PATH}@g" "${addon}"

kubectl apply -f ${addon}


text:
Q: How to prove this inequality for $n$-th derivative: $\left|\frac{d^n}{dx^n}\left(\frac{\sin x}{x}\right)\right|\leq \frac1n$? It's easy to see that $\frac{d^n(\sin x)}{dx^n}=\sin \left(x+\frac{\pi n}{2}\right)$, so the following inequality holds: $$\left|\frac{d^n(\sin x)}{dx^n}\right|=\left|\sin \left(x+\frac{\pi n}{2}\right)\right|\leq 1.$$
I'm interested in proving a similar inequality for the function $\frac{\sin x}{x}$. I suspect that for all $n$
$$\left|\frac{d^n}{dx^n}\left(\frac{\sin x}{x}\right)\right|\leq \frac1n.$$
Unfortunately I don't know any nice expression for this $n$-th derivative which could help. I'll be grateful for all useful suggestions.

A: A hint:
$${\sin x\over x}=\int_0^1\cos(t\,x)\ dt\ .$$


text:
Q: Custom agent image with Kubernetes Jenkins plugin I have been using csanchez's kubernetes-jenkins plugin to run my slave.  Everything works, but now I need a custom agent image.  I have changed the settings for the plugin from the default agent image to mine (in Container Template->Docker image), but when I check the logs in k8s I can see that it is still using the default.
Is this the right place to change it?  Is this a bug?
When I manually add a container based on my image named "jnlp" in the Jenkinsfile it works as expected.  It only uses the default image when I try to change things through the GUI.
I also tried adding a new cloud entry with the correct settings, but that one also does nothing.

A: After doing a lot of research, I discovered the root cause.  I'm adding this to help any future searchers.
The issue is that the plugin won't use your pod template if you're using YAML to define your containers.  If you do not have a container named "jnlp", it silently injects one using the stock image.  It does not matter what you put in the container template in the GUI config.
If you define your pod with yaml, and you want a custom jnlp image, then you must also include that container definition in your spec and it must be named "jnlp".
As an alternative, you can just use the pipeline syntax and not yaml.  In this case, it will inherit from the template.  Note that this only works in specific cases:
a) You can use the scripted pipeline.  I haven't tested this, but according to my research this will work without restrictions.
b) You can use the declarative pipeline, but only if you have one container (not counting jnlp).  If you want to use the declarative pipeline with multiple containers, then you must use yaml.


text:
Q: Is there a simple way to implement routing in JSF? I am trying to implement a "generic" view where (part of) the content displayed depends on the URL. E.g.
If /somepath/somepage.xhtml points to a non existing file, instead of going straight to a 404 error I want to try to retrieve /somepath/somepage.xhtml's content from the database using a generic view, /genericview.xhtml, where I have something like:
<h:outputText value="#{genericViewBean.content_lg}"
                escape="false" />

which, if found by the backing bean, would output the content of the database entry from a tgenericcontent table, depending on the originally requested viewId:
 webpath                              | content
 /somepath/somepage.xhtml             |
This is a test

 /someotherpath/someotherpage.xhtml   |
A different test

If the view content is not found in that table then the standard 404 error would be returned.
The closest I got wast to clone /genericview.xhtml changing only the file path (for example, to /somepath/somepage.xhtml). But that gets me one exact copy of the file per view, it is quite messy, and it doesn't allow me to create a new url just by adding an entry to my database.
How can I get the same result without cloning /genericview.xhtml?
(P.S: I have read about prettyfaces, but isn't there a simpler solution?)

A: For that, normally a servlet filter is being used. PrettyFaces, UrlRewriteFilter and FacesViews also do it that way.
You can get the request URI by HttpServletRequest#getRequestURI(). You can check the existence of a web resource by ServletContext#getResource() which will return null on non-existent resources. If the resource exists, just continue the request by FilterChain#doFilter(), else forward the request to the generic view by RequestDispatcher#forward().
All in all, this is how the filter could look like:
@WebFilter("/*")
public class GenericViewFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String relativeRequestURI = request.getRequestURI().substring(request.getContextPath().length());

        boolean resourceExists = request.getServletContext().getResource(relativeRequestURI) != null;
        boolean facesResourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER));

        if (resourceExists || facesResourceRequest) {
            chain.doFilter(request, response);
        }
        else {
            request.getRequestDispatcher("/genericview.xhtml").forward(request, response);
        }
    }

    // ...
}

In the /genericview.xhtml, the original request URI is available as request attribute keyed with RequestDispatcher#FORWARD_REQUEST_URI. You could use it in @PostConstruct of backing bean associated with the view in order to pull the right content from the DB.
String originalRequestURI = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
// ...


text:
Q: Hibernate search 6 , refresh index after updating entity I didn't find unfortunatly a solution for my Problem and I need help.
I have tow entity like that
@Table(name = "A")
@Entity
@Indexed
@Getter
@Setter
@NoArgsConstructor
public class EntityA {

    @IndexedEmbedded
    @OneToOne(cascade = CascadeType.ALL)
    private EntityB b;
}

@Table(name = "B")
@Entity
@Indexed
@Getter
@Setter
@NoArgsConstructor
public class EntityB {

    @OneToOne(mappedBy = "b")
    private EntityA a;

    @KeywordField(name = "text_sort", sortable = Sortable.YES)
    @FullTextField(projectable = Projectable.YES)
    @Column(nullable = false)
    private String text;

}

I make a first save for my EntityA
EntityB entityB = new EntityB();
entityB.setText("text");
EntityA entityA = new EntityA();
entityA.setB(entityB);
entityARespository.save(entityA);

then I want to update the field text in the entityB, so I get first the entityA from the database and then make the update and save the entityA
EntityA entityA = entityARepository.findById(1L);
entityA.getB().setText("test")
entityBRepository.save(entityA);

then when I make a research with the string "test" and don't find any result, but with string "text" yes . That's mean the index ist not refreshed but I didn't find where the problem is

A: Two possible explanations:

*

*Your update to the value test is done outside of a transaction. Make sure to use a transaction, or if you really don't want one, call entityManager.flush() (entityBRepository.flush() with Spring Data, I suppose?) after the call to save().

*You didn't wait long enough for the update to be visible. Elasticsearch is a near-real-time platform. This means your updates are not visible immediately, but after a periodic "refresh", which happens every second by default.
See here for more information about the concept of "refresh".
You can configure Hibernate Search to force a refresh after each index update by using the sync synchronization strategy, but then Elasticsearch's performance will be poor. I would only recommend that for automated tests, definitely not in production.


text:
Q: Play random audio file on click JavaScript not working I am using the following code to play a random audio file (files named from 1.wav to 15.wav) The variable 'file' is displaying random files. But on each mouse click they are playing the same file
$(document).ready(function() {
    $("body").click(function() {

        function explode() {
            var file = Math.floor(Math.random() * 14) + 1 + '.wav';
            var audioElement = document.createElement('audio');
            audioElement.setAttribute('src', file);
            audioElement.setAttribute('autoplay', 'autoplay');
            //audioElement.load()

            $.get();
            audioElement.addEventListener("load", function() {
                audioElement.play();
            }, true);
        }
        setTimeout(explode, 5000);
    });
});


text:
Q: Enabling and Disabling DataGridView button cell I have made a DataGridView in a Windows Form with the Name serverListand then added a selection of columns then at the end of each row I have added a button cell using this code
DataGridViewButtonColumn deleteBtn = new DataGridViewButtonColumn();
                deleteBtn.HeaderText = "Delete";
                deleteBtn.Text = "Delete";
                deleteBtn.Name = "deleteBtn";
                deleteBtn.UseColumnTextForButtonValue = true;
                serverList.Columns.Add(deleteBtn);

is there a way for me to grey this button out or make it so the user can't click it?
EDIT:
I check when the button is clicked with this method:
private void serverList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        switch (e.ColumnIndex)
        {
            case 8:
                try
                {
                    string filePath = @"C:\ProgramData\Server_Manager\default.xml";
                    int serverIndex = Int32.Parse(serverCell);

                    XmlDocument doc = new XmlDocument();
                    doc.Load(filePath);
                    XmlElement nodeToDelete = (XmlElement)doc.SelectSingleNode("/Servers/Server[serverIndex="+serverIndex+"]");
                    if (nodeToDelete != null)
                    {
                        nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
                    }
                    doc.Save(filePath);

                    clearList();
                    populateList();
                }

                catch (Exception ex)
                {
                    string errorMsg = "Unable to Delete Nodes from XML:  " + ex;
                    errorBox(errorMsg, "Failed to Delete List Item", "error");
                }

                break;

A: The Property you are looking for should be found under "deleteBtn.Enabled", possible Values are true/false.
You can set this property at any time in your code.

A: Solution:
Rather than disable the button I instead created an error when the button is clicked:
MessageBox.Show("Server Currently Being Edited by Another User");

A: I went a different route with this as I couldn't find an answer anywhere when using the CellContentClick event.
I used an int List to store e.index when the button was clicked and the process successfully began (from a Y/N message box).
When CellContentClick is entered I first check to see if the row index was in the list and to not show the message box again to begin processing until the process finished. I also disabled the button so it greyed out on the form.
When it the process finishes, the button is enabled again and e.index is removed from the List.


text:
Q: jquery array returning one undefined? I am trying to get an array out of this html code to add boxes, having the numbers in their id, to my content:
An Array

The boxes to add:

    ...

    ...

    ...

As there are also html lines like this:
No Array

I also need something that detects if there are multiple values or just one. In this case I just used if (theid.length > 2) because the single values won't get longer then two characters.
The array should be [38,39,49] and it is, as console.log(theid); returns exactly this array.
var theid = $(this).data('box');
var newHTML = '';

if (theid.length > 2) {
    theid = theid.split(',');
    $.each(theid, function(idx) {
        newHTML += $('#box' + theid[idx]).html();
    });
} else {
    var newHTML = '';
    newHTML = $('#box' + theid).html();
    console.log(theid);
};

But if I then add newHTML to my existing content content.html(newHTML); there is always an "undefined" in front of the loaded boxes? Here's a screenshot:

A: This is a byproduct of variable hoisting. Since you are using the += operator the string is being appended to the end of the variable newHTML which previously held undefined. You can look at it like this:
//hoisted
var newHTML = undefined;

var theid = $(this).data('box');

if (theid.length > 2) {
 theid = theid.split(',');
 $.each(theid, function(idx) {
    newHTML += $('#box' + theid[idx]).html();
 });
} else {
 /*var */newHTML = '';
 newHTML = $('#box' + theid).html();
 console.log(theid);
};


text:
Q: How to make basic 2D flip-clock in unity I saw a mobile game called Township. There was a flip-clock based animation in that game. I was wondering how to make that flip-clock in unity.
Can anyone please help me.


text:
Q: Is there a package or function that will make a reasonable guess at the mode/type/class of a vector? Does R have some automatic type detection? Perhaps in a CRAN package?
The specifically, when R loads data (from a text file), it would be nice if R could make some reasonable assumptions about Types and/or automatically coerce them.
I know that you could possibly do something like:
try( as( x, "..." ) )

And try various types.  I would think that there is a better way.
Also, note, I am not looking to coerce into objects.  The basic data types is all: numeric, integer, character, POSIXct, ...

A: I am answering my own questions for book-keeping reasons, though the answer came in the comments from @mdsummer:
Use type.convert.  See ?type.convert for details.


text:
Q: Access-Control-Allow-Origin error with JavaScript I'm trying to load a bit of content onto sites that I browse to using a simple Javascript bookmarklet. Since I'm hoping to make this usable by anyone and not just me, I make a get request that has a unique identifier associated with the bookmarklet, like so:
$.get("http://www.mysite.com/dothis.php?id=1234", {}, function(data) {
   $("body").append(data);
});

The trouble is that I get
XMLHttpRequest cannot load http://www.mysite.com/dothis.php?id=1234. Origin http://www.google.com is not allowed by Access-Control-Allow-Origin.

The issue seems that I can recognize the request (dothis.php can save the fact that I made the get request to a database, for example) but it cannot return any data back to the requester. It makes sense, but is there some way around it? iFrames won't work because I'll need to act upon that returned data, too, eventually.
Thanks!

A: In your PHP script you can allow Access-Control-Allow-Origin from every website. Just put
<?php header("Access-Control-Allow-Origin: *"); ?>

to the very beginning of your php file. I haven't tested this, but it ought to work.


text:
Q: Something wrong with some batch file stuff, doesn't do what it should do, cant spot syntax errors So, I am writing a computer speeder in batch, and I am baffled by this problem:
@echo off
cls
color 02
:licence
title Computer Speeder 2012 (Free licence)
cls
echo This is the free version of Computer Speeder 2012.
echo.
echo Do you wish to license this copy? [Y]es or [N]o.
choice /c NY /n
if ERRORLEVEL 2 goto license
if ERRORLEVEL 1 goto startup1
:license
dir | find "validatecode.txt" > if exist "validatecode.txt"
goto bam
) else (
goto else
:bam
cls
echo Type in your lisencing code to validate this
echo copy to upgrade to the full version:
echo.
set /p vd=""
:else
cls
echo You do not have a validation file on your computer,
echo if you purchased the full version you probably
echo deleted the file. Check the recycle bin, check you
echo put it in the correct path or re-purchase the
echo software because it has an individual code.
pause
goto startup1

For some odd reason, it executes all of this code chronologically:
First it asks if you want to license the copy of the software. If you press Y it takes you  to license. It then performs the line dir | find "validatecode.txt" >if exist "validatecode.txt"
so on and so forth. However, it goes to bam and THEN goes to else. There's no other flaw in the code, I cant find any syntax error, can you guys explain what I am doing wrong? Im a noob kinda :/

A: If you want the program to stop after executing :bam, you should put a
goto:EOF after set /p vd=".
:bam
cls
echo Type in your lisencing code to validate this
...
set /p vd=""
goto:EOF

:else
cls
...

A: Try replacing this:
:lisence
dir | find "validatecode.txt" > if exist "validatecode.txt"
goto bam
) else (
goto else

with this:
:lisence
if exist "validatecode.txt" goto bam
goto else

Explanation:
You would need to test an errorlevel of the Find process for your code to possibly work, and the redirector '>' only creates a file called 'if', containing, oddly, the words exist and vaildatecode.txt.
Your DIR command will only look in the execution directory, but your 'bam' subroutine implies you intend to search the hard drive?  True?  If so, my 'if exist' command should be changed to:

dir /s/b validatecode.txt && goto bam

You  appear to not be using information inside the file, so if you need to search the entire hard drive this command will perform it, and will logically go to the correct subroutine.
The snippet provided tests for a file called validatecode.txt in the local directory, and executes a goto to the label bam if it is found.  If the file does not exist, focus drops to the next line, which performs a goto to the label :else.
You will need to finish your script differently as well.  As it stands, if the validatecode.txt is found, you will be executing both 'bam' and 'else'.  You should place a final label like :exit (:eof is reserved) and make a goto :exit command as the last line of each subroutine.
Finally, your call to the subroutine Startup1 will always fail because you have no label called Startup1.
From a flow standpoint, it looks like you have no way to exit if the user does not want to license the copy they are using.


text:
Q: How to get data from prop.location.state in react? I try to send data through history push like that.

And then I try to get the value of id that I send.

The problem is when the first time rendering of component, I got the value of undefined.
And then when I click the previous button on browser then I got the value.
Why could be happened ???

A: Default state is missing, so use componentDidMount life cycle and inside componentDidMount call default state.

A: send params in the url.
Define the route

<Route path="/bookingform/:id" component={BookingForm} />

and then in the component you can get the id by
props.match.params.id

A: It would help if I could see how you're writing your  component.
to make this code work, this should help.
<Route exact path="" render= {routeProps => (<theComponent {...routeProps} />)}

A: You can pass a state to push method as the second parameter, push(url, state) not push({ pathname, state}) .Example below
// Home.jsx
const Home = (props) => {
  // the second value in push method is the state
  handClick = () => props.history.push('/login', { comingFromHome: true })
  return <HomeBigOrSmallComponent onClick={handleClick} />
}

then, access the state
// Login.jsx
const Login = (props) => {
  // now let's log our state
  useEffect(() => console.log(props.history.location.state.comingFromHome), [])

  return <LoginBigOrSmallComponent onClick={handleClick} />
}

History objects typically have the following properties and methods:

*

*length - (number) The number of entries in the history stack

*action - (string) The current action (PUSH, REPLACE, or POP)

*location - (object) The current location. May have the following properties:

*

*pathname - (string) The path of the URL

*search - (string) The URL query string

*hash - (string) The URL hash fragment

*state - (object) location-specific state that was provided to e.g. push(path,
state) when this location was pushed onto the stack. Only available in
browser and memory history.

*push(path, [state]) - (function) Pushes a new entry onto the history stack

*replace(path, [state]) - (function) Replaces the current entry on the history
stack

*go(n) - (function) Moves the pointer in the history stack by n entries

*goBack() - (function) Equivalent to go(-1)

*goForward() - (function) Equivalent to go(1)

*block(prompt) - (function) Prevents navigation (see the history docs)


text:
Q: PasswordBox with DataTrigger and secure If it right to bind the value of passwordBox in datatrigger
 <DataTrigger Binding="{Binding ElementName=password, Path=Password}" Value="">
     <Setter Property="IsEnabled" Value="false" />
 </DataTrigger>

PasswordBox field
 <PasswordBox x:Name="password" PasswordChanged="Password_PasswordChanged" Style="{StaticResource passwordStyle}" />

and style resource
<Style TargetType="PasswordBox" x:Key="passwordStyle">
        <Setter Property="Width" Value="190"/>
        <Setter Property="Height" Value="30"/>
        <Setter Property="FontSize" Value="20"/>
        <Setter Property="Padding" Value="6,1,1,0"/>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type PasswordBox}">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Background="{TemplateBinding Background}"
                                CornerRadius="10"
                                SnapsToDevicePixels="True">
                        <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

I send the password by interface without binding to ViewModel, for doesn't keeps the password exposed in memory
For passwordbox i need block button if the field empty in first app start, because the event PasswordChanged doesn't do that.
but if i bind in trigger it breake this logic or not?
if it right way or may no? if consider the memory.


text:
Q: Copy path file with NERDtree Vim plugin Is there some way to copy the path of a file in the Vim's NERDtree plugin?
Better: is there some plugin to make the same operations the SideBarEnhancements plugin of Sublime Text does?

A: This is what I found for NERDTree with a quick google: CopyPath
However it sounds like you are trying to make vim into Sublime Text. Vim tends to have a very different philosophy on text editing than most text editors. In my personal opinion it is often better to work with vim than against it. Here is a nice post by Drew Neil of Vimcasts explaining the benefit to split explorers.
Probably the more vim way of inserting a path is to use file completion. When in insert mode you can trigger this completion by pressing <c-x><c-f> then go through the menu with <c-p> and <c-n> (previous and next respectively). If you want to insert the current buffers path you can paste it via the % register e.g."%p or in insert/command-line mode press with <c-r>%.
For more help see:
:h ins_completion
:h i_CTRL-R
:h quote%
:h registers

A: I guess what you really need is a context menu like that sublime plugin?
That's built-in with NERDTree.
Just hit m on the node you highlighted and you'll see a new window pop under asking you what you want to do. The basic functions are: Add, Delete, Move, Copy.
There is also a plugin to let you search(using grep), either for single file or whole directory highlighted.
NERDTree also provides API for your easily built any custom actions in that context window.

A: NERD_tree comes with its own extension system; just put the following fragment into ~/.vim/nerdtree_plugin/yank_mapping.vim:
call NERDTreeAddKeyMap({
        \ 'key': 'yy',
        \ 'callback': 'NERDTreeYankCurrentNode',
        \ 'quickhelpText': 'put full path of current node into the default register' })

function! NERDTreeYankCurrentNode()
    let n = g:NERDTreeFileNode.GetSelected()
    if n != {}
        call setreg('"', n.path.str())
    endif
endfunction

Of course, you can adapt the default key (yy), and register ("; use + for the clipboard).


text:
Q: How to insert JSON Array into database I'm using dropdown when selected first dropdown, based on first dropdown selected it will show second dropdown. Each dropdown have data from database and the problem is i want to insert it into new table on database based on dropdown selected.
All the code on the same page, this is the php.
<?php
            $sql= mysql_query("SELECT KodeMapel,NamaTema FROM mapel");
            while ($row = mysql_fetch_array($sql))
            {
                $tema[] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['NamaTema']);
            }

            $query = mysql_query("SELECT KodeMapel, Subtema FROM subtema");

            while ($row = mysql_fetch_array($query))
            {
                $subtema[$row['KodeMapel']][] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['Subtema']);
            }

            $jsonTema = json_encode($tema);
            $jsonSubTema = json_encode($subtema);
        ?>

This is the form, included javascript on it. Inside the javascript there's php code.
<script type='text/javascript'>
  <?php
    echo "var tema = $jsonTema;";
    echo "var subtema = $jsonSubTema;";
  ?>
  function loadtema(){
    var select = document.getElementById("PilihTema");
    select.onchange = updateSubTema;
    for(var i = 0; i < tema.length; i++){
      select.options[i] = new Option(tema[i].val,tema[i].KodeMapel);
    }
  }
  function updateSubTema(){
    var PilihTema = this;
    var idtema = this.value;
    var PilihSubtema = document.getElementById("PilihSubtema");
    PilihSubtema.options.length = 0; //delete all options if any present
    for(var i = 0; i < subtema[idtema].length; i++){
      PilihSubtema.options[i] = new Option(subtema[idtema][i].val,subtema[idtema][i].KodeMapel);
    }
  }
</script>
<body onload='loadtema()'>
<select id='PilihTema' name='PilihTema' class='form-control11'>
</select>

<select id='PilihSubtema' name='PilihSubtema' class='form-control11'>
</select>
<button input class="btn btn-success" id="submit" type="submit" name="add" value="Simpan" onclick="return(submitmapel());"/>
    <i class="fa fa-save fa-fw"></i> Simpan

A: So far I see some errors in your code.
select.onchange = updateSubTema;

You are missing () for the function. Should be select.onchange = updateSubTema();
I'm not sure if var PilihTema = this; will actually select anything, personally i'd do it the following way.
loadTema function:
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema(select.value);

updateTema function
function updateTema(pilihTema){
  //Your code here
}

EDIT: If you mean you want to add an item per run through your for loop, I would suggest doing it the following way (I use jQuery as it is much easier in my opinion):
$(document).ready(function(){
  <?php
    echo "var tema = $jsonTema;";
    echo "var subtema = $jsonSubTema;";
  ?>

  //Load Tema
  $.each(tema, function (i, item) {
  //I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
    $("#PilihTema").append(new Option(item.val, item.KodeMapel));
  });

  //Called when the first select field is changed.
  $("#PilihTema").change(function(){
    //Get value of first select fields' selected item
    var pilihValue = $("#PilihTema option:checked").val();

    //Remove all the options from the second select field
    $("#PilihSubtema").html("");

    //For each subtema, with first select fields value, add option to second select field
    $.each(subtema[pilihValue], function (i, item) {
      //Again, I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
      $("#PilihSubtema").append(new Option(item.val, item.KodeMapel));
    });

  });

});


text:
Q: Event triggered on entering a textbox. Is there any way of knowing when a text-box has been clicked on so that this can trigger an event? This may not be the best way to do it but I want to animate the text-box to a different part of the screen when it is clicked and then return to its original position when finished.

A: If your question related to iOS, Set delegate for the UITextField, and in following delegaqte method, add your code.
- (void)textFieldDidBeginEditing:(UITextField *)textField

Setting delegate


text:
Q: What's the difference between rootkit and RAT? I know that both can give attacker remote access to computer. Is RAT easier to detect than rootkit? Where are they typically get installed? Can one make more damage than another? Which one is easier to remove?

A: From Kaspersky - A Malware Classification

Rootkit:
A rootkit is a special form of malware, designed specifically to hide its presence and actions from both the user and any existing protection software they have installed on their system. It's able to do this via deep integration with the operating system, sometimes even starting before the operating system does (this variety of rootkit has its own name, bootkits). Sophisticated antivirus software is still able to detect rootkits and get rid of them though.
Backdoor (RAT):
A Backdoor, or a Remote Administration Tool, is an application that allows a person (the system administrator or a cybercriminal) access to a computer system without user consent or knowledge. Depending on the RAT functionality, an attacker could install and launch other software, send keystrokes, download or delete files, switch the microphone and/or camera on, or log computer activity and send it back to the attacker.

For the rest of your questions, see How can I remove malicious spyware, malware, adware, viruses, trojans or rootkits from my PC?


text:
Q: how to include time in bootstrap-datepicker is it possible to include time to bootstrap-datepicker because I could not find anything to include time, and if it is not possible what Is the attentive to bootstrap-datepicker that could work with bootstrap 5
here is my code
<input class="datepicker" data-date-format="mm/dd/yyyy">

$('.datepicker').datepicker({
    format: 'mm/dd/yyyy',
    startDate: '-3d'
});

A:
if it is not possible what Is the attentive to bootstrap-datepicker
that could work with bootstrap 5

There are lots of alternatives. But I will recommend flatpickr. It's javascript/CSS framework independent.

// without jquery
flatpickr('.datepicker', {
    // put options here if your don't want to add them via data- attributes
});

// with jquery
// $('.datepicker').flatpickr({ /* options here */ });
<!-- flatpickr CSS and javascript -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<input class="form-control bg-white datepicker" data-date-format="m/d/Y G:iK" data-enable-time="true">


text:
Q: How to add Yes or No option in my java code Ive coded a program that converts numbers/integers to roman numerals but i need a Yes or no option. Pls i need help
import java.util.*;

public class num2roman
{
    public static void main(String...args)
    {

    int ones, tens, hundred;
    int num;

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number [1-1000]: ");
    num = sc.nextInt();

    if (num>0 && num<10)
        {
            ones = num;
            switch(ones)
            {
            case 1:
                System.out.print("I");
            break;

            case 2:
                System.out.print("II");
            break;

            case 3:
                System.out.print("III");
            break;

            case 4:
                System.out.print("IV");
            break;

            case 5:
                System.out.print("V");
            break;

            case 6:
                System.out.print("VI");
            break;

            case 7:
                System.out.print("VII");
            break;

            case 8:
                System.out.print("VIII");
            break;

            case 9:
                System.out.print("IX");
            break;
            }

        }

    else if (num>9 && num<100)
        {
            tens =(num/10);
            ones =(num%10);

            switch(tens)
            {
            case 1:
                System.out.print("X");
            break;

            case 2:
                System.out.print("XX");
            break;

            case 3:
                System.out.print("XXX");
            break;

            case 4:
                System.out.print("XL");
            break;

            case 5:
                System.out.print("L");
            break;

            case 6:
                System.out.print("LX");
            break;

            case 7:
                System.out.print("LXX");
            break;

            case 8:
                System.out.print("LXXX");
            break;

            case 9:
                System.out.print("XC");
            break;
            }

            switch(ones)
            {
            case 1:
                System.out.print("I");
            break;

            case 2:
                System.out.print("II");
            break;

            case 3:
                System.out.print("III");
            break;

            case 4:
                System.out.print("IV");
            break;

            case 5:
                System.out.print("V");
            break;

            case 6:
                System.out.print("VI");
            break;

            case 7:
                System.out.print("VII");
            break;

            case 8:
                System.out.print("VIII");
            break;

            case 9:
                System.out.print("IX");
            break;
            }

        }
    else if (num>99 && num<1000)
        {
            hundred =(num/100);
            tens =((num/10)%10);
            ones =(num%10);

            switch(hundred)
            {
            case 1:
                System.out.print("C");
            break;

            case 2:
                System.out.print("CC");
            break;

            case 3:
                System.out.print("CCC");
            break;

            case 4:
                System.out.print("CD");
            break;

            case 5:
                System.out.print("D");
            break;

            case 6:
                System.out.print("DC");
            break;

            case 7:
                System.out.print("DCC");
            break;

            case 8:
                System.out.print("DCCC");
            break;

            case 9:
                System.out.print("CM");
            break;
            }

            switch(tens)
            {
            case 1:
                System.out.print("X");
            break;

            case 2:
                System.out.print("XX");
            break;

            case 3:
                System.out.print("XXX");
            break;

            case 4:
                System.out.print("XL");
            break;

            case 5:
                System.out.print("L");
            break;

            case 6:
                System.out.print("LX");
            break;

            case 7:
                System.out.print("LXX");
            break;

            case 8:
                System.out.print("LXXX");
            break;

            case 9:
                System.out.print("XC");
            break;
            }

            switch(ones)
            {
            case 1:
                System.out.print("I");
            break;

            case 2:
                System.out.print("II");
            break;

            case 3:
                System.out.print("III");
            break;

            case 4:
                System.out.print("IV");
            break;

            case 5:
                System.out.print("V");
            break;

            case 6:
                System.out.print("VI");
            break;

            case 7:
                System.out.print("VII");
            break;

            case 8:
                System.out.print("VIII");
            break;

            case 9:
                System.out.print("IX");
            break;
            }

        }
    else if (num == 1000)
        {
        System.out.print("M");
        }

    else
        {
            System.out.print("Out of range 1-1000 only!");
        }
 }
 }

A: System.out.print("Enter yes or no");
while (!sc.next().equals("yes") && !sc.next().equals("no")){
    System.out.print("Enter yes or no...");
}

That's basically what you want =)

A: There is a good question to start in stackoverflow.
You should check the program arguments like this :
if(args[0].equalsIgnoreCase("YES")) {
    // Do whatever you want.
}

A: Add the following lines right after num = sc.nextInt();:
if (JOptionPane.showConfirmDialog(null, "Do you want to convert?", "Convert option", JOptionPane.YES_NO_OPTION) == 1) {
            System.out.print(num);
            System.exit(0);
        }

If you choose "No", it just displays the number.
If you choose "Yes" it converts it.


text:
Q: Grafana: Show median request time as value (using @Timed from micrometer) i've using the @Timed Annotation in my SpringBoot Application:
@Timed(value = "stats.myapp.dosomething")
public void doSomething() { ... }

Now I would like to display the average/median processing time in Grafana. So i've used a Stat widget with the following query:
SELECT mean("sum") FROM "stats.myapp.dosomething" WHERE time >= now() - 2d and time <= now() GROUP BY time(2m) fill(none)

But the value still shows 0 :(
I suspect it has to do with all the 0 values. How can I suppress them?

Thank you!


text:
Q: easiest way to do the lightening of the image in this example A really simple question here. We have some static images and would like make them more interesting. One thing would be to lighten them with some type of overlay. For example, mousing over one of the images here:
http://www.cnn.com/interactive/2013/02/world/pope-contenders/index.html (just the lightening effect). What is the easiest strategy to achieve this preferably in jquery?
thx in advance

A: you can do it with css only
.myDiv:hover {
    background-image:url(/path/to/transparent.png); /* width 1px, height 1px, the color and opacity you want*/
    background-repeat:repeat;
}

the problem with opacity is that it wont work in ie7 (maybe also ie8)

A: you have to put two divs inside each other.
alternatively you can also put a picture  inside the container.

here's the css you need:
(i assumed all your images have the same heights and widths as in the link you posted. alternatively you can set relative (in %) css properties.)
.img-container {
  position: relative;
  width: 100px; /* your images widths */
  height: 200px; /* your images heights */
  background: url('path/to/your/image.png');
}

.img-overlay {
  position: absolute;
  z-index: 5; /* it has just to be one more than the one above */
  width: 100px; /* your images widths */
  height: 200px; /* your images heights */
  display: none;
  background-color: '#333333'; /* your color of choice */
  opacity: 0.8;
}

do it with jQuery:
$('.img-container').mouseEnter(function() {
    $(this).children('.img-overlay').fadeIn('fast');
}).mouseLeave(function() {
    $(this).children('.img-overlay').fadeOut('fast');
});

keep in mind that you should use vendor prefixes and filter for IE to make this work in older browsers. ensure also to deactivate it for very old IE and Safari versions.

A: This kind of effect can be easily achievable with css itself.
Try this piece of css.
img
{
opacity:1.0;
}
img:hover
{
opacity:0.4;
}

For IE8 and later use
filter:alpha(opacity=x);

A: Opacity won't actually make the hover state "lighter" when applied to the element itself. What you could do is either negative margin or z-index a white div to overlay the img. This way you truly get a white fade on hover. Below should serve as a fix to always achieve the "lighten" effect even w/o a white bg.
See this working fiddle
HTML

Just Opacity

With an overlay

CSS
body {
    background: #262626;
}
h3 {
    color: white;
}
a:hover.one {
    opacity: .5;
}
.two {

}
a.three {
    width: 252px;
    height: 250px;
    background: #FFF;
    display: block;
    margin: -254px 0 0 0;
    position: relative;
    opacity: .0;
}
a:hover.three {
    opacity: .7;
}


text:
Q: Oracle: How to Save result of query on Unix layer How Can I save the result of the query onto the Unix filesystem. If its possible I need step by step process.
What I have done.
created a directory in Unix filesystem.
created a directory in oracle pointing it towards Unix filesystem directory.
tried to spool the result to Unix filesystem But it dosent work for some reasons.
would appreciate if any 1 helps .
working on client windows xp.
Environment :oracle 11g and
application: TOAD for oracle 11.

A: 1st. Create the directory in Unix filesystem (not under your name otherwise it wont work ) then chmod 777 <dir_path> .
2nd Create a directory in oracle
CREATE OR REPLACE DIRECTORY <dir_name> AS '<dir_path>';

Now to Test it
create or replace procedure  WRITEFILE is
       fh UTL_FILE.FILE_TYPE;
       dir VARCHAR2(30) := '<dir_name>';
       name VARCHAR2(30)  := 'test1';
    begin

       fh := UTL_FILE.FOPEN(dir, name, 'w');
       UTL_FILE.PUT_LINE(fh, 'bla bla');
       UTL_FILE.FCLOSE(fh);
    end;

A: You can use External table unload. this will create a dump file of the query results in datapump format (you can import this file using impdp)
In order to do it create and external table who's type is ORACLE_DATAPUMP.
here is an example:
SQL>
SQL>
SQL>
SQL> CREATE TABLE emp_ext
ORGANIZATION EXTERNAL
(
 TYPE ORACLE_DATAPUMP
 DEFAULT DIRECTORY EXPORT
LOCATION ( 'emp_ext.dmp' )
 )
 AS SELECT * FROM SCOTT.EMP;

Table created.

SQL> select count(*) from emp_ext;

  COUNT(*)
----------
        18

SQL> !ls /export/home/oracle/export
 EMP_EXT_13392.log  emp_ext.dmp


text:
Q: Is there any way to suppress a sent SMS message from appearing on the sending phone? I'm using the following code to send a SMS message in the background using Plugin.Messaging:
    public async void SendSMS(string pMessage, string pPhoneNumber)
    {
        try
        {
            var smsMessenger = CrossMessaging.Current.SmsMessenger;
            if (smsMessenger.CanSendSmsInBackground)
                smsMessenger.SendSmsInBackground(pPhoneNumber, pMessage);
        }
        catch (Exception ex)
        {
            Utils.LogError("App: OMLAndroid (TextMessage.cs) - An error occurred when trying to send a text, the error is: " + ex.Message);
        }
    }

Once the permissions are set properly, the SMS gets sent with no issues. Because there's a possibility that a user can send a lot at once, is there anyway I can suppress the display of the message in the messages app?
I can see hundreds of copies the same message being displayed with all the different numbers, all the answers I've seen suggest no unless your app is set as the default message system. I don't want the users to have to do that, but if there's no other way, it is what it is and I can instruct users to workaround that by setting my app as the default temporarily (ugly).


text:
Q: Hopf invariant of composition of functions Given two functions $f: S^{2p-1} \to S^p$ and $g: S^{p} \to S^{p}$, I want to prove that
\begin{equation}
H(f) = (\text{deg}(g))^2 H(f),
\end{equation}
where $H(f)$ is the Hopf invariant of $f$. I first tried to analyze the problem by assuming that $g$ preserves orientations. That is if $y \neq z$ are two distinct regular values of $g \circ f$ and since $(g \circ f)^{-1}(w) = \coprod_{u \in g^{-1}(w)} f^{-1}(u)$, then
\begin{equation}
\begin{split}
H(g\circ f) & = l\left((g \circ f)^{-1}(y),(g \circ f)^{-1}(z)\right)
\\ &= l\left(\coprod_{x \in g^{-1}(y)} f^{-1}(x), \coprod_{u \in g^{-1}(z)} f^{-1}(u)\right) \\ & = \sum_{x \in g^{-1}(y)} \sum_{u \in g^{-1}(z)} l\left( f^{-1}(x),f^{-1}(u)\right) \\ & = \sum_{x \in g^{-1}(y)} \sum_{u \in g^{-1}(z)} H(f) \\ & = H(f) \sum_{x \in g^{-1}(y)} \sum_{u \in g^{-1}(z)} 1 \\ & = H(f) \; (\text{deg}(g))^2.
\end{split}
\end{equation}
The sixth equality holds if $g$ preserves orientations. Here $l$ represents the linking number.
Is the above correct?
This was my idea to solve the problem in the case that g preserves orientations; however, in the general case I am stuck. This is problem 15 of Milnor's Topology from the Differentiable Point of View.


text:
Q: How to get a "item" if I created it on the code     Public WithEvents newListBox As Windows.Forms.ListBox
        newListBox = New Windows.Forms.ListBox
    newListBox.Name = "ListBox" & i
    newListBox.Height = 44
    newListBox.Width = 250
    newListBox.Top = 10 + i * 50
    newListBox.Left = 150
    newListBox.Tag = i
    Me.Controls.Add(newListBox)

So I created a button that create a listbox and I set a name for each listbox while created.
This listbox are filled with files that I select, but how can I get the values from a especified listbox like.
For Each nome In ListBox1.Items

...
If I cant call ListBox1 on the main code cuz its not created yet.
So what should I do ? How can I get the right listbox insted of the last one created.

A: Your problem is that the compiler can't know about ListBoxi at compile time. It is not created until runtime.
Friend WithEvents newListBox As ListBox

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Static i As Integer = 1
    newListBox = New ListBox
    newListBox.Name = "ListBox" & i
    newListBox.Height = 44
    newListBox.Width = 250
    newListBox.Top = 10 + i * 50
    newListBox.Left = 150
    newListBox.Tag = i
    Me.Controls.Add(newListBox)
    i += 1
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim listBoxi = TryCast(Controls.Find("ListBox1", True).FirstOrDefault(), ListBox)
    For Each item In listBoxi.Items

    Next
End Sub


text:
Q: How can I get multiple instances of an associative Array? I'm doing a GET request. I need 'groups' to be have multiple instances of the same associative array ('time'=>string,'sessions'=>array()). My frontend works with this specific .json structure.
I've used array_push inside the while loop. I also tried building a temporary array and then push it, but the last array I push overwrites the last one.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once '../objetos/token.php';
include_once '../objetos/log.php';
include_once '../objetos/agenda.php';
$idLogAccion = 16;

//Leo los parametros

// instantiate database and product object
$database = new Database();
$db = $database->getConnection();

// initialize object
$miAgenda = new agenda($db);

$respuesta_arr=array();
$respuesta_arr["schedule"]=array();
$respuesta_arr["speakers"]=array();

$groups_arr["groups"]=array();
$respuesta_arr["schedule"]["date"]="2018-05-17";
$respuesta_arr["schedule"]["groups"]=array('time'=>'','sessions'=>array());

$listaEventos = $miAgenda->obtenerEventos();
$numeroEventos = $listaEventos->rowCount();

$listSpeakers = $miAgenda->obtenerOradores();
$numeroSpeakers = $listSpeakers->rowCount();

if($numeroSpeakers>0){

    // retrieve our table contents
    while ($row = $listSpeakers->fetch(PDO::FETCH_ASSOC)){

        // extract row
        extract($row);

        $speakers_item=array(
            "idEvento" => $idEvento,
            "nombre" => $nombre." ".$apellido,
            "fotoPerfil" => $fotoPerfil,
            "mail" => $mail
        );

        array_push($respuesta_arr["speakers"],$speakers_item);

    }

    //$stmt = $milog->logear($idUsuario, $idLogAccion,$versionApp);

}
$listSpeakers = $miAgenda->obtenerOradores();

$rowSpeakers = $listSpeakers->fetchAll(PDO::FETCH_ASSOC);

if($numeroEventos>0){

    //$respuesta_arr["schedule"]["date"]='asd';

    // retrieve our table contents
    while ($rowEvento = $listaEventos->fetch(PDO::FETCH_ASSOC)){

        // extract row
        extract($rowEvento);
        $eventos_item=array(
            "id" => $idEvento,
            "idCongreso" => $idCongreso,
            "timeStart" => $horarioComienzo,
            "description"=> "Mobile devices, etc.",
            "timeEnd" => $horarioFin,
            "location" => $sala,
            "name" => $nombreEvento,
            "idDia" => $idDia,
            //"hora" => $hora,   // NO NECESITO LA HORA ACA
            "speakerNames" => array()
        );

        // agregamos los speakers
        if($numeroSpeakers>0){

            // retrieve our table contents
            $speakerTmp=array();
                foreach($rowSpeakers as $row) { //por cada registro en rowSpeakers

                    if ($row['idEvento'] == $rowEvento['idEvento']){ //Si el speaker tiene idEvento igual a idEvento de este evento

                        $speakerTmp=$row['nombre']." ".$row['apellido'];

                    array_push($eventos_item["speakerNames"],$speakerTmp);  //Lo agrego al array de speakers
                    }

                }
                if($horaPrev!=$hora){
                    $respuesta_arr["schedule"]["groups"]["time"]=$hora;

                        // print_r("Same Time");

                    }
                if($horaPrev!=$hora && $horaPrev!=null){
                    $respuesta_arr["schedule"]["groups"]["time"]=$hora;

                    // print_r("New Time");

                }

                $horaPrev=$hora;

            }
            array_push($respuesta_arr["schedule"]["groups"]["sessions"],$eventos_item);

            //array_push($groups_arr["groups"],$eventos_item);  // TODO: cargar uno por uno, no el array entero
        }

        //TODO: Divido por horas

}

http_response_code(200);
echo json_encode($respuesta_arr);

?>

Expected results
{
    "schedule": {
        "date": "2018-05-17",
    "groups": [{
      "time": "8:00 am",
      "sessions": [{
            "id": "1",
            "idCongreso": "1",
            "timeStart": "08:00:00",
            "description": "Mobile devices, etc.",
            "timeEnd": "09:00:00",
            "location": "condor",
            "name": "Maternidad deseada",
            "idDia": "1",
            "speakerNames": [
                "apellido1 usuario1",
                "apellido2 usaurio2"
            ]
        }]
    },{

        "time":"22:00 PM",
        "sessions": [{
            "id": "2",
            "idCongreso": "1",
            "timeStart": "22:30:00",
            "description": "Mobile devices, etc.",
            "timeEnd": "13:00:00",
            "location": "condorito",
            "name": "Legal y clandestino",
            "idDia": "2",
            "speakerNames": [
                "apellido1 usuario1",
                "apellido3 Usuario3"
            ]
        }]

    }
    ],
    "speakers": [
        {
            "idEvento": "1",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "1",
            "nombre": "apellido2 usaurio2",
            "fotoPerfil": null,
            "mail": "1235"
        },
        {
            "idEvento": "2",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "2",
            "nombre": "apellido3 Usuario3",
            "fotoPerfil": null,
            "mail": "1236"
        }
    ]
  }
}

Actual results
{
    "schedule": {
        "date": "2018-05-17",
        "groups": {
            "time": "22:00 PM",
            "sessions": [
                {
                    "id": "1",
                    "idCongreso": "1",
                    "timeStart": "08:00:00",
                    "description": "Mobile devices, etc.",
                    "timeEnd": "09:00:00",
                    "location": "condor",
                    "name": "Maternidad deseada",
                    "idDia": "1",
                    "speakerNames": [
                        "apellido1 usuario1",
                        "apellido2 usaurio2"
                    ]
                },
                {
                    "id": "2",
                    "idCongreso": "1",
                    "timeStart": "22:30:00",
                    "description": "Mobile devices, etc.",
                    "timeEnd": "13:00:00",
                    "location": "condorito",
                    "name": "Legal y clandestino",
                    "idDia": "2",
                    "speakerNames": [
                        "apellido1 usuario1",
                        "apellido3 Usuario3"
                    ]
                }
            ]
        }
    },
    "speakers": [
        {
            "idEvento": "1",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "1",
            "nombre": "apellido2 usaurio2",
            "fotoPerfil": null,
            "mail": "1235"
        },
        {
            "idEvento": "2",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "2",
            "nombre": "apellido3 Usuario3",
            "fotoPerfil": null,
            "mail": "1236"
        }
    ]
}

A: you have one array
$respuesta_arr=array();

now you add groups schedule and speakers:
$respuesta_arr["schedule"]=array();
$respuesta_arr["speakers"]=array();

now you add the nested data:
$respuesta_arr["schedule"]["date"]="2018-05-17";
$respuesta_arr["schedule"["groups"]=array();

now add the groups data
$respuesta_arr["schedule"]["groups"][] = array('time'=>'','sessions'=>array())

you can do it at once if you like:
 $respuesta_arr = array(
    "schedule" => array(
      "date" => "2018-05-17",
      "groups" => array(
         array('time'=>'','sessions'=>array()),
         array('time'=>'','sessions'=>array())
       )
     ),
    "speakers" => array()
 );

you had 2 mistakes: $groups_arr and you have to nest arrays with array(array(...)) or []. you could also have a look at the docs: https://www.php.net/manual/en/language.types.array.php


text:
Q: Elementary Direct Product Question Here is the problem I'm working on.
Let $G,H$ be groups. Let $\Gamma = \{(g,e_{H}) | \ g \in G\}$ and $\Sigma = \{(e_{G},h) | \ h \in H\}$. Show that for any $x = (g,h) \in G \times H$ we have $x\Gamma x^{-1} = \Gamma$ and $x\Sigma x^{-1} = \Sigma$.
I don't think I even understand what the question is saying: what does it mean to say that $x\Gamma x^{-1}$? Does it mean applying the group operation of $G$ to any elements $x, (g, e_{H}),x^{-1}$ like this: $(g_0,h_0)(g,e_H)(g_0^{-1},h_0^{-1})$ and therefore considering their triple direct-product?
As an example, the question gives the hint that the Chinese remainder theorem shows that $C_n \times C_m$ is isomorphic to $C_{nm}$ if $gcd(n,m) = 1$ but I don't find this particularly informative.


text:
Q: Number of search results not counting accurate Our search result page shows 50123 result on search result page 1, 49567 on page 2, 48945 on page 3, 50327 on page 4 and on and on.
This causes confusion on our users, and they wonder about it. Why does it differ?

A: My (not so) wild guess is that SharePoint to save performance only estimates the total number of results for the query. And the closer you get to the end of the results list, the more accurate this approximation becomes.
I have thought about checking out exactly how this works behind the scenes, but I have not gotten the time.


text:
Q: I get this error collator_create: unable to open ICU collator: U_FILE_ACCESS_ERROR on Mac os with php54 installed via brew Some information about my system:
$php -v
PHP 5.4.26 (cli) (built: Apr  3 2014 04:46:38)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

$php -i | grep intl
/usr/local/etc/php/5.4/conf.d/ext-intl.ini,
intl
intl.default_locale => en => en
intl.error_level => 0 => 0

$cat /usr/local/etc/php/5.4/conf.d/ext-intl.ini
[intl]
extension="/usr/local/Cellar/php54-intl/5.4.26/intl.so"

Here is the issue i'm having:
$php -r "var_dump(new Collator('en'));echo intl_get_error_message();"
NULL
collator_create: unable to open ICU collator: U_FILE_ACCESS_ERROR

I also tried php55 and got the same error.
Anyone knows what should I do to fix this?

A: its searching 'icudt52l.dat' where 52 is the version number of the ICU.

A: I fixed this problem at a later date by reinstalling php and icu4c:
brew reinstall icu4c
brew reinstall php54 --with-intl


text:
Q: type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr Flutter I am using Event Channels in Flutter to return beacon data from Native SDK to Flutter. This was working fine until a recent Flutter upgrade.Now, I am getting the following error.
type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic>
with the following stack trace:
#0      _registerErrorHandler (dart:async/async_error.dart:22:60)
#1      _BufferingStreamSubscription.onError (dart:async/stream_impl.dart:146:16)
#2      new _BufferingStreamSubscription (dart:async/stream_impl.dart:113:10)
#3      new _ControllerSubscription (dart:async/stream_controller.dart)
#4      new _BroadcastSubscription (dart:async/broadcast_stream_controller.dart)
#5      _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:212:46)
#6      _ControllerStream._createSubscription (dart:async/stream_controller.dart:817:19)
#7      _StreamImpl.listen (dart:async/stream_impl.dart:466:9)
#8      _MyHomePageState.initPlatformState.<anonymous closure>.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:95:43)
#9      _RootZone.runUnary (dart:async/zone.dart:1381:54)
#10     _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#12     Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#13     Future._complete (dart:async/future_impl.dart:467:7)
#14     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#15     MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart)
<asynchronous suspension>
#16     _MyHomePageState.initPlatformState.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:89:24)
<asynchronous suspension>
#17     _RootZone.runUnary (dart:async/zone.dart:1381:54)
#18     _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#19     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#20     Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#21     Future._complete (dart:async/future_impl.dart:467:7)
#22     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#23     User_Profile.getUser (package:flutter_poc/Models/User.dart)
<asynchronous suspension>
#24     _MyHomePageState.initPlatformState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:69:24)
<asynchronous suspension>
#25     _MyHomePageState.initState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:52:5)
#26     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
#27     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
#28     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
#29     Element.updateChild

This is my EventChannel implementation:
static const platform = const MethodChannel('samples.flutter.io/initialiseRanging');
static const stream =
  const EventChannel('samples.flutter.io/ranging');
try {
        await platform.invokeMethod('initialiseRanging').then((result){
          print(result);
          setState(() {
            _currentValue = result;
          });

          stream.receiveBroadcastStream().listen(_onEvent, onError: _onError);
        });

  } on PlatformException catch (e) {
        print( "{e.message}");
  }

This is how the _onEvent and _onError functions are implemented.
void _onEvent(Object event) {
    setState(() {
      _currentValue = event.toString();
    });
    print(event);
}

void _onError(PlatformException error) {
    print(error);
}

Any idea on why this could possible happen?

A: void _onError(PlatformException error) {

should be
void _onError(Object error) {

Even when you are only interested in PlatformException or even when this is the only exception that happened so far, doesn't mean there can't be others. The expected handler function needs to match the parameter type, instead of only the exceptions you expect.


text:
Q: Change button text color on button click in tkinter I am trying to figure out how to change the color of the text on a button, when that button is clicked.  My code is shown below:
def Power1():
    btn1["text"]=("Power 1 On")

btn1 = tkinter.Button(top_frame, text = " Power 1 ", fg = "red", command = Power1).pack(side = "left") #'fg or foreground' is for coloring the contents (buttons)

A: There is one problem which stops you from doing this:
Problem:

*

*You are packing the Button on the same line on which you have defined the Button, which returns None and stores None in the variable(btn1) instead of the Button.

Solution:

*

*The solution is simple, just move the pack() to a new line like this: btn1.pack(side="left"). Then you would be able to change the color of the text as well as the text itself.

Here is the Fixed Code for you:
def Power1():
    btn1["text"] = "Power 1 On"
    btn1["fg"] = "green"

btn1 = tkinter.Button(top_frame, text=" Power 1 ", fg="red", command=Power1)
btn1.pack(side="left")


text:
Q: Pandas DataFrame: Calculate difference (which is no. of days) for each row, satisfying a condition dynamically Consider the below DataSet Screenshot:

pd.DataFrame({'Date': ['05/10/2018','08/10/2018','09/10/2018','10/10/2018','11/10/2018','12/10/2018','15/10/2018','16/10/2018','17/10/2018','19/10/2018','22/10/2018','23/10/2018','24/10/2018','25/10/2018','26/10/2018','29/10/2018','30/10/2018','31/10/2018'],
              'Open': [271,259.75,268,261.6,268,266,264.4,264.6,273.75,259.7,266,258,260.25,254.5,252,250,267.5,275],
              'High': [271,268.5,268.15,280.45,271.5,267.9,265.7,270.85,275,264.2,266,259,261.8,255,252.5,269.25,279.1,282.75],
              'Low': [256,258.35,260,261.2,260.6,261.5,261.1,263.35,260,258.1,259.45,255,252.8,248.4,247.4,248.4,266,268.6],
              'Close': [258.35,265.75,262.95,278.65,262.15,263.75,263.2,270.3,261.15,261.1,260.35,255.65,255.7,249.55,248.1,267.9,273.15,281.4]})

I want to calculate the difference between dates for each row where current row 'High' is broken. Let's say, for example, for 30/10/18 'High' is 279.1. Now, I want to find the Date (backwards) where this 'High' is broken (the first Date/index where it is broken). In this case, it is 10/10/2018 ('High' is 280.45). So, there is no such specific period (which I can mention for comparison). This is dynamic.
Now, In my DataFrame, I need to add a Column which will show the difference between such dates (Here, it is 12).
My approach to above problem is by slicing the DataFrame containing the new row, each time and then see where the 'High' is broken, thus calculating the difference between them. Something like this,
for index in range(df.shape[0]):
     av_data = df[:index+1]

for index in range(-2, -av_data.shape[0], -1):
     if av_data['High'].iloc[index] > av_data['High'].iloc[-1]:
         #Our Logic to find the no. of days
         break`

Although, it is working but I think there is a major drawback in terms of performance coz this need to be applied on whole Dataset (which could be more than 2000 rows) and moreover, I am not familiar with the in-built functions Pandas that can achieve the same thing.


text:
Q: Conditional mean by colnames I need to put a new column in my data frame, using dplyr::mutate who simply calculate the row means if the column name starts with V.
I tried to use
fcst_prices <- fcst_prices %>%
 mutate(
  Mean_Fcsts = rowMeans(select(starts_with("V")), na.rm=TRUE)
)

data:
glimpse(fcst_prices)
Rows: 504
Columns: 1,000
$ V1         <dbl> 0.9882854, 0.9943432, 1.0066737, 1.0358174, 1.0318638, 1.05~
$ V2         <dbl> 1.0067812, 0.9780687, 1.0038225, 1.0131935, 1.0089143, 1.03~
$ V3         <dbl> 1.018123, 1.011892, 1.025020, 1.066394, 1.059514, 1.065158,~
$ V4         <dbl> 1.0072748, 0.9973791, 0.9791292, 0.9534645, 0.9765678, 0.95~
$ V5         <dbl> 0.9783680, 0.9655283, 0.9649827, 1.0490434, 1.0503648, 1.06~
$ V6         <dbl> 1.0027197, 0.9870110, 0.9734787, 0.9764613, 0.9662142, 0.94~
$ V7         <dbl> 0.9951287, 1.0177348, 1.0054102, 1.0174618, 0.9996121, 0.98~
$ V8         <dbl> 0.9856348, 0.9969825, 0.9779560, 0.9971946, 1.0053000, 1.02~
$ V9         <dbl> 1.000684, 1.009189, 1.024402, 1.032096, 1.053807, 1.068524,~
$ V10        <dbl> 1.0068093, 0.9939374, 0.9802338, 0.9885188, 0.9622480, 0.96~
$ V11        <dbl> 0.9988063, 1.0051448, 1.0142188, 1.0223961, 1.0399016, 1.03~
$ V12        <dbl> 1.017846, 1.012508, 1.024628, 1.024206, 1.004845, 1.022993,~
$ V13        <dbl> 1.0206625, 0.9939849, 0.9607511, 0.9852449, 0.9395213, 0.92~
$ V14        <dbl> 1.0161157, 1.0085123, 1.0095981, 1.0017129, 0.9897123, 0.99~
$ V15        <dbl> 0.9585678, 0.9820704, 0.9911285, 0.9817727, 0.9911644, 1.00~
$ V16        <dbl> 0.9941426, 0.9927010, 0.9917946, 0.9889182, 0.9925894, 0.99~
$ V17        <dbl> 0.9979804, 1.0214071, 1.0286764, 1.0415425, 1.0409966, 1.04~
$ V18        <dbl> 0.9878930, 0.9820520, 0.9741155, 0.9707525, 0.9548519, 0.96~
$ V19        <dbl> 0.9871881, 1.0021602, 1.0243242, 0.9994608, 1.0003129, 0.99~
$ V20        <dbl> 0.9828258, 0.9910219, 1.0019939, 0.9944902, 0.9552034, 0.93~
$ V21        <dbl> 0.9888249, 0.9718689, 0.9760357, 0.9850335, 0.9819784, 1.01~
$ V22        <dbl> 0.9981441, 1.0049319, 0.9887205, 0.9895039, 1.0148411, 1.01~
$ V23        <dbl> 0.9970455, 1.0061045, 1.0248983, 1.0224870, 1.0197655, 1.03~
$ V24        <dbl> 1.0125220, 1.0253541, 1.0307841, 1.0425741, 1.0344221, 1.02~
$ V25        <dbl> 0.9914851, 0.9711403, 0.9917044, 0.9963411, 1.0075890, 1.00~
$ V26        <dbl> 1.0011011, 1.0078956, 1.0029757, 1.0049124, 1.0332714, 1.06~
$ V27        <dbl> 1.0159438, 1.0158054, 1.0104938, 1.0020727, 1.0017532, 1.01~
$ V28        <dbl> 0.9846138, 0.9908568, 0.9851029, 0.9398689, 0.9388180, 0.92~
$ V29        <dbl> 0.9913572, 0.9970750, 0.9957020, 0.9994990, 0.9960493, 1.00~
$ V30        <dbl> 0.9675074, 0.9495288, 0.9357869, 0.9164587, 0.9231961, 0.93~
$ V31        <dbl> 0.9884108, 1.0102067, 1.0023929, 1.0282738, 1.0292449, 1.02~
$ V32        <dbl> 1.0003712, 1.0018117, 1.0124738, 1.0117079, 1.0192414, 1.02~
$ V33        <dbl> 0.9740372, 0.9587591, 0.9711541, 1.0084787, 1.0095611, 0.99~
$ V34        <dbl> 0.9996792, 1.0078209, 1.0109785, 1.0188314, 1.0302227, 1.03~
$ V35        <dbl> 1.0119468, 1.0127999, 1.0289631, 1.0143031, 1.0543618, 1.05~

But that doesn't work. How can I solve this?


text:
Q: how to get array of sentences and words passing as parameter to a function in javascript? I have a function say
 var init = function(data){
     all sentences: " I have to get all the sentences and return an array containing all sentences"
     all words : "this method should return an array of words in 'Data' when there is no parameter passed in. Optionally, when there is a parameter passed in that is a number, return the words in the sentence indicated by the input parameter"

     all reverse sentences: "this method is the same as all Sentences, except it should return the sentences in reverse order"

     reverse words :" same as all words but in reverse order"
     countWordsBeginningWith:" this method should return the amount of words that begin with an inputted string. The optional second parameter should determine what sentence the words come from when present."

thanks

A: I think what you need to do is decompose your argument (assuming it's a string) into an array. For instance:
function getAllWords(sentences) {
    var result = sentences.split(' ');
    return result;
}

var init = function(data){
    var result = [];
    result['words'] = getAllWords(data.text);
    // result['sentences'] = getAllSentences(data.text);
    // result['sentencesreversed'] = getReverseSentences(data.text);
    // result['sentencewords'] = getReverseWords(data.text);
    // result['beginswith'] = getWordsBeginningWith(data.text, data.beginswith);
    return result;
}

var getIt = {
    'beginswith': 't',
    'text': 'This is stuff. I am a sentence. Stuff happens now.'
};

console.log(init(getIt));

This is a very simplistic answer, not taking into account for periods, commas, and other bits. But that's the general answer. Some for loops and/or RegEx's may occur after this point, buyer beware.

A: In Javascript you can pass any data structure as a function parameter.
First learn how to construct an array of strings to contain you word or sentences. Once you have accomplished this it will be straightforward.


text:
Q: Solrnet: How to use QueryelevationComponent in .net? I am using SolrNet for site search. However, now I need to show some documents at the top for specific queries. I went through the Query Elevation manual  http://wiki.apache.org/solr/QueryElevationComponent and set up solrconfig.xml accordingly. The the debugging url mentioned in the manual is working pretty well.
I just don't know how to use  Query elevation component with Solrnet. I cannot find any code example in SolrNet wiki that shows how to use elevate.xml. Any example, suggestion will be highly appreciated.

A: Based on the QueryElevatorComponent documentation on the wiki, you have a few options for enabling this for use with the SolrNet client.

*

*You can add the following parameter to your SolrNet client query, to tell Solr to use the elevate RequestHandler instead of the default.
solr.Query("ipod", new QueryOptions {
     ExtraParams = new Dictionary<string, string> {
        {"qt", "elevate"}
     }
 });

*Modify your default request handler in the solrconfig.xml file to add the elevate component as last-component. Below is a modified version of solrconfig.xml that comes with the Solr distribution sample file. Note: This assumes that you have the elevator searchcComponent defined as shown in the wiki page.
<requestHandler name="search" class="solr.SearchHandler" default="true">
   <!-- default values for query parameters can be specified, these
   will be overridden by parameters in the request
    -->
  <lst name="defaults">
    <str name="echoParams">explicit</str>
    <int name="rows">10</int>
  </lst>

  ...

  <arr name="last-components">
    <str>elevator</str>
  </arr>
</requestHandler>

A: There is nothing you need to do client-side (i.e. in SolrNet) to activate this feature. It's configured and activated purely server-side.


text:
Q: Adding ActiveRecord's migration generators to a non-rails project Is it possible to get the Active Record migration generators that Rails has to work in a project that is not using Rails -- perhaps via rake tasks.
I have a Ruby project that is using ActiveRecord but it is not a Rails project.  So far, I create my migrations by hand which works but it would be nice to get the migration generators to work.  Is that practical?


text:
Q: enum static variable reference between java I have three java files I'm working with and using Junit.
The test class is where I'm getting my error in regard to an enum that is in the main class.
EDIT
I found out that the this was working as is.  Just not in a larger scale implementation.
Goods.java
class Good {
    private static StaticTest.THESES name;
    static void setStatusName(StaticTest.THESES status) {
       name = status;
    }
    static StaticTest.THESES getStatusName() {
        return name;
    }
}

Test.class
import org.junit.Test;
import static org.junit.Assert.*;

public class Tests {

     @Test
     public void test() {
        Good good = new Good();
        good.setStatusName(Library.STATUSES.HIM);
        String actual = good.getStatusName().toString();

         String expected = Library.STATUSES.HIM.toString();
         assertEquals(expected, actual);
    }

    public static void main(String args[]) {
        Tests runningTest = new Tests();
        runningTest.test();
    }
}

class Library {
    public static enum STATUSES {
        YOU, ME, HER, HIM, THEM, US
    }
}

can you tell me what I can't find any values from my products class?

A: You need to get a better grasp of what it means to declare something static. I think each Good will need to have its own status right - so you are on the right track by not declaring your private status as static. Your problem (as Boris pointed out) is that you are trying to mutate the instance variable status by using static (class level) methods.
I think you will want to use something like the below to start you off.
public class Test {

    public static void main(String[] args) {
        Good good = new Good();
        good.setStatus(Library.STATUS.SALE);
        System.out.println("Good's status: " + good.getStatus());
    }

}

class Good {

    private Library.STATUS status;

    public void setStatus(Library.STATUS status) {
       this.status = status;
    }
    public Library.STATUS getStatus() {
       return status;
    }
}

class Library {

    public enum STATUS {
          SALE, NOSALEITEM, ITEMOOS, SHIPPING, ONORDER, INSTOCK
     }
}


text:
Q: Trying to generate numbers in a range and add the number which was generated to a counter to display as an output I'm generating random numbers in the range 1 to 7 and assigned 1 to A, 2 to B .... 7 to G. When the random number generates I want to add that number onto a counter till the loop finishes and then output how many numbers of which letter were generated. What I'm trying to achieve when I enter say: 10. I should get the output:
Count is as follows:
A: 1
B: 3
C: 1
D: 2
E: 2
F: 1
G: 0
If you count the numbers that were generated is adds up to 10 which was the input, but when I enter say, 10, I get:
A: 3
B: 4
C: 5
D: 5
E: 7
F: 8
G: 11
import javax.swing.JOptionPane;
public class sheet10t3
{
    public static void main(String[] args)
    {
        String menu = "How many random notes would you like?\n(input must be in the range 10 to 50)?", results = "";
        int input = Integer.parseInt(JOptionPane.showInputDialog(null,menu));
        int aNumber, countA = 0, countB = 0, countC = 0, countD = 0, countE = 0, countF = 0, countG = 0;
        if(input < 1 || input > 50)
            results = "Please enter a valid input in the range 1 to 50.";
        else
        {
            for(int i = 0; i <= input; i++)
            {
                aNumber = (int) (Math.random() * 7 + 1);
                switch(aNumber)
                {
                    case 1: countA++;
                    case 2: countB++;
                    case 3: countC++;
                    case 4: countD++;
                    case 5: countE++;
                    case 6: countF++;
                    case 7: countG++;
                }
            }
            results = "Count of each note is as follows:";
            results += "\nA: " + countA;
            results += "\nB: " + countB;
            results += "\nC: " + countC;
            results += "\nD: " + countD;
            results += "\nE: " + countE;
            results += "\nF: " + countF;
            results += "\nG: " + countG;
        }
        JOptionPane.showMessageDialog(null,results);
    }
}

A: case 1: countA++;
break;
case 2: countB++;
break;
case 3: countC++;
break;
case 4: countD++;
break;
case 5: countE++;
break;
case 6: countF++;
break;
case 7: countG++;
break;

Solves it


text:
Q: thinking about moving to Trac We're starting development and are at a point where we need a bug tracking site.  Our code is in SVN and we're thinking of using Bugzilla, but setup is tricky.  I'm considering going for Trac instead.  From what I understand, Trac would need to be on the same machine as SVN.
I'm really having a hard time parsing through the Trac documentation.  What kind of things should I look for when I'll be migrating?

A: You are correct that Trac must be running on the same machine as the svn repository; it requires local access to the repo.
To use Trac, you need to: install the Trac software, create a Trac environment, configure your webserver, configure Trac authentication and users, customize Trac as needed for your purposes.
To install Trac, you can use the egg, rpm, or your distro's packaging system, etc.
To create your Trac environment, you will run
trac /path/to/new/trac/environment initenv

and follow the prompts.  Since you have an existing svn repo, you will specify the path to it at that prompt.
To configure your webserver, you'll need to decide among several options.  I tend to use mod_python though others will direct you to mod_wsgi.
I would recommend installing the AccountManagerPlugin and using its "form based login" instead of http auth.  Using it with its htpasswd backend works well; you'd point it to an htpasswd file you create with an admin user and a good password.  Then you would grant that admin account full access to the Trac environment like this:
trac /path/to/new/trac/environment permission add admin TRAC_ADMIN

You should now be able to log into Trac with your web browser as your admin user and customize Trac as desired.
Also, #trac on freenode is a good resource for getting help.
Disclosure: I'm one of the Trac devs.


text:
Q: Maximize a button when a button is clicked I ran into trouble, When i click on img or link tag my box must be maxmized and when i click again the same button then my box must minimize.
Hear i ran into trouble, can any one correct my issue

*

*when i click on hello button my box must be maximised and when i click back it need to get minimize,

*hear the problem is both the buttons getting maximizes when i start click event??

i am unable to find wht issue is
http://jsfiddle.net/Navya/eVUkG/1/
$(function() {
        $( "#button" ).toggle(
            function() {
                $( "#effect" ).animate({
                    backgroundColor: "#0000",
                    width: 500,

                }, 500 );
            },
            function() {
                $( "#effect" ).animate({
                    backgroundColor: "#000",

                    width: 240
                }, 500 );
            }
        );
    });

A: First off, both buttons have an ID of button. Id's must be unique. Secondly, instead of targeting .effect just target the parent of the button (demo)
$(function() {
    $("#container").sortable({
        handle: 'h1',
        scroll: false,
        revert: true,
        tolerance: 'pointer'
    });

    $(".button").toggle(function() {
        $(this).parent().animate({
            backgroundColor: "#0000",
            width: 500,
        }, 500);
    }, function() {
        $(this).parent().animate({
            backgroundColor: "#000",
            width: 40
        }, 500);
    });

});


text:
Q: How run MATLAB in linux server with C code embedded I am submiting my matlab files in a server using linux. But I need to run some command lines when the server calls may main.m, how can I include this commands inside the main.m? This commands are:
build mex
load('workspace')

The 1st is for MATLAB to able to run embedded C code. So far, I am including this commands just as another line in the top of my main.m file, and was expecting the server to run it. But is not running. I am trying to use multiple nodes and cores from the server and for that I need to use a submission file to queue my job behind more users. The file looks like this:
indexed_stdout = logfile
M_file = main.m
cores_per_node = 8
total_jobs = 1

I was also testing an executable (Standalone Application from MATLAB) file of my MATLAB project but is not running neither. The errors are:
expr: non-numeric argument
Undefined variable "coder" or class "coder.config".
Error in build (line 11)
Error in main (line 4)
MATLAB:undefinedVarOrClass
Undefined function or variable 'bimifunc_mex'.


text:
Q: python array address pass to C I want to pass the address of a python array buffer to another application or to c function,
buf = array("d", range(10))
addr, count = buf.buffer_info()
print "Address of buffer ", addr

output:
Address of buffer  0x28a3ab0

Is this address an actual memory address of first element of the buf array?
Is this similar address like in C , address of first element of buf?
If not how can I declare a buffer in python and pass its address to c function and use its value and addressing like arrays of C ?
if this address is actual memory address can i use this address in memcpy() function in C.

A: As the documentation wrote, it's okay to use it as a address. But think of using buffer protocol as per NOTE.

Return a tuple (address, length) giving the current memory address and
  the length in elements of the buffer used to hold array's contents.
  The size of the memory buffer in bytes can be computed as
  array.buffer_info()1 * array.itemsize. This is occasionally useful
  when working with low-level (and inherently unsafe) I/O interfaces
  that require memory addresses, such as certain ioctl() operations. The
  returned numbers are valid as long as the array exists and no
  length-changing operations are applied to it.
Note When using array objects from code written in C or C++ (the only
  way to effectively make use of this information), it makes more sense
  to use the buffer interface supported by array objects. This method is
  maintained for backward compatibility and should be avoided in new
  code. The buffer interface is documented in Buffer Protocol.


text:
Q: Cannot read property 'hasError' of undefined on nested form group in angular I keep having an error of "Cannot read property 'hasError' of undefined" when creating a validation for my nested group. On the main group, I do not have problems but if it is on the nested form group, that's where the issue comes. Please see my codes below:
<form
    [formGroup]="form"
    (ngSubmit)="onSubmit(form)"
    class="border border-light p-5"
  >

      <input
        type="text"
        placeholder="Plaza Name"
        formControlName="name"
        id="name"
        class="form-control mb-4"
        mdbInput
        required
      />

        Plaza Name is required

      <input
        type="number"
        placeholder="Plaza Code"
        formControlName="code"
        id="code"
        class="form-control mb-4"
        mdbInput
        required
      />

        Plaza code is required

        <input
          type="number"
          placeholder="Lane Number"
          formControlName="number"
          id="number"
          class="form-control mb-4"
          mdbInput
          required
        />

          Lane number is required

        <select
          formControlName="type"
          id="type"
          class="browser-default custom-select mb-4"
          mdbInput
          required
        >
          <option *ngFor="let type of typeSelect" [value]="type.label">{{
            type.label
          }}</option>
        </select>

    <button
      mdbBtn
      color="info"
      outline="true"
      block="true"
      class="z-depth-0 my-4 waves-effect"
      mdbWavesEffect
      type="submit"
    >
      Send
    </button>
 </form>

This is in the ts file
createForm() {
    this.form =  this.fb.group({
      name: [null, Validators.required],
      code: [null, Validators.required],
      lanes: this.fb.group({
        number: [null, Validators.required],
        type: [null, Validators.required]
      })
    });
}

formHasError(controlName: string, errorName: string) {
   return this.form.controls[controlName].hasError(errorName);
}

Can you please show me how to do this right? THank you.

A: Personally; I opt for such a solution it's easier and clearer without using an extra function
<form
    [formGroup]="form"
    (ngSubmit)="onSubmit(form)"
    class="border border-light p-5"
  >

      <input
        type="text"
        placeholder="Plaza Name"
        formControlName="name"
        id="name"
        class="form-control mb-4"
        mdbInput
        required
      />

        Plaza Name is required

      <input
        type="number"
        placeholder="Plaza Code"
        formControlName="code"
        id="code"
        class="form-control mb-4"
        mdbInput
        required
      />

        Plaza code is required

        <input
          type="number"
          placeholder="Lane Number"
          formControlName="number"
          id="number"
          class="form-control mb-4"
          mdbInput
          required
        />

          Lane number is required

        <select
          formControlName="type"
          id="type"
          class="browser-default custom-select mb-4"
          mdbInput
          required
        >
          <option *ngFor="let type of typeSelect" [value]="type.label">{{
            type.label
          }}</option>
        </select>

    <button
      mdbBtn
      color="info"
      outline="true"
      block="true"
      class="z-depth-0 my-4 waves-effect"
      mdbWavesEffect
      type="submit"
    >
      Send
    </button>
 </form>

A: stackblitz
formHasError(controlName: string, errorName: string) {
    const control=this.form.get(controlName);
    return control?control.hasError(errorName):false;
  }

A: cause you have a formgroup (lanes) in your main form so if you call this.form.controls['lanes'] it will return you a formGroup with controls not a formcontrol so you should consider your child form in your function and your formHasError should be:
if(this.form.controls[controlName].controls) {
        return this.form.controls[controlName]['controls'].hasError(errorName);
    } else {
        return this.form.controls[controlName].hasError(errorName);
    }

A: you just need to use get method
formHasError(controlName: string, errorName: string) : boolean {
   return this.form.get(controlName).hasError(errorName);
}

get method retrieves a child control given the control's name or path.

stackblitz demo


text:
Q: Observe generic values with Combine Take this case of a type constrained class Parameter, wrapping a value of given type.
Parameter conforms to the AnyParameter so it can be passed anywhere in the app without knowing the type. Parameters can be displayed in value cells AnyValueCell

*

*How would you do to observe the change without having to know the underlying value type? It would be nice to avoid the code repetition in the value cell updateObserver function

*Could AnyPublisher can be used here and how?

import UIKit
import Combine

print("Hello Playground")

protocol AnyParameter {
    var anyValue: Any { get }
    func set(value: Any)
}

protocol ParameterProtocol: AnyParameter {
    associatedtype ValueType

    var value: ValueType { get }
    func set(value: ValueType)

}

public class Parameter<T>: ParameterProtocol {

    typealias ValueType = T

    @Published var value: T

    var anyValue: Any { value }

    init(value: T) {
        self.value = value
    }

    func set(value: Any) {
        guard let value = value as? T else { return }
        set(value: value)
    }

    func set(value: T) {
        self.value = value
    }
}

public class AnyValueCell {

    var parameter: AnyParameter {
        didSet {
            updateObserver()
        }
    }

    var observer: AnyCancellable?

    init(parameter: AnyParameter) {
        self.parameter = parameter
        updateObserver()
    }

    func updateObserver() {
        observer?.cancel()

        // This is the point of the question - How to make this generic?
        // ---->
        if let p = parameter as? Parameter<Int> {
            observer = p.$value.sink() { value in
                print("Update Cell -> \(value)")
            }
            return
        }

        if let p = parameter as? Parameter<Double> {
            observer = p.$value.sink() { value in
                print("Update Cell -> \(value)")
            }
            return
        }

        if let p = parameter as? Parameter<Bool> {
            observer = p.$value.sink() { value in
                print("Update Cell -> \(value)")
            }
            return
        }
        // <----

        print("Wrong param type")
    }
}

let intParam = Parameter<Int>(value: 42)
let doubleParam = Parameter<Double>(value: 3.14)
let boolParam = Parameter<Bool>(value: false)

var params: [AnyParameter] = [intParam, doubleParam, boolParam]

print ("--> Init Cells")
let cells: [AnyValueCell] = params.map { AnyValueCell(parameter: $0) }

print ("--> Change values")
intParam.set(value: 21)
doubleParam.set(value: 1.618)
boolParam.set(value: true)

Result, as expected:
Hello Playground
--> Init Cells
Update Cell -> 42
Update Cell -> 3.14
Update Cell -> false
--> Change values
Update Cell -> 21
Update Cell -> 1.618
Update Cell -> true

A: Add an anyValuePublisher property. You can (and maybe should) add it to AnyParameter, or you can define it in a separate protocol like this:
protocol AnyParameterPublishing: AnyParameter {
    var anyValuePublisher: AnyPublisher<Any, Never> { get }
}

extension Parameter: AnyParameterPublishing {
    var anyValuePublisher: AnyPublisher<Any, Never> {
        return $value.map { $0 as Any }.eraseToAnyPublisher()
    }
}

Then you can use it like this:
class AnyValueCell {
    // ...

    func updateObserver() {
        guard let publishing = (parameter as? AnyParameterPublishing) else {
            print("Wrong param type")
            return
        }
        observer = publishing.anyValuePublisher
            .sink { print("Update Cell -> \($0)") }
    }
}


text:
Q: Hosting custom control in DataGridView - C# WinForm I looked at http://msdn.microsoft.com/en-us/library/7tas5c80.aspx for reference and it makes sense as far as editable column goes.
The question is how do I host a "view only" custom control in a DataGridView (WinForm and C#)?

A: Derive from DataGridViewCell and override the Paint methods.

A: Another easy way would be to make that column one of the "DataKeyNames" columns of the grid.  Any field that is considered a "Key" is by default disabled from a user editing it.  However, if you deal with object analysis on "clicked" on records for editing, or other, the array of returned keys will be in the same sequence as they are listed in the DataKeyNames property.  So, even though you may be ignoring the actual value as a "Key", it can act to disable it.
HTH


text:
Q: What are the conditions when sometimes Required field validators fails in C#? There is a strange problem in my application. There is one mandatory field which we are making mandatory through Required field validator but still in few scenarios it fails. Can someone tell me what can be the possible causes. I am not able to recreate this issue.

A: If someone disables JavaScript, and you're not using Page.IsValid in your server side code, then you might encounter empty fields.
This should do:
void SubmitButton_Click(object sender, EventArgs e)
{
    if (!Page.IsValid)
        return;

    // Do form stuff
}

A: If you are trying to validate a dropdownlist with a "Please select" option, with a value of "-1" for example, you will need to set the initial value property of the validation control to this value to ensure that another choice has been made.