text:
Q: mysql remove unwanted text from field using substring_index with wildcard I have a table called hamburgers.  I want to clean up the data and remove some garbage text from around the name of the hamburger and just use ONLY the name of the hamburger in the title field.  So far this is all my little brain can muster...
UPDATE hamburgers
SET title = SELECT SUBSTRING_INDEX(title, "My favorite hamburger is called %, I'm not really sure why.   Yesterday was the first time I ate a %", -1) FROM hamburgers
where title like "%My favorite hamburger is called %.%";

I suck at MySql but I just want to figure out a way to remove the text surrounding the name of the burger.  There are 3,000 or so records that have the same exact text surrounding the name of the hamburger.  TIA.

A: This might get you going in the right direction:
select substring_index(substring_index("My favorite hamburger is called Whopper, I'm not really sure why.   Yesterday was the first time I ate a Whopper","My favorite hamburger is called ",-1),",",1);

This will give you:
Whopper

So:
UPDATE hamburgers
SET title = substring_index(substring_index(title,"My favorite hamburger is called ",-1),",",1)
where title like "My favorite hamburger is called %,";

It does kinda rely on there being a comma after the hamburger though....


text:
Q: Can't save option for custom option type for 'test' I have created new custom option type as test but it does not save in database can you suggest for the same ?
Following code I have used to modify CustomOptions.php
<?php
namespace Test\Module\Ui\DataProvider\Product\Form\Modifier;
use Magento\Ui\Component\Container;
use Magento\Ui\Component\DynamicRows;
use Magento\Ui\Component\Form\Field;
use Magento\Ui\Component\Form\Element\Input;
use Magento\Ui\Component\Form\Element\Select;
use Magento\Ui\Component\Form\Element\ActionDelete;
use Magento\Ui\Component\Form\Element\DataType\Text;
use Magento\Ui\Component\Form\Fieldset;

class CustomOptions extends \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions
{
    const FIELD_TYPE_TEST_NAME = 'test';
    protected function getStaticTypeContainerConfig($sortOrder)
    {
        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'componentType' => Container::NAME,
                        'formElement' => Container::NAME,
                        'component' => 'Magento_Ui/js/form/components/group',
                        'breakLine' => false,
                        'showLabel' => false,
                        'additionalClasses' => 'admin__field-group-columns admin__control-group-equal',
                        'sortOrder' => $sortOrder,
                        'fieldTemplate' => 'Magento_Catalog/form/field',
                        'visible' => false,
                    ],
                ],
            ],
            'children' => [
                static::FIELD_PRICE_NAME => $this->getPriceFieldConfig(10),
                static::FIELD_PRICE_TYPE_NAME => $this->getPriceTypeFieldConfig(20),
                static::FIELD_SKU_NAME => $this->getSkuFieldConfig(30),
                static::FIELD_MAX_CHARACTERS_NAME => $this->getMaxCharactersFieldConfig(40),
                static::FIELD_FILE_EXTENSION_NAME => $this->getFileExtensionFieldConfig(50),
                static::FIELD_IMAGE_SIZE_X_NAME => $this->getImageSizeXFieldConfig(60),
                static::FIELD_IMAGE_SIZE_Y_NAME => $this->getImageSizeYFieldConfig(70),
                static::FIELD_TYPE_TEST_NAME => $this->getTemplateTypeFieldConfig(80)
            ]
        ];
    }

    protected function getTypeFieldConfig($sortOrder)
    {
        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'label' => __('Option Type'),
                        'componentType' => Field::NAME,
                        'formElement' => Select::NAME,
                        'component' => 'Magento_Catalog/js/custom-options-type',
                        'elementTmpl' => 'ui/grid/filters/elements/ui-select',
                        'selectType' => 'optgroup',
                        'dataScope' => static::FIELD_TYPE_NAME,
                        'dataType' => Text::NAME,
                        'sortOrder' => $sortOrder,
                        'options' => $this->getProductOptionTypes(),
                        'disableLabel' => true,
                        'multiple' => false,
                        'selectedPlaceholders' => [
                            'defaultPlaceholder' => __('-- Please select --'),
                        ],
                        'validation' => [
                            'required-entry' => true,
                        ],
                        'groupsConfig' => [
                            'text' => [
                                'values' => ['field', 'area'],
                                'indexes' => [
                                    static::CONTAINER_TYPE_STATIC_NAME,
                                    static::FIELD_PRICE_NAME,
                                    static::FIELD_PRICE_TYPE_NAME,
                                    static::FIELD_SKU_NAME,
                                    static::FIELD_MAX_CHARACTERS_NAME,
                                ],
                            ],
                            'file' => [
                                'values' => ['file'],
                                'indexes' => [
                                    static::CONTAINER_TYPE_STATIC_NAME,
                                    static::FIELD_PRICE_NAME,
                                    static::FIELD_PRICE_TYPE_NAME,
                                    static::FIELD_SKU_NAME,
                                    static::FIELD_FILE_EXTENSION_NAME,
                                    static::FIELD_IMAGE_SIZE_X_NAME,
                                    static::FIELD_IMAGE_SIZE_Y_NAME,
                                ],
                            ],
                            'test' => [
                                'values' => ['test'],
                                'indexes' => [
                                    static::CONTAINER_TYPE_STATIC_NAME,
                                    static::FIELD_TYPE_TEST_NAME

                                ],
                            ],
                            'select' => [
                                'values' => ['drop_down', 'radio', 'checkbox', 'multiple'],
                                'indexes' => [
                                    static::GRID_TYPE_SELECT_NAME,
                                ],
                            ],
                            'data' => [
                                'values' => ['date', 'date_time', 'time'],
                                'indexes' => [
                                    static::CONTAINER_TYPE_STATIC_NAME,
                                    static::FIELD_PRICE_NAME,
                                    static::FIELD_PRICE_TYPE_NAME,
                                    static::FIELD_SKU_NAME,
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }
    /**
     * Get config for "Price Type" field
     *
     * @param int $sortOrder
     * @param array $config
     * @return array
     * @since 101.0.0
     */
    protected function getTemplateTypeFieldConfig($sortOrder, array $options = [])
    {
        //echo "<pre>";print_r($this->productOptionsPrice->toOptionArray());exit;
        $arr[0]['value'] = 0;
        $arr[0]['label'] = 'test';
        $arr[1]['value'] = 1;
        $arr[1]['label'] = 'test1';

        return array_replace_recursive(
            [
                'arguments' => [
                    'data' => [
                        'config' => [
                            'label' => __('Template Option'),
                            'componentType' => Field::NAME,
                            'formElement' => Select::NAME,
                            'dataScope' => static::FIELD_TYPE_TEST_NAME,
                            'dataType' => Text::NAME,
                            'sortOrder' => $sortOrder,
                            'options' => $arr,

                        ],
                    ],
                ],
            ],
            $options
        );
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Live FLV streaming in C# WebApi Currently I have a working live stream using webapi. By receiving a flv stream directly from ffmpeg and sending it straight to the client using PushStreamContent. This works perfectly fine if the webpage is already open when the stream starts. The issue is when I open another page or refresh this page you can no longer view the stream (the stream is still being sent to the client fine). I think it is due to something missing from the start of the stream but I am not sure what to do. Any pointers would be greatly appreciated.
Code for client reading stream
public class VideosController : ApiController
{
    public HttpResponseMessage Get()
    {
        var response = Request.CreateResponse();
        response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue("video/x-flv"));

        return response;
    }

    private async Task WriteToStream( Stream arg1, HttpContent arg2, TransportContext arg3 )
    {
        //I think metadata needs to be written here but not sure how
        Startup.AddSubscriber( arg1 );
        await Task.Yield();
    }
}

Code for receiving stream and then sending to client
while (true)
{
    bytes = new byte[8024000];
    int bytesRec = handler.Receive(bytes);

    foreach (var subscriber in Startup.Subscribers.ToList())
    {
        var theSubscriber = subscriber;
        try
        {
            await theSubscriber.WriteAsync( bytes, 0, bytesRec );
        }
        catch
        {
            Startup.Subscribers.Remove(theSubscriber);
        }
    }
}

A: I've never used FLV or studied video formats closely
Most file formats are structured, especially video formats. They contain frames (i.e. a complete or partial screen shots depending on the compression format).
You should be really lucky if you manage to hit a specific frame when you start streaming to the new subscriber. Hence when they start receiving the stream they cannot identify the format as frame is partial.
You can read more FLV frames in wikipedia article. This is most likely your problem.
A simple attempt would be to try to save the initial header that you receive from the streaming server when the first subscriber connects.
Something like:
static byte _header = new byte[9]; //signature, version, flags, headerSize

public void YourStreamMethod()
{
    int bytesRec = handler.Receive(bytes);
    if (!_headerIsStored)
    {
        //store header
        Buffer.BlockCopy(bytes, 0, _header, 0, 9);
        _headerIsStored = true;
    }
}

.. which allows you to send the header to the next connecting subscriber:
private async Task WriteToStream( Stream arg1, HttpContent arg2, TransportContext arg3 )
{
    // send the FLV header
    arg1.Write(_header, 0, 9);

    Startup.AddSubscriber( arg1 );
    await Task.Yield();
}

Once done, pray that the receiver will ignore partial frames. If it doesn't you need to analyze the stream to identify where the next frame is.
To do that you need to do something like this:

*

*Create a BytesLeftToNextFrame variable.

*Store the received packet header in a buffer

*Convert the "Payload size" bits to an int

*Reset the BytesLeftToNextFrame  to the parsed value

*Countdown until the next time you should read a header.

Finally, when a new client connects, do not start streaming until you know that the next frame arrives.
Pseudo code:
var bytesLeftToNextFrame = 0;
while (true)
{
    bytes = new byte[8024000];
    int bytesRec = handler.Receive(bytes);

    foreach (var subscriber in Startup.Subscribers.ToList())
    {
        var theSubscriber = subscriber;
        try
        {
            if (subscriber.IsNew && bytesLeftToNextFrame < bytesRec)
            {
                //start from the index where the new frame starts
                await theSubscriber.WriteAsync( bytes, bytesLeftToNextFrame, bytesRec - bytesLeftToNextFrame);
                subscriber.IsNew = false;
            }
            else
            {
                //send everything, since we've already in streaming mode
                await theSubscriber.WriteAsync( bytes, 0, bytesRec );
            }
        }
        catch
        {
            Startup.Subscribers.Remove(theSubscriber);
        }
    }

    //TODO: check if the current frame is done
    // then parse the next header and reset the counter.
}

A: I'm not a expert in streaming, but looks like you should close stream then all data will be writed
await theSubscriber.WriteAsync( bytes, 0, bytesRec );

Like it mentions in WebAPI StreamContent vs PushStreamContent
{
     // After save we close the stream to signal that we are done writing.
     xDoc.Save(stream);
     stream.Close();
}

A: I LIKE THIS CODE BECAUSE IT DEMONSTRATES A FUNDAMENTAL ERROR when dealing with async programming
while (true)
{

}

this is a synced loop, that loops itself as fast as possible.. every second it can execute thousands of times (depending on availabe software and hardware resources)
await theSubscriber.WriteAsync( bytes, 0, bytesRec );

this is an async command (if that wasn't clear enough) that execute in a DIFFERENT thread (while loop representes the main thread execution)
now... in order to make the while loop to wait to the async command we use await... sounds good (or else the while loop will execute thousands of times, executing countless async commands)
BUT because the loop (of subscribers) need to transmit the stream for all subscribers simulatanly it get stucked by the await keyword
THAT IS WHY RELOAD / NEW SUBSCRIBER FREEZE THE WHOLE THING (new connection = new subscriber)
conclusion: the entire for loop should be inside a Task. the Task need to wait until the server send the stream to all subscribers. ONLY THEN it should continue to the while loop with ContinueWith (that is why it called like that, right?)
so... the write command need to get execute without await keyword
theSubscriber.WriteAsync

the foreach loop should use a task that continue with the while loop after it is done


text:
Q: Has anyone used NUnitLite with any success? I've recently started work on the Compact Framework and I was wondering if anyone had some recommendations for unit testing beyond what's in VS 2008. MSTest is ok, but debugging the tests is a nightmare and the test runner is so slow.
I see that NUnitLite on codeplex is an option, but it doesn't look very active; it's also in the roadmap for NUnit 3.0, but who knows when that will come out. Has anyone had any success with it?

A: What we've done that really improves our efficiency and quality is to multi target our mobile application.  That is to say with a very little bit of creativity and a few conditional compile tags and custom project configurations it is possible to build a version of your mobile application that also runs on the desktop.
If you put all your business logic you need tested in a separate project/assembly then this layer can be very effectively tested using any of the desktop tools you are already familiar with.

A: We use NUnitLite, although I think we did have had to add some code to it in order for it to work.
One of the problems we found is that if you are using parts of the platform that only exist in CF, then you can only run those tests in NUnitLite on an emulator or Windows Mobile device, which makes it hard to run the tests as part of an integrated build process. We got round this by added a new test attribute allowing you to disable the tests what would only run on the CF (typically these would be p/invoking out to some windows mobile only dll).


text:
Q: Linq to Xml, is it possible to improve this query? I am trying to learn LINQ to XML. I can not write a query correctly. What should I write to retrieve the list of code of the index MCCO?
<Indexes>
    <Index Name="ARTP">
        <Codes>
            aaa
            bbb
        </Codes>
    </Index>
    <Index Name="MCCO">
        <Codes>
            ccc
            ddd
        </Codes>
    </Index>
    <Index Name="AWAY">
        <Value>eee</Value>
    </Index>
</Indexes>

I already wrote this but I feel there is a way to improve query. I assume the fact there are codes (and not values) in my node.
    private List<string> GetCodes(string name)
    {
        var indexes = from index in indexXmlDocument.Descendants("Index")
                      where index.Attribute("Name").Value == name
                      select new
                      {
                          Codes = index.Element("Codes").Elements("Code")
                      };
        List<string> codes = new List<string>();
        foreach (var code in indexes.Single().Codes)
        {
            codes.Add(code.Value);
        }
        return codes;
    }

A: private IEnumerable<string> GetCodes(string name)
{
    return indexXmlDocument.Descendants("Index")
        .Where(e => e.Attribute("Name").Value == name)
        .Descendants("Code")
        .Select(e => e.Value);
}


text:
Q: Scheme how to remove extra message? like ;Value ;Unspecified return value in GNU Scheme I am computer science student in university, and my professor give me assignment about Scheme..
then, i set up the scheme 9.2 version, and try to this but, i'm gonna be crazy because of this![enter image description here][1]
52 error> (display "hi")
hi
;Unspecified return value

what is that? ;Unspecified return value
i wanna just display "hi" !
i have questions, how to remove that and how call like that? error code?, check text? or... what? there is a word?
thanks to read....

A: Your are using the read-eval-print loop. This has the effect that every expression you feed it has a response. If you don't like that you can run the program instead of using the REPL.
How to run a program is not covered by the standard so you need to check the documentation for your chosen implementation.
Here is an example using Ikarus:
#!r6rs
(import (rnrs))

(+ 4 5)
(display "Hello, world!")
(newline)

I've saved it as test.scm and I start it like this:
$ ikarus --r6rs-script  test.scm
Hello, world!
$

Notice the result of (+ 4 5) is not displayed. It is dead code since the value is calculated, but then thrown away since it is not used and then continues to evaluate the next expression. Nothing is printed unless you explicit ask it to. In Ikarus REPL you'll see this:
> (+ 4 5)
9
> (display "Hello, world!")
Hello, world!> (newline)

>

It doesn't print the undefiend value #<void>> in the Ikarus REPL. To see it you need to display it:
(display (if #f #t))
; ==> #<void> (not printed by the REPL), but `display` will print `#<void>`


text:
Q: Multiple web application deployment targets in Visual Studio 2008? I currently maintain several different environments for a single application - production, staging, development, etc .
I was wondering if there was a setting or an add-in for visual studio that would facilitate publishing to multiple deployment targets (preferabbly with a different web.config for each target)?
I'm considering writing a couple of nant scripts instead but it would be nice if there was an integrated solution.

A: It's not possible in VS 2008 out of the box. I don't know if there's an addin for this, but you could try searching VisualStudio Gallery.
From what I've seen from demo videos, VS2010 will support having different web.configs, and deploying to dev/staging/production.


text:
Q: How to implement a vertical and horizontal scroll bar in WinForms when using paint? In my code I draw a rectangle and usually the rectangle is too large for the screen, even when maximised. I have set the form property AutoScroll to true and this doesn't seem to do anything. There won't be anything else on my form except the rectangle painting, how can I implement a vertical and horizontal scroll?
 PrintingDesignForm form = new PrintingDesignForm();

        form.Paint += (se, pe) => {
            var r = new Rectangle(parameters.RectangleXPosition, parameters.RectangleYPosition, (int)Math.Ceiling(parameters.RectangleWidth) * 72, (int)Math.Ceiling(parameters.RectangleLength) * 72);

            var brush = new SolidBrush(Color.FromArgb(255, 255, 204));

            pe.Graphics.FillRectangle(brush, r);
            using (var pen = new Pen(brush.Color, 2))
                pe.Graphics.DrawRectangle(pen, r);
        };

        form.WindowState = FormWindowState.Maximized;
        form.Show();

A: In Form Properties Set

AutoScroll = True

A: Setting AutoScroll = true on a Control/Form  alone will only ensure that all Controls you add/nest to the parent will either show or can be reached by the scrollbars which will show up as needed.
This doesn't do anything for stuff you draw.
To make the drawing scrollable you need to set the AutoScrollMinSize to large enough values.
If you don't know in advance then at least while drawing you should be able to determine them from your data.


text:
Q: New screenshots/files not visible in Finder in Catalina, well visible when using a file manager like Nimble Commander Pro I've set the permissions to the 'screenshots' folder 'read & write' for all users in the list.  The screenshot app is added to have full rights on the drive in the settings...  I don't understand why I can't see the new screenshots via Finder but via any file manager, is not an issue.  Is there someone that can plz let me know what I'm doing wrong?  I'm Catalina since a few hours only, and this really works on my nerves... :-(. I noticed that I can't see newly added or created files either in the Finder!  If you ask me, this is not really an improvement!

A: The problem is solved after performing the macOS 10.15.1 update.
Seems it's not solved at all!
It happens once a while, with no reasons and when this happens, only a reboot helps!


text:
Q: Python request post doesn't get redirected When I use Chrome to post a from on this website: "http://xh.5156edu.com/index.php", I get redirected to a new page. However, when I use python request module to do the post, like this:
r = requests.post("http://xh.5156edu.com/index.php", data="f_key=%B7%AB&SearchString.x=0&SearchString.y=0")

the status code is 200 and the content is not what I want. I'am sure the data is the same as the one sent by Chrome. I can not understand what's wrong with the scripts. I also tried to add some headers, which didn't work neither.

A: What you're passing as data are actually query parameters.
This is what you need:
import requests
params = {'f_key': '%B7%AB', 'SearchString.x': '0', 'SearchString.y': '0'}
(r := requests.post("http://xh.5156edu.com/index.php", params=params)).raise_for_status()
with open('x.html', 'w') as html:
    html.write(r.text)

You can then open x.html to view the response


text:
Q: Strange .txt File Appeared on Desktop A strange .txt file appeared on my desktop today. Technically, it seemed to have been created one day ago, but it was only recently that I discovered it. The following were its contents when I opened it up:
'ma1 hour agoNo one'
And it was titled 'ma1 hour ag'.
It may also be worth mentioning that it was hidden away beneath the Quick Launch Bar, which explains why I didn't notice it before, but I'm confused as to: a) Where did the file even come from, and b) When I tried to re-tuck it beneath the bar, it was literally impossible to do. So how did it end up there in the first place?
I'm real freaked out by the ominous tone of the text and would appreciate any help figuring out how this could have possibly happened. Thanks in advance.

A: It looks like part of a comment from a blog or social media site was copy/pasted.
For example, a comment like this might have been partially highlighted then copied to the clipboard.
Emma
1 Hour ago
No one cares, dude.

Highlighting text is very easy to do accidentally, as is copying to clipboard and pasting. All it takes is mouse button clicks. Text files can also be created with the right-click menu. It could happen by accident, especially if children or pets are around.


text:
Q: How can I cast const unsigned char * to uint8 * I am using a API function where data should be passed as (uint8 *) type.
But I am getting data of type (const unsigned char *) form.
Here is my sample implementation:
virtual int
  read_data (uint32 addr, unsigned char *buf, size_t *nbytes)
    {
        MemRead (addr, buf, nbytes);
        return 0;
    }

getting following error:

error: invalid conversion from 'const unsigned char*' to
                                          'uint8* {aka unsigned char*}' [-fpermissive]

so, how can I manage cast from const unsigned char* to uint8 *.

A: Simply prepend (uint8*) to your buf argument:
MemRead (addr, (uint8*)buf, nbytes);
EDIT:
I overlooked that the buf pointer is not declared as const. The cast at this point is unnecessary as stated in some comments. However casting can be done by prepending (uint8*). If this is good practice is another question.


text:
Q: Custom color mapping based on function in matplotlib I'm plotting a scatterplot using matplotlib in python. I want to color the points based on some function, like so:
import matplotlib.pyplot as plt

def color(x, y):
    # based on some rules, return a color
    if(condition):
        return 'red'
    else:
        return 'blue'

plt.scatter(index, data) #c= something?

I'm aware of the matplotlib.from_levels_and_colors function, but the problem is that the mapping isn't based on levels of the values on the x or y axes. There's a third value associated with each data point that is calculated by the function, and that's what I want to color the dots based on.
Is there a way to do this?

A: Why don't you just make your c array an indicator function for a default colormap.  For example:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = np.arange(100)
# Colors whether or not x+y is a multiple of 5
c = (x + y)%5 == 0

# Use 'jet' colormap for red/blue.
plt.scatter(x, y, c=c, cmap='jet')

Of course you could use a colormap with different extremes that will get mapped to 0 and 1.
If your desired result has more than 2 colors, then it's totally fine to pass as c an array with many different values (and it doesn't need to be normalized).  See here for an example.

A: This is the way I ended up doing it. I created a list of colors based on the x and y values, and then passed that to the scatter function. Not as nice as wflynny's answer, but it does mean you can do as much computation as needed to come up with the array, rather than having to create a single function to do it.
import matplotlib.pyplot as plt

colors = calculate_colors(x, y)
plt.scatter(index, data, c=colors)


text:
Q: What does exec sp_updatestats do? What is the use of sp_updatestats? Can I run that in the production environment for performance improvement?

A: sp_updatestats updates all statistics for all tables in the database, where even a single row has changed. It does it using the default sample, meaning it doesn't scan all rows in the table so it will likely produce less accurate statistics than the alternatives.
If you have a maintenance plan with 'rebuild indexes' included, it will also refresh statistics, but more accurate because it scans all rows. No need to rebuild stats after rebuilding indexes.
Manually updating particular statistics object or a table with update statistics command gives you much better control over the process. For automating it, take a look here.
Auto-update fires only when optimizer decides it has to. There was a change in math for 2012: in <2012, auto update was fired for every 500 + 20% change in table rows; in 2012+ it is SQRT(1000 * Table rows). It means it is more frequent on large tables. Temporary tables behave differently, of course.
To conclude, sp_updatestats could actually do more damage than good, and is the least recommendable option.


text:
Q: How to assign a Ref to a button in a React component if I don't own that code? I want to focus it I'm working on React. There's another team which exposes us a component which has a button in it. It is a dependency for our repository. I want that button to be focused when a particular action is done. I want to do it using refs or any other acceptable way.
myCode.js
focusExternalButton() {
  // some code that focuses the button in the external component
}

render() {

  return {

      <ExternalButtonComponent/>
      <button onClick={this.focusExternalButton}>submit</button>

  }
}

ExternalButtonComponent.js
render() {
  return
<button id="btn-external">This is a button</button>

}

How do I put focus on the external button when I click my button? I'm thinking of refs but I'm not sure how I can achieve it.

A: It surprises me a little that the external component uses ids as rendering it more than once in a page will lead to duplicate ids on the page which isn't valid HTML.
Nonetheless, yes, you can query the DOM directly, though I would probably do this once on mount and store the result returned element in a ref.

const { useEffect, useRef } = React;

function App() {
  const buttonRef = useRef();

  useEffect(() => {
    buttonRef.current = document.getElementById('btn-external');
  }, []);

  function focusExternalButton() {
    buttonRef.current.focus();
  };

  return (

      <ExternalButtonComponent label="This is a button" />
      <button type='button' onClick={focusExternalButton}>submit</button>

  );
}

function ExternalButtonComponent({label}) {
  return
<button id="btn-external">{label}</button>
;
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
#btn-external:focus { box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);}

However, to avoid having to do this every time you use the component you can wrap the external component and forward the ref.
const WrappedExternalButtonComponent = forwardRef((props, ref) => {
  useEffect(() => {
    ref.current = document.getElementById('btn-external');
  }, []);

  return <ExternalButtonComponent {...props} />
});

const { useEffect, useRef, forwardRef } = React;

const WrappedExternalButtonComponent = forwardRef((props, ref) => {
  useEffect(() => {
    ref.current = document.getElementById('btn-external');
  }, []);

  return <ExternalButtonComponent {...props} />
});

function ExternalButtonComponent({label}) {
  return
<button id="btn-external">{label}</button>
;
}

function App() {
  const buttonRef = useRef();

  function focusExternalButton() {
    buttonRef.current.focus();
  };

  return (

      <WrappedExternalButtonComponent ref={buttonRef} label="This is a button" />
      <button type='button' onClick={focusExternalButton}>submit</button>

  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
#btn-external:focus { box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);}

Or even generalize it further by creating a utility that takes a Component and a query function as arguments and returns a wrapped component.
const wrapExternalComponent = (Component, query) => forwardRef(({ children, ...props }, ref) => {
  useEffect(() => {
    ref.current = query();
  }, []);

  return (
    <Component {...props}>
      {children}
    </Component>
  );
});

const WrappedExternalButtonComponent =
  wrapExternalComponent(ExternalButtonComponent, () => document.getElementById('btn-external'));

const { useEffect, useRef, forwardRef } = React;

const wrapExternalComponent = (Component, query) => forwardRef(({ children, ...props }, ref) => {
  useEffect(() => {
    ref.current = query();
  }, []);

  return (
    <Component {...props}>
      {children}
    </Component>
  );
});

function ExternalButtonComponent({label}) {
  return
<button id="btn-external">{label}</button>
;
}

const WrappedExternalButtonComponent =
  wrapExternalComponent(ExternalButtonComponent, () => document.getElementById('btn-external'));

function App() {
  const buttonRef = useRef();

  function focusExternalButton() {
    buttonRef.current.focus();
  };

  return (

      <WrappedExternalButtonComponent ref={buttonRef} label="This is a button" />
      <button type='button' onClick={focusExternalButton}>submit</button>

  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
#btn-external:focus { box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);}


text:
Q: Power BI how to display latest value of a column based on date slicer and filter? I have a Power BI table looks like this:

Cat
Price
Date

apple
2.0
03/21/2021

peach
3.0
03/22/2021

apple
1.8
03/18/2021

apple
2.0
03/19/2021

peach
3.1
03/20/2021

apple
1.7
03/17/2021

I want to use a date slicer and Cat filter to choose the latest price for Apple and display in a tile:
Date Slicer: 03/12/2021 - 03/21/2021
Filter: check 'apple'
Tile display:  2.0
I tried
price_LastValue := CALCULATE(SUM(fruit[Price]), LASTDATE(fruit[Date]))

but the result is BLANK. Any thoughts?

A: price_LastValue =
VAR _tbl = ALLSELECTED(Table1)
VAR _max_date = MAXX(_tbl, [Date])
RETURN MINX(FILTER(_tbl, [Date] = _max_date), [Price])


text:
Q: Can't Get Data for Simple Login with HTML to PHP Web Service I try to access login service from some web service for user validation directly to html page using jquery, but it seems not working, even when I access the web service with browser the web service work perfectly. Here is the html code:

    <link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
    <link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">

        Home

Login

    <input id="username" type="text" placeholder="username" />
    <input id="password" type="password" placeholder="password" />
    <button id="login">Login</button>

Even the "beforeSend" code is not working, I mean when I click on Login button the text on it doesn't change to Connecting. How can I make it work?

A: email is not defined before
$.trim(email)

Change it to and the connecting... will appear
$.trim(username)

A: Replace
$.trim(email).length

To
$.trim(username).length

One more problem in code in success function;
/* Now */
}else if(data.success="false"){

/* should be == because here we are comparing not assigning */
}else if(data.success=="false"){

/* OR we can remove if part completely because we don't need any comparison if not success  */
}else{

One more thing if we are getting the response as true or false i don't thing it would be string value, it would be Boolean so update code for success function like following:
success: function(data){
  if(data.success){
    localStorage.login = "true";
    localStorage.username = username;
    window.location.href = "index.html";
  }else{
    alert("Login error");
    $("#login").html('Login');
  }
}

And one more problem your code won't execute because here you are trying to reference element that not loaded that is login button;
Use following code with all fixes;

    <link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
    <link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">

      Home

Login

    <input id="username" type="text" placeholder="username" />
    <input id="password" type="password" placeholder="password" />
    <button id="login">Login</button>

A: change $.trim(email).length

To
 $.trim(username).length


text:
Q: C# BarCode Scanning Program won't Accept Alphabetic Characters I've some code written in C# that allows the user to scan a barcode, and the label.Text changes to the input of the barcode. I used a label instead of textbox to prevent the user from fat-fingering a wrong barcode -basically disabling any keyboard input.
Everything works nice, except when the barcode being scanned has alphabetic characters in it. If the barcode starts with an alphabetic character and ends with an alphabetic character, then the barcode doesn't scan at all.
If the barcode starts with an alphabetic character, but ends with numeric characters, the program picks up only the trailing numeric characters.
Here's the code:
    char cforKeyDown = '\0';
    int _lastKeystroke = DateTime.Now.Millisecond;
    List<char> _barcode = new List<char>();
    bool UseKeyboard = false;

  private void Form1_Load(object sender, EventArgs e)
    {
        this.ActiveControl = label1;
        this.KeyDown += new KeyEventHandler(Form1_KeyDown);
        this.KeyUp += new KeyEventHandler(Form1_KeyUp);
    }
 private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        // if keyboard input is allowed to read
        if (UseKeyboard && e.KeyData != Keys.Enter)
        {
            MessageBox.Show(e.KeyData.ToString());
        }

        /* check if keydown and keyup is not different
         * and keydown event is not fired again before the keyup event fired for the same key
         * and keydown is not null
         * Barcode never fired keydown event more than 1 time before the same key fired keyup event
         * Barcode generally finishes all events (like keydown > keypress > keyup) of single key at a time, if two different keys are pressed then it is with keyboard
         */

        if (cforKeyDown != (char) e.KeyCode || cforKeyDown == '\0')
        {
            cforKeyDown = '\0';
            _barcode.Clear();
            return;
        }

        // getting the time difference between 2 keys
        int elapsed = (DateTime.Now.Millisecond - _lastKeystroke);

        /*
         * Barcode scanner usually takes less than 17 milliseconds to read, increase this if neccessary of your barcode scanner is slower
         * also assuming human can not type faster than 17 milliseconds
         */
        // Bumped it up to 35[ms]
        if (elapsed > 50)
            _barcode.Clear();

        // Do not push in array if Enter/Return is pressed, since it is not any Character that need to be read
        if (e.KeyCode != Keys.Return)
        {
            //_barcode.Add((char) e.KeyData);
            _barcode.Add((char) e.KeyData);
        }

        // Barcode scanner hits Enter/Return after reading barcode
        if (e.KeyCode == Keys.Return && _barcode.Count > 0)
        {
            string BarCodeData = new String(_barcode.ToArray());

            if (!UseKeyboard)
            {
                //MessageBox.Show(String.Format("{0}", BarCodeData));
                label1.Text = String.Format("{0}", BarCodeData);
            }
            //_barcode.Clear();
        }
        // update the last key stroke time
        _lastKeystroke = DateTime.Now.Millisecond;
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        //Debug.WriteLine("CS_Single_Label_Printer_KeyDown : " + (char)e.KeyCode);
        cforKeyDown = (char) e.KeyCode;
    }

I've narrowed down the problem to the fact that the alphabetic parts of the alpha-numeric barcodes being scanned are uppercase. I generated a test barcode using lower-case letters, and everything worked as it should, but this still doesn't fix the problem as I have to scan thousands of already printed barcodes that have uppercase characters encoded into the barcode data matrix.
Is there a way to switch the above code in order to account for the 'character | Shift' KeyData?

A: The answer is that KeyCode returns the KEY pressed. It does not respect the case of the key. Use Shift to get the case. Below is a working example based on your supplied code. The magic is in the local function ToCharacter. You'll need to play with the if statements at the top to include numbers too if that's your desire.
From1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DesktopApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        char cforKeyDown = '\0';
        int _lastKeystroke = DateTime.Now.Millisecond;
        List<char> _barcode = new List<char>();
        bool UseKeyboard = false;

        private void Form1_Load(object sender, EventArgs e)
        {
            this.ActiveControl = InputBox;
            this.InputBox.KeyDown += new KeyEventHandler(Form1_KeyDown);
            this.InputBox.KeyUp += new KeyEventHandler(Form1_KeyUp);
        }
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            char NotALetter = '-';

            DebugBox.Items.Clear();
            DebugBox.Items.Add($"KeyEventArgs->KeyCode = {e.KeyCode.ToString()}");
            DebugBox.Items.Add($"KeyEventArgs->KeyData = {e.KeyData.ToString()}");
            DebugBox.Items.Add($"KeyEventArgs->KeyValue = {e.KeyValue.ToString()}");
            DebugBox.Items.Add($"KeyEventArgs->e.Shift = {e.Shift.ToString()}");
            DebugBox.Items.Add($"ToCharacter = {ToCharacter(e) ?? NotALetter}");

            char? ToCharacter(KeyEventArgs kea)
            {
                int DtoNumPadOffset = (int)(Keys.NumPad0 - Keys.D0);
                if (kea.KeyCode < Keys.D0) return null; // Keys.D0 through Kyes.D9 are the Keys on the top row of the keyboard. D9 is right next to A in the enum type.
                if (kea.KeyCode > Keys.NumPad9) return null;
                if (kea.KeyCode > Keys.Z && kea.KeyCode < Keys.NumPad0) return null; //knocks out keys between Z and NumPad0
                if (kea.Shift && kea.KeyCode < Keys.A) return null; // rejects special characters when numbers across the top are used with the <shift> key.

                if (kea.KeyCode < Keys.A) return (char)kea.KeyCode;
                if (kea.KeyCode > Keys.Z) return (char)((int)kea.KeyCode - DtoNumPadOffset);

                return kea.Shift
                    ? (char)kea.KeyCode
                    : char.ToLower((char)kea.KeyCode);
            }

            // if keyboard input is allowed to read
            if (UseKeyboard && e.KeyData != Keys.Enter)
            {
                MessageBox.Show(e.KeyData.ToString());
            }

            /* check if keydown and keyup is not different
             * and keydown event is not fired again before the keyup event fired for the same key
             * and keydown is not null
             * Barcode never fired keydown event more than 1 time before the same key fired keyup event
             * Barcode generally finishes all events (like keydown > keypress > keyup) of single key at a time, if two different keys are pressed then it is with keyboard
             */

            //if (cforKeyDown != (char)e.KeyCode || cforKeyDown == '\0')
            //{
            //    cforKeyDown = '\0';
            //    _barcode.Clear();
            //    return;
            //}

            // getting the time difference between 2 keys
            int elapsed = (DateTime.Now.Millisecond - _lastKeystroke);

            /*
             * Barcode scanner usually takes less than 17 milliseconds to read, increase this if neccessary of your barcode scanner is slower
             * also assuming human can not type faster than 17 milliseconds
             */
            // Bumped it up to 35[ms]
            //if (elapsed > 2000)
            if (e.KeyCode == Keys.Return)
            {
                InputBox.Text = String.Empty;
                _barcode.Clear();
            }

            // Do not push in array if Enter/Return is pressed, since it is not any Character that need to be read
            if (e.KeyCode != Keys.Return)
            {
                char? TestForCharacter = ToCharacter(e);

                if (TestForCharacter != null)
                {
                    //_barcode.Add((char) e.KeyData);
                    _barcode.Add((char)TestForCharacter);
                }
            }

            OutputBox.Text = string.Concat(_barcode);

            // Barcode scanner hits Enter/Return after reading barcode
            if (e.KeyCode == Keys.Return && _barcode.Count > 0)
            {
                string BarCodeData = new String(_barcode.ToArray());

                if (!UseKeyboard)
                {
                    //MessageBox.Show(String.Format("{0}", BarCodeData));
                    OutputBox.Text = String.Format("{0}", BarCodeData);
                }
                //_barcode.Clear();
            }
            // update the last key stroke time
            _lastKeystroke = DateTime.Now.Millisecond;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            //Debug.WriteLine("CS_Single_Label_Printer_KeyDown : " + (char)e.KeyCode);
            cforKeyDown = (char)e.KeyCode;
        }
    }
}

Form1.Designer.cs
namespace DesktopApp2
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.OutputBox = new System.Windows.Forms.TextBox();
            this.InputBox = new System.Windows.Forms.TextBox();
            this.DebugBox = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            //
            // OutputBox
            //
            this.OutputBox.Location = new System.Drawing.Point(52, 93);
            this.OutputBox.Name = "OutputBox";
            this.OutputBox.ReadOnly = true;
            this.OutputBox.Size = new System.Drawing.Size(650, 22);
            this.OutputBox.TabIndex = 1;
            //
            // InputBox
            //
            this.InputBox.Location = new System.Drawing.Point(52, 45);
            this.InputBox.Name = "InputBox";
            this.InputBox.Size = new System.Drawing.Size(650, 22);
            this.InputBox.TabIndex = 2;
            //
            // DebugBox
            //
            this.DebugBox.FormattingEnabled = true;
            this.DebugBox.ItemHeight = 16;
            this.DebugBox.Location = new System.Drawing.Point(52, 131);
            this.DebugBox.Name = "DebugBox";
            this.DebugBox.Size = new System.Drawing.Size(650, 308);
            this.DebugBox.TabIndex = 3;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(716, 450);
            this.Controls.Add(this.DebugBox);
            this.Controls.Add(this.InputBox);
            this.Controls.Add(this.OutputBox);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        private System.Windows.Forms.TextBox OutputBox;
        private System.Windows.Forms.TextBox InputBox;
        private System.Windows.Forms.ListBox DebugBox;
    }
}

Tidy helper class for dealing with KeyEventArgs
The Is* functions group the keycodes into ranges and detect (if appropriate) the shift states. To* functions produce the char that best represents the KeyCode in the event. ToAlphaNumericAsciiCharacter simply pairs up detectors with producers.
public static class KeyEventArgs_Functions
{
    public static bool Between(this Keys source, Keys lhv, Keys rhv)
    {
        return source >= lhv && source <= rhv;
    }
    public static bool IsLetterKeyBoardChar(this KeyEventArgs source)
    {
        return source.KeyCode.Between(Keys.A, Keys.Z);
    }
    public static bool IsNumberKeyBoardChar(this KeyEventArgs source)
    {
        return !source.Shift && source.KeyCode.Between(Keys.D0, Keys.D9);
    }
    public static bool IsNumber10KeyPadChar(this KeyEventArgs source)
    {
        return source.KeyCode.Between(Keys.NumPad0, Keys.NumPad9);
    }
    public static char ToLetterKeyBoardChar(this KeyEventArgs source) // Only returns a valid value if IsLetterKeyBoardChar returns true.
    {
       return source.Shift ? (char)source.KeyCode: char.ToLower((char)source.KeyCode);
    }
    public static char ToNumberKeyBoardChar(this KeyEventArgs source) // Only returns a valid value if IsNumberKeyBoardChar returns true.
    {
        return (char)source.KeyCode;
    }
    public static char ToNumber10KeyPadChar(this KeyEventArgs source) // Only returns a valid value if IsNumber10KeyPadChar returns true.
    {
        const int DtoNumPadOffset = (int)(Keys.NumPad0 - Keys.D0);
        return (char)((int)source.KeyCode - DtoNumPadOffset);
    }
    public static char? ToAlphaNumericAsciiCharacter(this KeyEventArgs source)
    {
        if (source.IsLetterKeyBoardChar()) return source.ToLetterKeyBoardChar();
        if (source.IsNumberKeyBoardChar()) return source.ToNumberKeyBoardChar();
        if (source.IsNumber10KeyPadChar()) return source.ToNumber10KeyPadChar();
        return null;
    }
}


text:
Q: Having difficulty creating the computer side moves in Tic Tac Toe using rand() function I've been trying to make a tic tac toe game.
I had first coded a two-player game which works but then tried to make one side computerized by placing a marker on random slot but can't exactly find the issue with why it's not working properly.
We get the first chance and choose the marker but after that the comp should play one slot but instead it asks us again the play the second move.
Mostly the function writing and order of calling it is getting jumbled, any help is appreciated!
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

char current_marker;
int current_player;
int comp_slot;

void drawBoard(){
    cout<< "     |       |    "<<endl;
    cout<<"  "<<board[0][0]<<"  |   "<<board[0][1]<<"   |   "<<board[0][2]<<endl;
    cout<< "_____|_______|_____"<<endl;
    cout<< "     |       |    "<<endl;
    cout<<"  "<<board[1][0]<<"  |   "<<board[1][1]<<"   |   "<<board[1][2]<<endl;
    cout<< "_____|_______|_____"<<endl;
    cout<< "     |       |    "<<endl;
    cout<<"  "<<board[2][0]<<"  |   "<<board[2][1]<<"   |   "<<board[2][2]<<endl;
    cout<< "     |       |     "<<endl;
}

bool placeMarker(int slot){
    int row = slot/3;
    int col;
    if(slot % 3 == 0){
        row = row - 1;
        col = 2;
    }
    else{
       col = (slot % 3) - 1;
    }

    if(board[row][col] != 'X' && board[row][col] != 'O'){
        board[row][col] = current_marker;
        return true;
    }
    else return false;
}

int winner(){
    for(int i=0; i<9; i++){
        //row
        if(board[i][0] == board[i][1] && board[i][1] && board[i][2]){
            return current_player;
        }

        if(board[0][i] == board[1][i] && board[1][i] == board[2][i]){
            return current_player;
        }
    }

    //for diagonals
    if(board[0][0] == board[1][1] && board[1][1] == board[2][2]){
        return current_player;
    }

    if(board[0][2] == board[1][1] && board[1][1] == board[2][0]){
        return current_player;
    }

    return 0;
}

void swap_player_marker(){
    if(current_marker == 'X') current_marker = 'O';
    else current_marker = 'X';

    if(current_player == 1) current_player = 2;
    else current_player = 1;
}

void game(){
    //players
    string name1, name2;
    cout<<"Enter your name: ";
    cin>>name1;

    cout<<name1<<" choose your marker: ";
    char h_marker; //X
    cin>>h_marker;

    current_player = 1;
    current_marker = h_marker; //X

    drawBoard();
    int player_won;

    for(int i=0; i<4; i++){
        cout<<"It's your turn. Enter slot: ";
        int slot;
        cin>> slot;

        if(slot < 1 || slot > 9){
            cout<<"Slot invalid! Try another slot!"<<endl;
            i--;
            continue;
        }

        if(!placeMarker(slot)){
            cout<<"Slot occupied! Try another slot!"<<endl;
            i--;
            continue;
        }

        drawBoard();

        player_won = winner();
        if(player_won == 1){
            cout<<"You won! Congratulations!";
            break;
        }

        if(player_won == 2){
            cout<<"Comp won! Congratulations!";
            break;
        }

        int comp_slot = (rand() % (10 - 1 + 1)) + 1;

        if(!placeMarker(comp_slot)){
            cout<<"Slot occupied! Try another slot!"<<endl;
            i--;
            continue;
        }

        swap_player_marker();

    }

    if(player_won == 0){
        cout<<"This game is a TIE";
    }
}

int main(){
    game();
}

A: Add srand((undesigned)time(0)) before using rand, Otherwise the number will repeat itself every time.


text:
Q: Appropriate distribution for simulating a random walk between two known points, with known min/max values I have a 1-D random walker. It starts at a value of x at time t=0. It ends with a value of y at time t=1. Along the way, it hits a low of w, and a high of z. I know nothing about its path except the endpoints and the min/max values achieved.
Suppose I want to simulate the behavior of this random walker. So at any given time t between 0 and 1, I need to be able to sample from a realistic distribution with the described endpoint and extremes. What would be an appropriate distribution for this task?
Properties of distribution function f(t)

*

*f(0)=x

*f(1)=y

*The central tendency should be weighted towards x at values close to t=0, and should lean more and more towards y as t approaches 1.

*The variance should scale according to w and z, should be greatest at t=0.5, and should go to zero at t=0 and t=1.

*The the tails of the probability distributions should go to zero at w and z, without abrupt discontinuity (i.e. it shouldn't be truncated).

Possible options?

*

*A beta distribution visually looks like it has the right properties, but I'm not entirely sure how to interpret its parameters as a random walk scenario.

*I understand that Rayleigh distributions describe random walks, but I'm not sure how one might incorporate the concept of knowing the bounds and final value of the walk.

A: After a couple of days hammering away at this, I think I have a workable solution, reparameterizing a beta distribution. The key insight (from this answer) was to solve for the beta distribution parameters $\alpha$ and $\beta$ as functions of the mean $\mu$ and variance $\sigma^2$. Then, I just had to decide how $\mu$ and $\sigma^2$ should vary with $t$ on the interval $[0,1]$.
As a reminder:
$w$ = min boundary,
$x$ = starting value,
$y$ = final value,
$z$ = max boundary
So then from $t=0$ to $t=1$, $\mu$ can travel linearly from $x$ to $y$. The simplest form of this would be:
$$\mu = x (1 - t) + yt$$
Next is the variance and standard deviation. At $t=0$ and $t=1$, the function value is exactly known (equivalent to the starting or end point mean), so $\sigma=0$. The simplest version of this would be:
$$\sigma=C*t(1-t)$$
In the middle ($t=0.5$), where the time is furthest from the two endpoints, we have the least information about the location of the random walker, so then the distribution should be approximately normal, spread across the entire interval. Thus, the min and max should each be about 3 standard deviations from the mean at that time:
$$z-w=6*\sigma(t=0.5)$$
rearranges to:
$$\sigma(t=0.5)=(\frac{z-w}6)$$
Solve the previous equation for $C$ in this scenario:
$$\sigma(t=0.5)=C*0.5(1-0.5)$$
$$C=4*\sigma(t=0.5)$$
$$C=4(\frac{z-w}6)$$
Finally:
$$\sigma=4(\frac{z-w}6)*t(1-t)$$
But the beta distribution is only defined on the interval $[0,1]$, so we can just set $w$ and $z$ to $0$ and $1$ respectively, and rescale everything later:
$$\sigma=4(\frac{1}6)*t(1-t)$$
$$\sigma=\frac{2}3t(1-t)$$
Hence, keeping in mind that $x$ and $y$ are predefined (and should be between $w$ and $z$ on the $[0,1]$ interval, to be rescaled later), these 4 equations fully determine the $\alpha$ and $\beta$ parameters of the beta distribution based on $t$, with all of the desired behaviors and constraints of a 1-D random walk from $x$ to $y$:
$$\mu = x (1 - t) + yt$$
$$\sigma=\frac{2}3t(1-t)$$
$$\alpha=\left(\frac{1-\mu}{\sigma^2}-\frac{1}{\mu}\right)\mu^2$$
$$\beta=\alpha\left(\frac{1}{\mu}-1\right)$$
Plugging in some values of $x$, $y$, and $t$, the plots of these beta distributions give a very convincing simulation!

A: A friend helpfully suggested that this is similar to a Brownian Bridge, and I was able to use that to derive an analytical solution.
Conditions: $w$ = min boundary, $x$ = starting value, $y$ = final value, $z$ = max boundary
1. Incorporating the x and y conditions using a Brownian Bridge
The generalized Brownian Bridge is a specific Wiener Process, defined as a time-dependent normal distribution:
$$B(t)=N(\mu_t,\sigma^2_t)$$
that is tethered at either end by the conditions:
$$B(t_1)=x,\;  B(t_2)=y$$
The mean and variance for this distribution are:
$$\mu_t=x+\frac{t-t_1}{t_2-t_1}(y-x)$$
$$\sigma^2_t=\frac{(t_2-t)(t-t_1)}{t_2-t_1}$$
When our time interval is $[0,1]$, these reduce to:
$$\mu_t=x(1-t) + yt$$
$$\sigma^2_t=t(1-t)$$
But then we have to condition our distribution on the observed min and max values, $w$ and $z$.
2. Min/Max Conditional
The total distribution of points observed across the entire $t\in[0,1]$, $B_T$ will also be normal (Brownian Bridges are proven to be normally distributed at all scales). We want to find the normal distribution that would be expected to have $w$ and $z$ as its min and max observed values.
It can be proven using the joint cumulative distribution functions (CDFs) that $B_T$ has a mean $\mu_T=\frac{1}2(w+z)$ halfway between the endpoints, and a standard deviation $\sigma_T=k(n)*(z-w)$ that depends on the sample size $n$.
For example, a well-known result derived from the normal CDFs is that 99.73% of the normal probability distribution lies within $3\sigma$ on either side of the mean. If we assume that $w$ and $z$ are the only two values observed outside this range, then $0.0027 = \frac{2}n$, giving $n=741$. Since this is the case where $2*3\sigma_T=z-w$, we can use this in our previous standard deviation equation to find $k(741)=\frac{1}6$.
Generalizing, where $p$ is the tail of the normal distribution containing a single extremum, and $z_p$ is the quantile:
$$2(1-p) = \frac{2}n$$
$$p=\frac{n-1}n$$
$$2*z_p\sigma_T=z-w$$
$$\sigma_T=\frac{z-w}{2z_p}$$
We can use the quantile function of the normal distribution to find $\sigma_T$ as a function of $n$:
$$z_p=\sqrt2\text{erf}^{-1}(2p-1)$$
$$z_p=\sqrt2\text{erf}^{-1}\left(\frac{n-2}n\right)$$
$$\sigma_T=\frac{z-w}{2\sqrt2\text{erf}^{-1}\left(\frac{n-2}n\right)}$$
Or, we can just use quantile tables that give us $z_p$ for values of $p\approx p(n)$.
3. Bringing it all together
Our solution will be a particular Wiener Process distribution that behaves like the Brownian Bridge, but also adds up over time to the total distribution described in Part 2:
$$W(t)\sim B(t)$$
$$B_T=\int_{0}^{1}W(t)dt$$
A helpful property is that the product of two independent normal distributions is another normal distribution. So, we can decompose our desired model into the joint probability of $B(t)$ and an independent, time-invariant normal distribution $N_C$:
$$W(t)\ = N_CB(t)$$
$$B_T=N_C\int_{0}^{1}B(t)dt$$
The time-integral of a Brownian or Wiener process is another specific normal distribution:
$$B_T=N_CN(0,\tfrac13)$$
In general, the product of two normal distributions is the normal distribution with mean and variance as:
$$\mu=\frac{\mu_1\sigma^2_2+\mu_2\sigma^2_1}{\sigma^2_1+\sigma^2_2}$$
$$\sigma^2=\frac{\sigma^2_1\sigma^2_2}{\sigma^2_1+\sigma^2_2}$$
So then $N_C$ is fully specified by:
$$\sigma^2_T=\frac{\sigma^2_C\tfrac13}{\sigma^2_C+\tfrac13}$$
$$\sigma^2_C=\frac{\sigma^2_T}{1-3\sigma^2_T}$$
and
$$\mu_T=\frac{\tfrac13\mu_C+0}{\sigma^2_C+\tfrac13}$$
$$\mu_C=\mu_T(3\sigma^2_C+1)$$
$$\mu_C=\frac{\mu_T}{1-3\sigma^2_T}$$
Finally, we can use the same property to fully specify our model $W(t)=N_CB(t)=N(\mu_W,\sigma_W^2)$ in terms of the values solved for in Parts 1 and 2:
$$\mu_W=\frac{\mu_C\sigma^2_t+\mu_t\sigma^2_C}{\sigma^2_C+\sigma^2_t}$$
$$\sigma_W^2=\frac{\sigma^2_C\sigma^2_t}{\sigma^2_C+\sigma^2_t}$$


text:
Q: My MySQL server time is not the same as my Server So a month ago I had purchased a server from a hosting company.
The info are;
Linux Centos (latest version).
I installed ZPanel which installs phpMyAdmin, MySQL and all the other good stuff. Anyway, I have managed to change my SERVER time to my local time which is GMT. However when I try to set it on my MySQL server it shows the right time, but when I use the
now()

function in PHP, the time stores +1 hour ahead of my current time, which pretty much messes up my system.
Does anyone know how to fix this? Please It's been a few weeks, yet nothing to fix it :/
Thank you.

A: I had this exact same problem after I had updated my server time. I just had to restart the MySql server then it reset the time to match my server time.
/etc/init.d/mysqld restart

Reference - https://major.io/2007/07/01/mysql-time-zone-different-from-system-time-zone/

A: If you can't get the server and SQL server in sync, in PHP, you could always use this workaround...
$date = date('D jS M Y, G:i:s a', strtotime('-1 hour'));

instead of now();
If you used shared hosting, you can often contact the support to change the default time zone for you.. I had to do that with ixwebhosting and they did it for me no problems.
This is complicated though because MySQL stores 'datetime' data type fields internally as UTC, but PhpMyAdmin shows you the dates using the server default time.. This can often cause confusion.
You can try adding this line before your SQL statement in PhpMyAdmin:
SET @@session.time_zone='+00:00'; SELECT * FROM TableName

or
SET time_zone = '+00:00'; SELECT now();

If you have SUPER privelege you can also set the system time by using the following..
SET GLOBAL time_zone = '+00:00';

You can see more here: http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html.

A: In my case my.cnf had wrong setting for timezone, correct format is like this:
default_time_zone=Europe/Riga

Also make sure you have updated mysql timezones via shell like this:
https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
using mysql_tzinfo_to_sql ...


text:
Q: Using a database in an android app I'm new to android development. I've started with an app on eclipse using java which uses a database of locations. My question is, how would I be able to connect my android app which to the database. Also suggest a suitable way of creating the database. Can I create it in mysql and then import in eclipse?

A: Look here.
I hope this will help you.
If you want to use MySQL to insert the data then use web service to send data in XML format from android to web service.

A: This link should explain everything that you need!
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
If you're just using this database for your application to store data, sqlite is a much better choice than mysql and integrates simply into android. I used the very same link above awhile back when I was getting into this stuff. The tutorial is structured in a very easy to read manner and explains everything as it goes. Good luck.


text:
Q: Retrieve properties of a class instance stored in a dictonary After reading this wonderful article about speeding-up looping in Python by using built-in iterators and implicit loops I have tried it in my code. It worked well on many parts, but one small part still annoys me - the values I iterate over are sometimes stored as fields of a class which are the dictionary values, and I can't get rid of looping over my dictionary to retrieve them.
Here is a simplified version of my code:
class Pair:
    def __init__(self):
        self.radius = 0.0

indices = [(x, y) for y in range(5) for x in range(5)]
d = {}
for (x, y) in indices:
    d[x, y] = Pair()
    d[x, y].radius = (x ** 2 + y ** 2) ** 0.5

sub_list = [(1, 2), (2, 3), (3, 4)]

values = [d[ind].radius for ind in sub_list] # <-- main problem

print reduce(lambda x, y: x + y, values)

So the dictionary d have tuples (x, y) as keys and Pair instances as values, and my goal is to sum the radii of the given sub_list of pairs (sub_list could be the entire dictionary). Is there any "broadcasting" technique for that, or the loop in the marked line is inevitable?
BTW - I am a beginner, so any useful comment about the code (including styling and Pythonish will be appreciated.
Thanks!

A: well your code is not so bad, though there's one useless thing, which is your object Pair. You may just as well store the radius as value in the dict:
indices = [(x, y) for y in range(5) for x in range(5)]
sub_list = [(1, 2), (2, 3), (3, 4)]

d = {}

for (x, y) in indices:
    d[x, y] = (x ** 2 + y ** 2) ** 0.5

values = [d[ind] for ind in sub_list] # <-- no problem

print reduce(lambda x, y: x + y, values)

I can't get rid of looping over my dictionary to retrieve them.

Reread your code! You're not looping over the dictionary, you're iterating over the sub_list! Maybe this is a syntax problem, here's how you could rewrite that iteration:
values=[]
for ind in sub_list:
    values.append(d[x, y])

And think about it, what you want is to get the precalculated radius value for each element of the sublist. So there's actually no other way than iterating over the sublist! Whether you do it using a list comprehension or a map is mostly a matter of personal preference, even though the list comprehension is more efficient:
>>> timeit.repeat(lambda: [d[ind] for ind in sub_list])
[0.8207108974456787, 0.8075330257415771, 0.788733959197998]
>>> timeit.repeat(lambda: map(lambda ind: d[ind], sub_list))
[1.6066839694976807, 1.630357027053833, 1.755575180053711]

If you talk about complexity, consider the size of d being m, and the one of values being n, then:
values = [d[ind] for ind in sub_list]

is O(n)!


text:
Q: Spam emails strange wordpress site I'm receiving strange emails can't stop them even using re-captcha in my site where it says they're comming from.

A: My answer to you is that you should redirect your question to https://wordpress.stackexchange.com
You're not giving us any information for your WordPress configuration to help determine what might be happening. I am guessing, but this looks like your form has been exploited. My suggestion would be to disable your forms to see if that stops the traffic. I also suggest you look at your WordPress configurations and disable comments or any other way someone can contact you, since that could be the other issue.
Good luck.


text:
Q: Can Excel read from .Rdata or .RDS flies? Is this possible (preferably without needing to have an R session running at the same time)? I've searched online but I can't see any mention of it...so perhaps not.
Many thanks

A: If your data are in a data frame, write it to a text file with write.table. Use tab as column separator, and it will likely load directly into a spreadsheet


text:
Q: why the shell script works with remote login but failed with GitHub Action I have writed a startup shell script for the project, when I start the script by login the remote server Linux VM-0-16-centos 3.10.0-1160.31.1.el7.x86_64 #1 SMP Thu Jun 10 13:32:12 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux it works fine. But when I execute the script in GitHub Actions, the process exists but seems not working, no log output. When I run this command ssh to remote server like this:
nohup ./tencent-cloud-start-app.sh &!

it works fine, the log could write into files. But when I execute the script from GitHub Actions like this:
- name: Restart server
  uses: appleboy/ssh-action@master
  with:
    host: ${{ secrets.BINGQIAN_HOST }}
    username: ${{ secrets.BINGQIAN_USER }}
    password: ${{ secrets.SSH_BINGQIAN_PASSWORD }}
    script: |
      cd /opt/apps/pydolphin
      nohup /opt/apps/pydolphin/tencent-cloud-start-app.sh >> schedule.log &!
      sleep 20

the schedule.log from /opt/apps/pydolphin is no content, the log from the app itself also did not output log. the process exists but the app logic did not work as expect. I have tried to find out where is going wrong but failed. is it possible to fixed the problem? BTW, this is the startup script looks like:
#!/usr/bin/env bash

set -u

set -e

set -x

#
# const define area
#
PROGRAM_NAME="schedule_spider.py"
CERT_PROGRAM_NAME="cert_check_trigger.py"
CELERY_PROGRAM_NAME="celery"
PYTHON_BIN_PATH="python3.9"

################ terminal old port forward ####################
pgrep -f port-forward | xargs -r kill -9
pgrep -f fedora-proxy-k8s-postgresql | xargs -r kill -9
pgrep -f fedora-proxy-k8s-redis | xargs -r kill -9
pgrep -f postgresql-alive | xargs -r kill -9
pgrep -f redis-alive | xargs -r kill -9

################ start new port forward ####################

nohup ./script/fedora-proxy-k8s-postgresql.sh >> ./script/proxy-postgresql.log &!
nohup ./script/fedora-proxy-k8s-redis.sh >> ./script/proxy-redis.log &!
nohup ./script/keep-port-forwad-postgresql-alive.sh >> ./script/alive-postgresql.log &!
nohup ./script/keep-port-forwad-redis-alive.sh >> ./script/alive-redis.log &!

########################### start app ##############################
#
# stop celery process
#
pgrep -f celery | xargs -r kill -9

#
# stop cert check process
#
ps auxww | grep "cert_check_trigger.py" | grep -v "grep"  | awk '{print $2}' | xargs -r kill -9

sleep 5s
ps auxww | grep "schedule_spider" | grep -v "grep"  | awk '{print $2}' | xargs -r kill -9

sleep 5s

#
# start process
#
count=$(ps -ef | grep ${PROGRAM_NAME} | grep -v "grep" | wc -l)
if [[ ${count} -lt 1 ]]; then
  export PYTHONIOENCODING=utf-8

    export LC_ALL=en_US.utf-8 \
    && export LANG=en_US.utf-8 \
    && nohup celery -A dolphin.tasks.tasks worker \
    --loglevel=WARNING -n editor-pick-worker \
    -Q editor_pick_and_diff_pull --concurrency 2 > /dev/null &

    export LC_ALL=en_US.utf-8 \
    && export LANG=en_US.utf-8 \
    && nohup celery -A dolphin.tasks.tasks worker \
    --loglevel=WARNING -n non-editor-pick-and-diff-pull-worker \
    -Q non_editor_pick_and_diff_pull --concurrency 2 > /dev/null &

    export LC_ALL=en_US.utf-8 \
    && export LANG=en_US.utf-8 \
    && nohup celery -A dolphin.tasks.tasks worker \
    --loglevel=WARNING -n non-editor-pick-and-non-diff-pull-worker \
    -Q non_editor_pick_and_non_diff_pull --concurrency 1 > /dev/null &

  export LC_ALL=en_US.utf-8 && \
  export LANG=en_US.utf-8 && \
  celery -A dolphin.tasks.tasks \
  --broker=redis://default:123456@cruise-redis-master.reddwarf-cache.svc.cluster.local:6379/5 \
  flower --address=0.0.0.0 --port=5555 \
  --basic-auth=floweradmin:123456 > /dev/null &

  # start cert period checker
  nohup ${PYTHON_BIN_PATH} cert_check_trigger.py > /dev/null &

  export LC_ALL=en_US.utf-8 \
    && export LANG=en_US.utf-8 \
    && nohup celery -A dolphin.tasks.tasks worker \
    --loglevel=INFO -n cert-notify-worker \
    -Q cert_expire_check --concurrency 1 > /dev/null &

  ${PYTHON_BIN_PATH} schedule_spider.py > /dev/null
    sleep 3
else
    echo "unable to start app, process already exists!"
fi


text:
Q: Passing a value into a function jquery ? which is the correct way to pass element_old to the element.change function?
  $('body').on('click', 'input', function(){
      element = $(this);
      element_old = element.val();

      element.change( function(element_old){
        if($(this).val() != element_old){ show button}
        else{ hide button }

      })

    });

I want to show a button only if the input value has changed from its original value.

A: Sample Code
HTML:
<input  id="txtCustom" data-defaultText="Hello" />

jQuery:
$("#txtCustom").on('input',function(){
    var self=$(this);
    var changedValue=self.val();
    var defaultValue=self.attr("data-defaultText");

    if(changedValue==defaultValue){
     //  Hide buttob
    }else {
     // show butto=n
    }

});

A: this solution works fine for me :)
  $('body').on('change', 'input', function(e){
      var x = $( '#q' ).prop( 'defaultValue' );
      if(x!=$( '#q' ).val() ){
       show button;
      }
    });


text:
Q: Disable Textbox based on CanExecute of command I have a button and a Textbox, I've setup the button to a command using MVVM, INotifyPropertyChanged and MVVM.
However I want the Textbox to be disabled when the CanExecute method of the command returns false, i.e. I want the Textbox to be disabled when the button is disabled.
How do I hook a Textbox only to a command's CanExecute?

A: A TextBox doesn't have a Command property that you can bind directly to an ICommand source property.
Depending on the relationship between the TextBox and the Button in the view, you may bind the former's IsEnabled property to the second's:
<Button x:Name="btn" Content="..." Command="{Binding Command}" />
<TextBox IsEnabled="{Binding IsEnabled, ElementName=btn}" />

This only works if the controls belong to same namescope. If they don't, you should add a bool property to your view model and return the value of this one from the CanExecute method of the command, and also bind the IsEnabled property of the TextBox to it.


text:
Q: Horizontal navigation menu - how to increase size of
* on hover I'm working on a navigation menu. I'm trying to achieve something like that the one on this website: www.fizjoterapia-domkrakow.pl/
I've been searching a lot and I couldn't find a way to increase the size of the
* when hovering over it. I'm using jquery(mouseover) to add new class to
* that would have a greater size.
Also, there is a ribbon shadow effect on the hovered element that I have no idea how to implement it.
The other problem I have is the opacity of the elements inside the header. I keep the logo inside one div and menu inside the other one. Both of them are in the  that has a background set to opacity:0.9. Unfortunately my logo and menu are also set to such value. Any ideas how to get rid of it?
Here is the code sample.

@Html.ActionLink("Home", "Home", "Home")

@Html.ActionLink("About", "About", "About")

@Html.ActionLink("PriceList", "PriceList", "Home")

@Html.ActionLink("Reviews", "Reviews", "Home")

CSS:
header {
    height: 200px;
    opacity: 0.9;
    background: #527F9D;
    box-shadow: 1px 1px 2px black;
  }

#logo
{
    padding: 30px 0 20px 70px;
    float: left;
}

#main
{
    margin:20px 210px 20px 210px;
    background-color: #ffffff;
    border-radius: 4px;
}

.liOnHover
{
    background-Color:#0099FF;
    color: white;
    min-height: 100px;
    -webkit-box-shadow: 0px 6px 6px 0px rgba(34, 50, 60, 0.89);
    -moz-box-shadow:    0px 6px 6px 0px rgba(34, 50, 60, 0.89);
    box-shadow:         0px 6px 6px 0px rgba(34, 50, 60, 0.89);
    text-align: center;
    display:inline-block
}

#menuItems {
    width: 900px;
    height: 36px;
    position: absolute;
    bottom:18px;
    right:20px;
    top:150px;
    left:350px;
    font-size: 23px;
    font-family: Enriqueta-Bold;
    font-weight: bold;
    text-align: center;
    background-color: #86ADED;
    -webkit-box-shadow: 0px 6px 6px 0px rgba(34, 50, 60, 0.89);
    -moz-box-shadow:    0px 6px 6px 0px rgba(34, 50, 60, 0.89);
    box-shadow:         0px 6px 6px 0px rgba(34, 50, 60, 0.89);
}

#menuItems ul {
    padding: 2px 0;
    margin: 0;
}

#menuItems li {
display: inline;
padding: 4px;
}

A: Instead of using Javascript to achieve this you could simply use the :hover attribute in CSS
#menuItems li {
   display: inline;
   padding: 4px;
}

#menuItems li:hover {
   background-Color:#0099FF;
   color: white;
   min-height: 100px;
   -webkit-box-shadow: 0px 6px 6px 0px rgba(34, 50, 60, 0.89);
   -moz-box-shadow:    0px 6px 6px 0px rgba(34, 50, 60, 0.89);
   box-shadow:         0px 6px 6px 0px rgba(34, 50, 60, 0.89);
   text-align: center;
   display:inline-block
}

regarding your second issue, opacity is always influencing the children of the element, if you just want to use a transparent background you could set the color using background-color: rgba(82,127,157,.9)

A: You need to use the selector #menuItems li.liOnHover or #menuItems li:hover for the hover changes to work.
Additionally, you should set the display of #menuItems li to inline-block.
Hope this helps.


text:
Q: Where to use Property or function in Knockout JS I don't know where to use property or functions. Can you please explain me in detail about the hasCellphone is a function or property here. And when it can be property or function. What should we use ?
enable: hasCellphone or
enable: hasCellphone()
 and why so.
<input type='checkbox' data-bind="checked: hasCellphone" />
I have a cellphone

Your cellphone number:
<input type='text' data-bind="value: cellphoneNumber, enable: hasCellphone" />

<script type="text/javascript">
var viewModel = {
    hasCellphone : ko.observable(false),
    cellphoneNumber: ""
};
</script>

A: As you have set yourself, hasCellphone as observable, it is an observable. And as the official document:

Observables are functions. The actual value and subscribers to the observable are cached internally by the function. You set an observable's value by passing the new value as the only argument to the function and you read the value by passing no arguments.

And about using observables without or with () :

However, in a binding if you use an observable in an expression, then you need to reference it as a function. Likewise, in code you typically need to reference your observables as functions, unless you actually want to pass the observable itself (not the value).

You can take a look at the following article:
10 Things to Know About KnockoutJS on Day One


text:
Q: Integration of a Bessel function times a sine function times a polynomial I have recently faced the following expression (while trying to compute the Fourier transform of a RKKY-like potential):
\begin{align}
\int_0^{\infty} \text{d} r\;  J_0 (k r) \frac{\sin \left(\alpha \sqrt{1+r^2} \right) }{(1+r^2)^2} \; r = -\frac{1}{\alpha} \int_0^{\infty} \text{d} r\;  J_0 (k r) \frac{1}{(1+r^2)^{3/2}} \frac{\text{d}}{\text d r} \left[\cos \left( \alpha\sqrt{1+r^2} \right) \right]
\end{align}
Although I can solve it numerically, I would like to find a closed-form expression, if there is one.
I found some related questions here, such as,
\begin{align}
\int_0^{\infty} \text{d}r\; J_0 \left( \alpha\sqrt{x^2 +z^2} \right) \, \cos \left(\beta x \right)  = \frac{\cos \left(z\sqrt{\alpha^2 -\beta^2} \right)}{\sqrt{\alpha^2 -\beta^2}}
\end{align}
but did not really helped me.

A: According to this reference, Table 8.2 , entry (7):
$$\int_0^\infty \dfrac{1}{\left(1+r^2\right)^\frac{3}{2}}J_0(kr)r \; dr = e^{-k}$$
and according to Table 8.2, entry (41):
$$\int_0^\infty \dfrac{\sin\left[\alpha\left(1+r^2\right)^\frac{1}{2}\right]}{\left(1+r^2\right)^\frac{1}{2}}J_0(kr)r \; dr = \dfrac{\cos\left[\left(\alpha^2-k^2\right)^\frac{1}{2}\right]}{\left(\alpha^2-k^2\right)^\frac{1}{2}}\Pi\left(\dfrac{k}{\alpha}-\dfrac{1}{2}\right)$$
where
$$\Pi(t) = \begin{cases} 1 & -\frac{1}{2} < t< \frac{1}{2}\\ 0 & \mathrm{otherwise} \end{cases}$$
Using the convolution property of the Hankel Transform, if the convolution exists
$$\begin{align*} \int_0^\infty \dfrac{1}{\left(1+r^2\right)^\frac{3}{2}}\dfrac{\sin\left[\alpha\left(1+r^2\right)^\frac{1}{2}\right]}{\left(1+r^2\right)^\frac{1}{2}}J_0(kr)r \; dr &= \dfrac{1}{2\pi}e^{-k}**\dfrac{\cos\left[\left(\alpha^2-k^2\right)^\frac{1}{2}\right]}{\left(\alpha^2-k^2\right)^\frac{1}{2}}\Pi\left(\dfrac{k}{\alpha}-\dfrac{1}{2}\right)\\
\\
&= \dfrac{1}{2\pi}\int_0^{2\pi}\int_0^{k\cos\theta+\sqrt{k^2\cos^2\theta-(k^2-\alpha^2)}} e^{-k'}\dfrac{\cos\left[\left(\alpha^2-\left[k^2+k'^2-2kk'\cos\theta\right]\right)^\frac{1}{2}\right]}{\left(\alpha^2-\left[k^2+k'^2-2kk'\cos\theta\right]\right)^\frac{1}{2}}k' \; dk' \; d\theta\\
\\
&\mathrm{or}\\
\\
&= \dfrac{1}{2\pi}\int_0^{2\pi}\int_0^{\alpha^-} e^{-\sqrt{k^2+k'^2-2kk'\cos\theta}}\dfrac{\cos\left[\left(\alpha^2-k'^2\right)^\frac{1}{2}\right]}{\left(\alpha^2-k'^2\right)^\frac{1}{2}}k' \; dk' \; d\theta\\
\end{align*}$$
Neither of which look possible to easily evaluate symbolically.  Although maybe one of them takes less effort to evaluate numerically than your original integral.


text:
Q: Jquery Clone a selector and modify option id <select id="one">
    <option id="one_val_a" value="one">one</option>
    <option id="two_val_a" value="two">two</option>
    <option id="three_val_a" value="three">three</option>
</select>

How could I clone #one, make its id #two, and have its options ids as #one_val_b, #two_val_b, etc.
$('#one').clone(true, true).attr('id', 'two').appendTo('#pin');

That will atleast change the ID of the clone, but now how do change its options ids?
Jsfiddle: http://jsfiddle.net/C2zCZ/2/

A: Here's another way, using a regex to replace the option id attributes, so it doesn't matter how many options the original select had:
$('#one').clone(true, true)
    .attr('id', 'two').appendTo('#pin')
    .find("option").each(function() {
        $(this).attr("id", $(this).attr("id").replace(/\_a$/, "_b"));
    });

Example fiddle

A: $('#one')
    .clone(true, true)   // perform the clone
    .attr('id', 'two')  // change the id
    .appendTo('#pin')    // append to #pin
    .children()          // get all options
    .attr("id", function(i, value) {  // processing on ids
        // replacing last charecter with its next charecter
        return value.replace(/[a-z]$/, function(char, index) {
            return String.fromCharCode(char.charCodeAt(0) + 1);
        });
    });

Working Sample

A: counter = 1;
$('#one').clone(true, true).attr('id', 'two').appendTo('#pin').find('option').each(function(){
    $(this).attr('id', 'option_id_' + counter++);
});

Here is your jsFiddle updated and working: http://jsfiddle.net/C2zCZ/4/

A: Another one-liner:
$('#one').clone(true, true).attr('id', 'two').each(function() {
    $(this).children().attr("id", function(i, value) {
        switch (i) {
            case 0: return "one_val_b";
            case 1: return "two_val_b";
            case 2: return "three_val_b";
        }
    });
}).appendTo('#pin');

DEMO: http://jsfiddle.net/C2zCZ/5/

Another, more flexible one-liner:
$('#one').clone(true, true).attr('id', 'two').appendTo('#pin')
    .children().attr("id", function(i, value) {

    var last = value.lastIndexOf("_") + 1;
    var char = value.substring(last).charCodeAt(0);
    return value.substring(0, last) + String.fromCharCode(char + 1);
});

DEMO: http://jsfiddle.net/C2zCZ/10/

A: Here's the one liner,
$('#one').clone(true).attr('id', 'two').children('option').attr('id',function(){
    return this.id.replace(/\a$/, 'b');
}).end().appendTo('#pin');

Fiddle
P.S.

*

*The second argument in clone() is copies the value in first argument (by default), so no need to pass second argument.

*I've used the end() because I think we should not access the after inserting into dom. (My approach should be faster but I haven't done a test)


text:
Q: PHP rowcount not returning correct result I am trying to get the row count which should equal 2 but it returns 0 everytime.
$username = "matthew";
$query_url = array(':user' => $username);
$chek_url = $db->prepare("SELECT Id FROM Customer WHERE Referral = :user");
$chek_url->execute($query_url);
$signups = $chek_url->rowCount();

This definitely should return 2. Am I doing something wrong?


text:
Q: Output showing null values. how to resolve  i have three classes :
CustomerData.java
import java.util.Date;
public class CustomerData
{
   private String FirstName;
   private String LastName;
   private int TaxId;
   private String HomePhone;
   private String WorkPhone;
   private String HomeAddress;
private Date Dob;
private String EmployerName;
private boolean isEmployed;
private String ProDescription;
private String IsSameAsPrevious;

public String getFirstName() {
    return FirstName;
}
public void setFirstName(String firstName) {
    FirstName = firstName;
}
public String getLastName() {
    return LastName;
}
public void setLastName(String lastName) {
    LastName = lastName;
}
public int getTaxId() {
    return TaxId;
}
public void setTaxId(int taxId) {
    TaxId = taxId;
}
public String getHomePhone() {
    return HomePhone;
}
public void setHomePhone(String homePhone) {
    HomePhone = homePhone;
}
public String getWorkPhone() {
    return WorkPhone;
}
public void setWorkPhone(String workPhone) {
    WorkPhone = workPhone;
}
public String getHomeAddress() {
    return HomeAddress;
}
public void setHomeAddress(String homeAddress) {
    HomeAddress = homeAddress;
}
public Date getDob() {
    return Dob;
}
public void setDob(Date dob) {
    Dob = dob;
}
public String getEmployerName() {
    return EmployerName;
}
public void setEmployerName(String employerName) {
    EmployerName = employerName;
}
public boolean isEmployed() {
    return isEmployed;
}
public void setEmployed(boolean isEmployed) {
    this.isEmployed = isEmployed;
}
public String getProDescription() {
    return ProDescription;
}
public void setProDescription(String proDescription) {
    ProDescription = proDescription;
}
public String getIsSameAsPrevious() {
    return IsSameAsPrevious;
}
public void setIsSameAsPrevious(String isSameAsPrevious) {
    IsSameAsPrevious = isSameAsPrevious;
}

}
MainCntrlr.java
public class MainCntrlr {
             public static void main(String[] args)
 {
    CustomerData customerData=new CustomerData();
    customerData.setFirstName("RAVI");
    customerData.setLastName("Shekhar");
    customerData.setHomePhone("123456789");
    customerData.setWorkPhone("1256554634");
    customerData.setHomeAddress("Banagalore");
    customerData.setEmployerName("ABc");
    customerData.setProDescription("New Produtc");
    customerData.setTaxId(1233434343);

    ContrOne ctr=new ContrOne();
    ctr.displayInformation();
        }
}

ContrOne.java
import com.blr.CustomerData;
public class ContrOne
{
  public void displayInformation()
  {
CustomerData cd=new CustomerData();
System.out.println("displaying customer Info");

System.out.println(cd.getFirstName());
System.out.println(cd.getLastName());
System.out.println(cd.getHomePhone());
System.out.println(cd.getWorkPhone());
System.out.println(cd.getEmployerName());
System.out.println(cd.getProDescription());
System.out.println(cd.getDob());
System.out.println(cd.getTaxId());

  }
}

Output is :
displaying customer Info
null
null
null
null
null
null
null
0

A: In your method ContrOne.displayInformation() you create a new new CustomerData() object. Thus it is not properly initialized. Maybe you want to pass customerData from your main method to displayInformation?

A: You are creating a CustomerData object  in MainCntrlr class but not passing it to the ContrOne class. ContrOne is creating it's own CustomerData object and printing it's values which are null.
A possible solution could be to change the signature of displayInfo and pass the CustomerData object to this method from MainCntrlr class.
A few other points to note

*

*The class names are confusing. It is not clear why you have created MainCntrlr and ContrOne classes separately.

*If all you want is to display Customer information, you may want to override the toString() method in CustomerData class instead.

A: Your ContrOne.displayInformation() instantiates a new CustomerData() object to cd but never populates fields in it.
If you want your ContrOne to display information, rather do this:
public class ContrOne {

    public void displayInformation(CustomerData cd)  {
        System.out.println("displaying customer Info");

        System.out.println(cd.getFirstName());
        System.out.println(cd.getLastName());
        System.out.println(cd.getHomePhone());
        System.out.println(cd.getWorkPhone());
        System.out.println(cd.getEmployerName());
        System.out.println(cd.getProDescription());
        System.out.println(cd.getDob());
        System.out.println(cd.getTaxId());
    }
}

and in MainCntrlr
public static void main(String[] args) {
    CustomerData customerData=new CustomerData();
    customerData.setFirstName("RAVI");
    customerData.setLastName("Shekhar");
    customerData.setHomePhone("123456789");
    customerData.setWorkPhone("1256554634");
    customerData.setHomeAddress("Banagalore");
    customerData.setEmployerName("ABc");
    customerData.setProDescription("New Produtc");
    customerData.setTaxId(1233434343);

    ContrOne ctr=new ContrOne();
    ctr.displayInformation(customerData);
}


text:
Q: Get text on same line HTML/CSS How do I put the address on the same line as "contact me on:" ? I also want one space between them. I was thinking of using float, nut isn't that overkill?

Contact me on:
<address>

me@gmail.com
</address>

http://jsfiddle.net/tY9nS/
Thanks in advance

A: Change your html as like this '
<address>

Contact me on:
me@gmail.com

   </address>

Don't** put the address tag in p tag put the p tag into address tag
demo

A: I'm not 100% sure why this is, but browsers don't allow an address tag in a p tag.
You can make this work, but you'll need to remove the p { width:100%}.
The since browsers are setting the address and p tag one after the other, your p tag will consume 100% of the width, thus no more room for the address.
Change the styles to : p,address{ display:inline-block;} and it will work just fine

A: Another simple way would be to format it in a table like this:

Contact me on:
me@gmail.com

Otherwise there's the more complicated options where you go into layout using div elements that you can find here: http://www.w3schools.com/html/html_layout.asp


text:
Q: Import errors after plugin updates for Python(x,y) I am using Python(x,y) (version 2.7.3.1) with the Spyder ide. Everything was working perfectly until I updated the plugins. I updated Pandas to version 0.12.0-7, matplotlib to version 1.3.1-4, and numpy to version 1.6.2. I did this by downloading the plugins on the Python(x,y) page and double clicking on the executable file.
Now I get errors when I try to import Matplotlib and pandas.
When I try to import matplotlib, the error is:
ImportError: matplotlib requires dateutil

When I try to import Pandas, the error I get is:
numpy.dtype has the wrong size, try recompiling.

Other stackflow questions ask how matplotlib and pandas were installed, but I'm not sure how to answer that question given that I used plugins.
ps: I'm running Windows Vista Home Premium

A: I've solved part of this problem. It turns out that I hadn't actually installed the latest plugin for numpy. Once I did that, I got a new error about datautil. I installed that using this blog post: http://blog.gmane.org/gmane.comp.python.xy.devel/month=20130601.
Now I can import pandas. Still working on Matplotlib.


text:
Q: How can you edit the objectID of a row in an ArcGIS geodatabase? I am trying to add a row to an ArcGIS geodatabase but I don't want an automatic objectid to be generated for this row. I want to insert a specific objectid. I get the error: field is not editable.
My code is as follows:
feature = fclass.CreateFeature();
feature.setValue((int)_fields[i].targetIndex, tripValue);

Now, in the first iteration, _fields[i].targetIndex=0 because I want to insert the specific objectid.
But the first iteration gives me an error, while the rest are fine.
Any idea on how to somehow get around the automatic objectid ?

A: Short answer:
You don't.
Long answer:
Using the ObjectID field as a unique key (which I assume is what you're doing here) is generally considered a Very Bad Idea, as that field is not as static as you might think - various operations on the dataset will re-assign them.
One of the answers to this question suggests that copy/pasting data might transfer the objectids intact, if you're copying data from somewhere else, but otherwise you should create another field to use as the unique key and leave the objectid alone.
(incidentally, this kind of geodatabase question will get much more intelligent answers over at GIS.SE.

A: The ObjectID is an internal system field for ArcGIS, and I such must not be tempered with.  As stated in the help documentation,

The ObjectID is used by ArcGIS to do such things as scroll, display
  selection sets, and perform identify operations on features.

Instead, I would recommend creating a GlobalID, which is also system generated by ArcGIS but ensure that each identifier is unique (see ArcGIS field data type for details).  The GlobalID also support geodatabase replication.  To create a GlobalID, simply right-click on your feature classes, in ArcCatalog, and select Manage > Add Global IDs...
I also second Juffy that this question would be better served over at GIS.SE.


text:
Q: Inner Function Identification I have having an issue identifying the inner function of this function:

$$f(g(x))=\frac{1}{\sqrt{x+1}}$$

I "need" to take the derivative of it; hence I have to identify the inner function.  My current thinking is that the inner function is $\sqrt{x+1}$, and outer would be $\frac{1}{x}$.
Outer

$$\frac{1}{x}$$

Inner

$$\sqrt{x+1}$$

Is my answer to the identification of the outside and inner functions correct?

A: Those are two possible solutions for the inner and outer functions, however, if you are to apply the chain rule, I would suggest just using $(x+1)^\frac{-1}{2}$ for your chain rule


text:
Q: Kivy screen manager only accepts screen widget This is my main code:
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window
Window.size = (350,580)

class LoginPage(MDApp):

    def build(self):
        global screen_manager
        screen_manager = ScreenManager()
        screen_manager.add_widget(Builder.load_file("pre-splash.kv"))
        screen_manager.add_widget(Builder.load_file("login.kv"))
        return screen_manager

if __name__ == "__main__":
    LoginPage().run()

This is my .kv file:
Screen:

    name: "pre-splash"
    MDFloatLayout:
        md_bg_color : 226/255, 0 , 48/255, 1
        Image:
            source:"AppData/Local/Temp/logo-no-background.png"
            size_hint: .26, .26
            canvas.before:
                Color:
                    rgb: 1, 1, 1, 1
                Ellipse:
                    size: 130, 130
                    pos: 110,250

Okay, so I am pretty new with Kivy so I do not understand some of the main concepts but this is my .kv code and its giving an error here saying that the screen manager only accepts Screen widget. I have included the main source and the .kv source. I cant seem to find anything out of place in this. I am running kivy 1.1.1 . I am trying to add a splash to my app in this but its giving me this error.

A: Yeah. ScreenManager only manages screen widgets. ScreenManager will not manage anything other than Screen widget and custom widgets made by Screen.
And there is no point in adding splash screen to your kivy app. Because you have the flexibility to add the splash screen and all that stuff in buildozer.spec file .