text:
Q: Access to view elements in fragments I have an activity which receive data from other activity. This data has to be showed in a TextView in a fragment inflated in the activity. So, the code is:
public class DetailActivity extends Activity {

private int idEstablecimiento;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit(); //Here the fragment is added to the activity
    }

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        idEstablecimiento = extras.getInt("idEstablecimiento");
    }

    TextView textView = (TextView) this.findViewById(R.id.nombreView); //Declared in fragmentDetail, which has been already inflated at this point, but still null
    textView.setText(this.idEstablecimiento);
}

//...
//Non related stuff...
//...

    public static class PlaceholderFragment extends Fragment {
    private int idEstablecimiento;
    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_detail,
                container, false);
        return rootView;
    }
}

The problem is that the textView in the onCreate() method is null, why is this happening if the fragment has been already inflated? Shouldn't I be able to access to the IU elements once the fragment has been inflated in the onCreate() method? Or if not, what is the rigth way to do access to it?

A: If you want to get the View from a fragment layout you should use the view inside the oncreateView of the fragment and then get the textView inside the oncreate view..
example:
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_detail,
            container, false);
    TextView textView = (TextView) rootView.this.findViewById(R.id.nombreView); //Declared in fragmentDetail, which has been already inflated at this point, but still null
textView.setText("I am here");
    return rootView;
}

A: You have to find the TextView in the Fragment.
public static class PlaceholderFragment extends Fragment {
private int idEstablecimiento;
public PlaceholderFragment() {
}
public PlaceholderFragment(int idEstablecimiento) {
this.idEstablecimiento = idEstablecimiento;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_detail,
            container, false);
    TextView text = rootView.findViewById(R.id.nombreView);
    text.setText(idEstablecimiento);
    return rootView;
}

And then you can get the text and commit it.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);

Bundle extras = getIntent().getExtras();
if (extras != null) {
    idEstablecimiento = extras.getInt("idEstablecimiento");
}

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment(idEstablecimiento)).commit();
}
}

Regards
Nils


text:
Q: Can php have a mixed type hinting? Say my function want to accept both string and integer. And if it is string, I convert it to int afterwards.
Like
function func(int|string $a) {
    echo is_string($a)?intval($a)+1:$a+1;
}

func(1344);
func('1344');

A: Mixed was accepted for PHP 8.0: https://wiki.php.net/rfc/mixed_type_v2
class B
{
    public function foo(mixed $value) {}
}

A: The feature you asked for is in the proposal phase. See PHP RFC: Union Types.
Update
Mixed type has been ultimately accepted and introduced in PHP 8 released in November 2020.

A: Union types RFC has been accepted and implemented for PHP 8.
Mixed type RFC is being voted on, but likely to pass at time of writing this answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Slick Slider Width issue with WP 5.6 editor & ACF Pro This is a bit of a specific issue, but I'm hoping I'm not alone with it!
After updating to WP 5.6, all of my websites are having issues rendering a Slick Slider in the Block Editor. On the front-end, the sliders are fine.
I believe the issue is that if I have a block with Slick Slider inside it, and that block is set to 'full width' in the WP editor, Slick Slider is unable to find the correct size of the window within the block editor. The sliders then expand beyond the viewport, pushing the block editor settings box off-screen and making the editor pretty unusable.
As the title suggests, I'm using the latest version of slick slider, and I'm rendering this through a custom ACF Block within WP 5.6.
Prior to 5.6 everything rendered just fine. I'm hoping the solution is a simple CSS change, but I can't for the life of my find something that works.
Here is my code:
ACF block
acf_register_block_type(array(
        'name'              => 'image-slider',
        'title'             => __('Image Slider'),
        'description'       => __('A slider of images.'),
        'render_template'   => get_template_directory().'/inc/blocks/core/image-slider.php',
        'render_callback'   => 'render_block__image_slider',
        'category'          => 's2f-blocks',
        'icon'              => 'images-alt2',
        'keywords'          => array( 'slider', 'images', 's2f' ),
        //'mode'                => false
    ));
    if( !function_exists('render_block__image_slider') ) {
        function render_block__image_slider( $block, $content = '', $is_preview = false, $post_id = 0 ) {
            include(get_template_directory().'/inc/blocks/core/image-slider.php');
        }
    }

ACF block render template
/**
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during AJAX preview.
 * @param   (int|string) $post_id The post ID this block is saved to.
 */

$block_name = 'image-slider-block';

// Create id attribute allowing for custom "anchor" value.
$id = 'slider-' . $block['id'];
if( !empty($block['anchor']) ) {
    $id = $block['anchor'];
}

// Create class attribute allowing for custom "className" and "align" values.
$className = $block_name;
if( !empty($block['className']) ) {
    $className .= ' ' . $block['className'];
}
if( !empty($block['align']) ) {
    $className .= ' align' . $block['align'];
}
if( $is_preview ) {
    $className .= ' is-admin';
}

$slidesToShow = get_field('slides_to_show') ?: '3';

$lightbox = get_field('lightbox_images') ?: false;
if( $lightbox ) {
    $className .= ' is-lightbox';
}

$crop = get_field('crop_images') ?: false;
if( $crop ) {
    $className .= ' is-cropped';
}

$arrows = get_field('show_arrows') ?: false;
if( $arrows ) {
    $className .= ' has-arrows';
}

$slides = get_field('slides');

?>
<div id="<?php echo esc_attr($id); ?>" class="slider <?php echo esc_attr($className); ?> wp-block">
    <?php if( $slides ): ?>
        <div class="slides" data-slides="<?php echo $slidesToShow; ?>">
            <?php foreach($slides as $slide) : ?>

                    <?php if( $lightbox ) : ?>
                        <a href="<?php echo wp_get_attachment_image_url($slide['image']['id'], 'large', false); ?>" data-fancybox="<?php echo esc_attr($id); ?>">
                    <?php endif; ?>

                        <?php echo wp_get_attachment_image( $slide['image']['id'], 'large' ); ?>

                    <?php if( $lightbox ) : ?>

                    <?php endif; ?>

            <?php endforeach; ?>

    <?php else: ?>

Please add some slides.

    <?php endif; ?>

Slick Slider JS
/**
         * initializeBlock
         *
         * Adds custom JavaScript to the block HTML.
         *
         * @date    15/4/19
         * @since   1.0.0
         *
         * @param   object $block The block jQuery element.
         * @param   object attributes The block attributes (only available when editing).
         * @return  void
         */
        var initialiseSliderImageBlock = function( $block ) {

            var slider = $block.find('.slides');
            var slidesToShow = slider.data('slides');
            var arrows = false;

            if( !slidesToShow ) {
                slidesToShow = 3;
            }

            if( isAdmin() ) {
                var container = $block.find('.image-slider-block');
                if( container.hasClass('has-arrows') ) {
                    arrows = true;
                }
            } else {
                if( $block.hasClass('has-arrows')) {
                    arrows = true;
                }
            }

            // init slider
            slider.find('.slide').each(function() {
                $(this).addClass('show-slide');
            });

            if( !slider.hasClass('slick-slider') ) {
                slider.slick({
                    dots: true,
                    arrows: arrows,
                    infinite: false,
                    speed: 300,
                    slidesToShow: slidesToShow,
                    autoplay: false,
                    responsive: [
                        {
                            breakpoint: 1300,
                            settings: {
                                dots: true,
                                arrows: false
                            }
                        },
                        {
                            breakpoint: 1100,
                            settings: {
                                slidesToShow: Math.ceil(slidesToShow/2),
                                dots: true,
                                arrows: false
                            }
                        },
                        {
                            breakpoint: 700,
                            settings: {
                                slidesToShow: 2,
                                dots: true,
                                arrows: false
                            }
                        },
                        {
                            breakpoint: 450,
                            settings: {
                                slidesToShow: 1,
                                dots: true,
                                arrows: false
                            }
                        },
                    ]
                });

                slider.on('init beforeChange', function(){
                    $.fn.matchHeight._update();
                });

            }

            if( !isAdmin() ) {
                initialiseHeightMatch($block);
            }
        }

        // Initialize each block on page load (front end).
        $(document).ready(function(){
            $('.slider').each(function(){
                initialiseSliderImageBlock( $(this) );
            });
        });

        // Initialize dynamic block preview (editor).
        if( window.acf ) {
            window.acf.addAction( 'render_block_preview/type=image-slider', initialiseSliderImageBlock );
        }

slider css
.slider {
    position: relative;
    z-index:1;
    outline: none;
    overflow: hidden;
    .slide  {
        height: 100%;
        float: left !important;
    }
}

.slider .slide:nth-child(n+2)   { display: none; }
.slider .slide.show-slide       { display: block; }

.slick-list,
.slick-track                    { height: 100%; }

.slick-slider .slick-slide      { float: left; position: relative; width: 100%; outline: none; }

.slick-list                     { overflow: hidden; outline: none !important; position: relative; }
.slick-track                    { margin: 0 auto; outline: none; }

.slick-next,
.slick-prev {
    -webkit-appearance: none;
    outline: none;
    border: none;
    position: absolute;
    top: 0;
    bottom: 0;
    cursor: pointer;
    font-size: 1px;
    color: rgba(0,0,0,0);
    width: 84px;
    transition: 0.3s all ease;
    z-index: 10;

    background-color: rgba(0,0,0,0.1);
    //background-image: url(../images-dist/icon-white-arrow-left.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
}

.slick-next:hover,
.slick-prev:hover                       { width: 95px; }

.slick-next {
    right: 0;
    -moz-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    transform: scaleX(-1);
    filter: FlipH;
    -ms-filter: "FlipH";
}
.slick-prev                             { left: 0; }

ul.slick-dots {
    padding: 0;
    text-align: center;
    list-style: none;
    li {
        display: inline-block;
        list-style: none;

        button {
            border: none;
            background-color: grey;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin: 0 5px;
            font-size: 0;
            outline: none;
            cursor: pointer;
        }
        &.slick-active button {
            background-color: yellow;
        }
    }
}
.image-slider-block {
&.is-cropped {
    .slick-track {
        display: flex;
        justify-content: stretch;
        .slick-slide > div {
            height: 100%;
        }
    }
    img {
        height: 100%;
        flex: 1;
        -o-object-fit: cover;
        object-fit: cover;
        width: 100%;
    }
}
&.is-lightbox {
    a {
        display: block;
        height: 100%;
    }
}
}

A: I had the same issue
Add this line to gutenberg editor css
.interface-interface-skeleton__editor {
  overflow: auto;
}


text:
Q: Select2 set dynamic value from array I try use this JS Plugin: https://select2.github.io/examples.html#programmatic
I have variable in array.
//title: Cat, Ass, Bebe
var array = title.split(',');

And try set value in SELECT.
var $exampleMulti = $("#tags").select2();
$exampleMulti.val([t1, t2, t3]).trigger("change");

It does not work??
Maybe somthing wrong with my array??
When I add static variable, it's work.
var $exampleMulti = $("#tags").select2();
$exampleMulti.val(["Cat", "Ass", "Bebe"]).trigger("change");


text:
Q: ADB.exe is obsolete and has serious performance problems ( New ) Im trying to run my application in an emulator but im getting this error; The ADB binary at C:\Users\siviw\AppData\Local\Android\Sdk\platform-tools\adb.exe is obsolete and has serious performance problems with the Android Emulator. Please update to a newer version to get significantly faster app / file transfer
Ive tried to update SDK Build-Tools as this post shows; ADB.exe is obsolete and has serious performance problems but i just keep getting the same result.
How would i go about fixing this error?

A: In my case I've followed all the instructions I've found on Internet without any luck. Finally I've decided to remove and install again the "SDK Build-Tools" (additional steps 5,6,7,8) and the problem was solved.

*

*Menu Tools | SDK Manager

*Click the second tab "SDK Tools".

*Check "[x] Show Package Details" in the lower right corner

*Scroll to the last item under "SDK Build-Tools"(Mine was [x] 28.0.3)

*Uncheck [ ] 28.0.3

*Click "Apply"

*Check [x] 28.0.3

*Click "Apply"

*In the dialogue box that pops up, click "OK"

*When the installer finishes, click "Finish"

A: Download ADB.exe (you can google it) and paste into this folder.
C:\Users\siviw\AppData\Local\Android\Sdk\platform-tools\

I have faced the same problem. After doing this, my problem has been solved.


text:
Q: C#.NET foreach skips first row of DataGridView when changing Row HeaderCell value I'm trying to show the row number on DataGridView RowHeader, but when I do the following block of code it doesn't change the first row row.HeaderCell.Value, but it will change all the next.
When I watch the row variable and the gridView.Rows[0], the gridView.Rows[0] doesn't change at all and the row gets clear like it's a new row.
foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}

Weirdly, if I change the gridView.Rows[0].HeaderCell.Value before entering the loop, this line will be "ignored", but the loop will work just fine and change the HeaderCells of all rows.
gridView.Rows[0].HeaderCell.Value = "";
foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}

It looks like you need to change the first row once to "unlock" the subsequent changes.
What could be going on to this issue?
Thank you all
EDIT:
This is a Windows Application on .NET Framework 4.8
And I forgot to show the steps before the problem.
bs = new BindingSource();
bs.DataSource = table;
IBindingListView bindingList = bs;
gridView.DataSource = bindingList;
gridView.Visible = true;

foreach (DataGridViewRow row in gridView.Rows)
{
    row.HeaderCell.Value = (row.Index + 1).ToString();
}

A: If you don't have a lot of records try the following. I'd call this clunky but it may suit you?
In form shown or load event
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader;
dataGridView1.CellFormatting += DataGridView1OnCellFormatting;

Then add this code to the form
private void DataGridView1OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var grid = sender as DataGridView;
    if (!(grid.Rows[e.RowIndex].IsNewRow))
    {
        grid.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);
    }
}


text:
Q: System.Net issues When I use code like this:
System.Net.WebClient objClient = new WebClient();
string url = "http://google.com";
objClient.DownloadString(url);

It takes a couple of seconds for the connection to get established and then the downloading starts.  I reinstalled Windows yesterday and this problem started. This problem seems to happen when I reinstall Windows.
Does anybody know why this problem occurs? Thanks all.

A: See if you have a proxy configured in your Internet Explorer settings (Tools - Internet Options - Connections - LAN Settings). Make sure you got Automatically detect settings checked.

A: Maybe you have automatic configuration of proxy enabled in your Internet Explorer? Since you don't specificially set the proxy settings of your WebClient object, it looks at Internet explorer settings.


text:
Q: Removing drive from LVM that has the /boot partition I have two drives /dev/sda and /dev/sdb that are in a Volume Group with three volumes: /boot, /root, and /home, mounted respectfully.
If I remove /dev/sda after doing
# pvmove /dev/sda
# vgreduce $myVolGroup /dev/sda

Will that affect my boot-loader assuming all of the /boot volume was on /dev/sda and it was the initial install disk?
I would really like to avoid surprises.

A: There are two components to the boot loader: the first stage, which is written directly to the MBR-and-later-blocks and isn't on a filesystem anywhere, and the second stage/config files/kernel image/initrd, which is in /boot. grub at least (I'm assuming that's your bootloader, if not this may not apply) knows about lvm in its own right, and so can find a /boot which uses it and load configuration from there. Thus, on that level it shouldn't make a difference. However, if you plan to remove /dev/sda from the system, you need to ensure that the first stage is in at least one of the remaining block devices; you would probably use some invocation of grub-install for this.


text:
Q: Replacing  with a New Line (\n) in JSOUP I'd like to replace all instances of
 with a new line (\n most likely) using Jsoup, but I cannot devise a clean and efficient way of doing so. The resulting Element#text() should output no HTML and contain \n in place of where
 was found in the HTML code of the original Element.

A: JSoup is Java library, so I assume you're using Java (your question should be then tagged). I've seen a comparison (I didn't wrote the link) where text replacement methods were compared, and StringUtils replace methods from apache-commons library seemed to be very effective compared to JRE methods, so you should try it.


text:
Q: C# - Linq MultiThreading with varying Max/Min Threads? ThreadPool.SetMinThreads(50, 50);
ServicePointManager.MaxServicePointIdleTime = 8000;
ServicePointManager.DefaultConnectionLimit = 50;

List<Match> Combos = new Regex("^(.{5,}):(.{6,})$", RegexOptions.Multiline).Matches(File.ReadAllText(ofd.FileNames[0])).OfType<Match>().ToList();
var query = Combos.ToObservable().SelectMany(s => Observable.Start(() => new
{
    grab = checkall(s.Groups[1].Value.Replace("\n", "").Replace("\r", ""), s.Groups[2].Value.Replace("\n", "").Replace("\r", ""))
})).ObserveOn(this).Do(x =>
{
    try
    {
        TotalChecked.Text = "Tested: " + (int.Parse(TotalChecked.Text.Substring(7)) + 1).ToString();
        progressBar2.Value = (int)Math.Round((double)(100 * int.Parse(TotalChecked.Text.Substring(7))) / Combos.Count);
    }
    catch (Exception)
    {
        TotalChecked.Text = "Tested: " + (int.Parse(TotalChecked.Text.Substring(7)) + 1).ToString();
        progressBar2.Value = (int)Math.Round((double)(100 * int.Parse(TotalChecked.Text.Substring(7))) / Combos.Count);
    }
});
query.ToArray().ObserveOn(this).Subscribe(x =>
{
    CheckButton.Location = new Point(CheckButton.Location.X + 31, 9);
    CheckButton.Width -= 31;
});

The code above uses regex on a text file and then executes a function.
It works just fine, but now I want it to execute multiple DIFFERENT functions and only allow a set amount of threads on some of them.
For example:
var query = Combos.ToObservable().SelectMany(s => Observable.Start(() => new
{
    grab = checkall(s.Groups[1].Value.Replace("\n", "").Replace("\r", ""), s.Groups[2].Value.Replace("\n", "").Replace("\r", "")),
    //This one should be LIMITED to only 5 threads MAX!
    grab2 = checktwo(Hi, Hello)
}))

In the code above I added grab2 which should have a maximum of 5 threads allocate to it.
To be honest I have no idea how I could execute a method like this.
Any help would be appreciated.

A: If you need to some code gets executed only by n threads, you need a semaphore, in this case SemaphoreSlim is enough
// 5 threads to run in parallel, all 5 can start immidiately
var semaphore = new SemaphoreSlim(5, 5);

// ...

try
{
    semaphore.Wait();
    //This one should be LIMITED to only 5 threads MAX!
    grab2 = checktwo(Hi, Hello);
}
finally
{
    // ensure the release of semaphore
    semaphore.Release();
}

You can even wait for it in async methods:
await semaphore.WaitAsync();


text:
Q: How do we understand the Word-Count sample of Apache Flink I'm just learning Apache Flink and here is the Word Count sample:
https://ci.apache.org/projects/flink/flink-docs-stable/getting-started/tutorials/local_setup.html
I works but I have something that can't understand clearly.
Flink have three parts: JobManager, TaskManager and JobClient. As my understanding, the java code of the class SocketWindowWordCount should be a part of JobClient, this class should send what it asks to do to the JobClient then the JobClient can send the tasks to the JobManager.
Am I right?
If I'm right, I don't know which part of code in the file SocketWindowWordCount.java is responsible to send what it asks to do to the JobClient.
Is listening on the port also a part of the task which will be sent to the JobManager then to TaskManager?
// get input data by connecting to the socket
DataStream<String> text = env.socketTextStream("localhost", port, "\n");

// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
    .flatMap(new FlatMapFunction<String, WordWithCount>() {
        @Override
        public void flatMap(String value, Collector<WordWithCount> out) {
            for (String word : value.split("\\s")) {
                out.collect(new WordWithCount(word, 1L));
            }
        }
    })
    .keyBy("word")
    .timeWindow(Time.seconds(5), Time.seconds(1))
    .reduce(new ReduceFunction<WordWithCount>() {
        @Override
        public WordWithCount reduce(WordWithCount a, WordWithCount b) {
            return new WordWithCount(a.word, a.count + b.count);
        }
    });

// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);

Is all of the codes above a part of the task?
In a word, I kind of understand the architecture of Flink but I want to know more details about how the JobClient works.

A: Your program itself is the JobClient from the architectural point of view. In particular, you have dependencies on the JobClient that are used when you execute the DataStream.
All of your code is the task definition that gets serialized and sent to the JobManager, which distributes it to the TaskManager.
You left out the "most" important part of the program

env.execute("Socket Window WordCount");

That is actually triggering the JobClient to package the DataStream program and send it to the configured JobManager.


text:
Q: allauth problems extending SignupForm class I keep finding outdated solutions that don't seem to be working.
I'm trying to change the error messages from English to Hebrew, for my website in django-allauth, I haven't checked if their are any translations because I would like to write them myself anyhow.
I tried changing for example the duplicate email error with the following code.
forms.py
from allauth.account.forms import SignupForm

class CustomSignupForm(SignupForm):
    def raise_duplicate_email_error(self):
        raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")

base.py (base settings file)
SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}

this resulted in the following error:
__init__() got an unexpected keyword argument 'sociallogin'

Traceback:
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/socialaccount/views.py" in dispatch
  38.         return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  68.                                             **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/views.py" in dispatch
  151.                                                           **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get
  205.         form = self.get_form()
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/django/views/generic/edit.py" in get_form
  74.         return form_class(**self.get_form_kwargs())
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  289.         super(SignupForm, self).__init__(*args, **kwargs)
File "/home/david/.virtualenvs/sikumim/lib/python3.4/site-packages/allauth/account/forms.py" in __init__
  223.         super(BaseSignupForm, self).__init__(*args, **kwargs)

Exception Type: TypeError at /accounts/social/signup/
Exception Value: __init__() got an unexpected keyword argument 'sociallogin'

What am I doing wrong?

A: You are inheriting from allauth.account.forms.SignupForm but using it in the setting SOCIALACCOUNT_FORMS, which is for social accounts. Your code should look like this:
website/forms.py
from allauth.socialaccount.forms import SignupForm

class CustomSignupForm(SignupForm):
     def raise_duplicate_email_error(self):
         raise forms.ValidationError("שם משתמש כבר קיים עם כתובת אימייל")

settings.py
SOCIALACCOUNT_FORMS = {
    'signup': 'website.forms.CustomSignupForm',
}

A: You need to overwrite the __init__() method and define sociallogin as parameter, which then will not be passed to the __init__() method of the super class.
Like this:
def __init__(self, sociallogin=None, *args, **kwargs):
    super().__init__(*args, **kwargs)


text:
Q: understanding Vue components and fileupload More reading on Vue components.
I don't understand the el property versus the name of the component.
The first two components simply use a template. The third seems to require the 'el' property. What should it point to? form again?
This gives me onFileChange is not defined:
app.js:
Vue.component('pg-title', {
    template: '
ATS Credits and Debits
'
});
Vue.component('pg-subtitle', {
    template: '
Table:
'
});
Vue.component('form', {
        el: '#app',
        data: {
            fileinput: ''
        },
        methods: {
            onFileChange(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createInput(files[0]);
            },
            createInput(file) {
                var reader = new FileReader();
                var vm = this;
                reader.onload = (e) => {

                vm.fileinput = reader.result;
                }
                reader.readAsText(file);

                console.log(this.fileinput);
            }

        }});

var vm = new Vue({
    el: '#app'
});

index.html:

<pg-title></pg-title>
<pg-subtitle></pg-subtitle>

<form enctype="multipart/form-data">
    <input type="file" @change="onFileChange">
</form>

A: Okay just a few things

*

*You need to use template rather than el when creating components.

*Take the template out of the main document flow and use the corresponding component tag name as an element or use the inline-template property.

*Don't name components the same as any standard html tags.

*Data should be a function.

Vue.component('v-form', {
        template: '#myform',
        data() {
          return{
            fileinput: ''
          };
        },
        methods: {
            onFileChange(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createInput(files[0]);
            },
            createInput(file) {
                var reader = new FileReader();
                var vm = this;
                reader.onload = (e) => {
                    vm.fileinput = reader.result;
                    console.log(vm.fileinput);
                }
                reader.readAsText(file);
            }
        }
});

new Vue({
  el: '#app',
})

  <v-form></v-form>

<template id="myform">
  <form enctype="multipart/form-data">
      <input type="file" @change="onFileChange">
  </form>
</template>

With inline-template, remove template from the component and define your html like this:

  <v-form inline-template>
      <form enctype="multipart/form-data">
        <input type="file" @change="onFileChange">
      </form>
  </v-form>


text:
Q: Unable to log in with your OpenID provider: No OpenID endpoint found Hello All,
These days more often I see the following error when I try to log in SO with my Yahoo account. I have raised a question regarding the same few months back and the question was closed as error didn't happen again. But for the past 2 weeks the error resurfaced and it was really frustrating me.
Note: This question was raised using the same Yahoo account
Can some thing be done on this please?alt text http://img121.imageshack.us/img121/7651/93536968.jpg

A: web5 had a bad DNS entry to yahoo.com for some reason.
We were unable to reach http://yahoo.com without extreme 10-30 second delays on that server, and specifically only on that server.
We flushed the web5 DNS cache, and now it resolves to a different IP address for Yahoo.com and seems to work now.

A: Recently same problem happened with me while tring to create different stackexchange account. While I tried to create "open data" https://opendata.stackexchange.com/
It told me to enable cookies for it.
So, it left as it is and moved to create another account. Then this problem appeared. What I did was I cancelled all my process of that account and retried to create other account.
This helped me. Hope, it will work for you too.
If this doesn't work try viewing this link:
https://askubuntu.com/help/openid-endpoint


text:
Q: MySQL PHP Query caching
I have question that is driving me insane.
I'm building a web store, and obviously all the products have properties, in my case, something like "power", "color"... and my costumer wants the ability to search filter them by those properties. I tried those options:

*

*Adding a row for every property in the 'products' table

*Table properties(id, displayName) and productProperties(property, product, value)

*Storing the properties fields and values in a JSON field in the product table.
I've chosen the third option after trying them all, and here comes my question:
Since all the queries I need to do are relative to the search result, is it possible to cache/store the result table and use it in the other queries?I'll explain: filtering the products means querying a table and selecting only the products that matches the filters, but then, I need to count the products in this subset (this is pretty easy to do with the last query) and get all the available properties that are present JUST in this subset of products. I could redo the filtering query every time, but it's inefficient, I already have asked the DBMS to do this query.
 Thanks for your help
Matteo


text:
Q: Reading unknown length line I have an unknown length line that is in this format
bobaboao dsaas : 5->2  2->3  4->6  7->2  1->4  5->1  8->1  222->1  23->13 ...

I need to read each
"X->Y"

and send to function
Dist(X,Y)

until the end of the line
How can I do this in MATLAB?

A: One suggestion I have is to use regular expressions so that you search for substrings within that string in your example that specifically have one ID, followed by -> followed by another ID.  Once we find these exact patterns in your string, we simply extract those out and place them into a cell array.  In other words, supposing that our string was stored in s (I'm actually going to use your example), do this:
s = 'bobaboao dsaas : 5->2  2->3  4->6  7->2  1->4  5->1  8->1  222->1  23->13';
g = regexp(s, '[0-9]+->[0-9]+', 'match');

Let's go through this code slowly.  s stores the string that you're analyzing, then the next line finds substrings in your string s that finds a sequence of at least one digit, followed by a ->, followed by at least one digit.  The 'match' flag extracts out the strings that match this pattern we are finding in s.  g is the output of this line, and each string is stored in a cell array.  We thus get:
g =

  Columns 1 through 7

    '5->2'    '2->3'    '4->6'    '7->2'    '1->4'    '5->1'    '8->1'

  Columns 8 through 9

    '222->1'    '23->13'

Note that storing into a cell array is important, because the length of each substring may be different.
Once we extract these substrings, what we can do is extract the numbers before and after the ->.  We simply apply two more regular expression calls to get the numbers before and after:
X = regexp(g, '^[0-9]+', 'match');
Y = regexp(g, '[0-9]+$', 'match');

The first call looks for substrings at the beginning of each string in g that starts with a number, while the second call looks for substrings at the end of each string in g that ends with a number.  What will be returned are the numbers contained in cell arrays.  Also, the numbers themselves are strings.  Because each element in the cell is a string, we should convert these back into actual numbers.  We should also place these into a numeric vector for you to use with your code:
X = cellfun(@str2double, X);
Y = cellfun(@str2double, Y);

cellfun is a function that allows you to apply a particular function to each cell in a cell array.  In this case, we want to convert each number in the cell array as it's a string into double.  Therefore, use str2double to facilitate this conversion.  Once we're done, we will get numeric vectors that give you the numbers before the -> and after the ->.
We finally get:
X =

     5     2     4     7     1     5     8   222    23

Y =

     2     3     6     2     4     1     1     1    13

A: I'd use regexp with 'tokens', which pulls out the bits of the match in between parentheses (()):
>> C = regexp(s,'(\d*)->(\d*)','tokens')
C =
    {1x2 cell}    {1x2 cell}    {1x2 cell}    {1x2 cell}    {1x2 cell}   ...
    {1x2 cell}    {1x2 cell}    {1x2 cell}    {1x2 cell}
>> xy = str2double(vertcat(C{:})).'
xy =
     5     2     4     7     1     5     8   222    23
     2     3     6     2     4     1     1     1    13

Then you have X = xy(1,:); and Y = xy(2,:);.
Explained: \d is a digit ([0-9]), \d* means any number of digits.  Wrapping them in () makes them tokens.  The whole pattern defines a match, but the tokens are extracted into a cell array of cell arrays, one cell array for each match, containing cell arrays for the tokens.  It's easy to make a single matrix with vertcat and convert it with str2double.

A: I found a tricky way:
0)delete the alphabetical sequence by writing the following line:
  str(1:strfind(str,':'))=''

1)concatenate this string in the following way:
newStr=['[',str,']']

, so that now your new string will be: '[5->2  2->3  4->6  7->2  1->4  5->1  8->1  222->1  23->13]'
2)delete all the '>'  , you can do it by the command:
newStr(newStr=='>')=''

,so that now you will have '[5-2  2-3  4-6  7-2  1-4  5-1  8-1  222-1  23-13]',
pay attention that this is actually a string that represents a vector that contains the distances between the numbers, and that leads us to step 3...
3)evaluate the string we get:
distances=eval(newStr);

if you want the distances without + an - , just use abs() function.


text:
Q: check_diag is not working properly it is showing win in only 2 "x"/"o" def check_diag(user, board):
    #Top left to bottom right
    if board[0][0] == user and board[1][1] == user and board[2][2] == user:
        return True
    elif board[0][2] == user and board[1][1] == user and board[0][2] == user:
        return True
    else:
        return False

A: You have a typo in your elif statement. You have board[0][2] twice. It should be board[2][0].
Try this:
def check_diag(user, board):
    #Top left to bottom right
    if board[0][0] == user and board[1][1] == user and board[2][2] == user:
        return True
    elif board[0][2] == user and board[1][1] == user and board[2][0] == user:
        return True
    else: return False


text:
Q: UVA 195 Anagram - Runtime Error - C++ I'm trying to solve the UVA 195 problem, but besides the accurate results in tests, the Online Judge returns "Runtime Error".
The function called "fatorial" calculates the factorial of a given number.
The function called "permutacoes" calculates the number of permutations of a given word.
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>

using namespace std;

int fatorial (int a){
    int resultado = 1;
    for(int i=1; i<=a; i++) resultado *= i;
    return resultado;
}

int permutacoes (string s){
    int t = s.length();

     //conta as repetições de cada letra
    int rep[t];
    for(int i=0; i<t; i++) rep[i]=1;
    for(int i=0; i<t; i++){
        if(rep[i]==1){
            for(int j=(i+1); j<t; j++){
                if(s[i]==s[j]){
                    rep[i]++;
                    rep[j] = 0;
                }
            }
        }
    }

    //Calcula o número de permutações
    int fat = fatorial(t);
    int dividendo = 1;
    for(int i=0; i<t; i++){
            if(rep[i]>1) dividendo *= fatorial(rep[i]);
    }
    int resultado = fat/dividendo;
    return resultado;
}

int main()
{
    int n;
    string s;
    cin>>n;

    while(n--){
        cin>>s;
        sort(s.begin(),s.end()); //Ordem inicial
        cout<<s<<endl; //Primeira saída

        int perm = permutacoes(s);
        //Todas as permutações, menos a primeira que já foi dada pelo sort
        while (--perm){
            next_permutation(s.begin(),s.end());
            cout<<s<<endl;
        }
    }

    return 0;
}

A: The problem could be in the way you are calculating the number of permutations. The program is maybe trying to divide some really big numbers, but one of those numbers is maybe overflowed (larger than maximum for int), and so incorrect.
Check your algorithm with word "aaaaaaaaaabbbbbbbbbb" (10 letters 'a' and 10 letters 'b'). You should get 20!/(10!*10!)=184756 permutations, but I bet you will get some other value. Redirect the program output to a file, so that it finishes faster.
To solve the problem remove the function permutacoes and run the loop for as long as next_permutation is returning true. When next_permutation returns false there are no more permutations, and the word should be sorted as it was before the loop.


text:
Q: jQuery Controlling Single DIVs With the Same Class (Siblings?) I am building a FAQ module for my site and I want to be able to control single elements on the page even though they all have the same class. I believe this comes under siblings which I am not yet familiar with.
Basically I want the user to be able to click the question div and then when they click it the answer div within the same div as the question div is set to show (if that makes sense!). Any help would be greatly appreciated.

What is the airspeed velocity of an unladen swallow?

Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour.

What is the airspeed velocity of an unladen swallow?

Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour.

What is the airspeed velocity of an unladen swallow?

Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour.

A: If I understand your question correctly, you should
Start by setting all answers as hidden in the css:
.answer {display:none;}
Then you can use jquery to show the correct answer to the clicked questions :
$(document).ready ( function () {
    $('.question').click(function() {
        $(this).next('.answer').show();
    });
});

Edit: you can also use .toggle() instead of .show() to show/hide.

A: You should probably check out this question where something similar is done.
Basically, you first need to setup ID's for your elements so that you can identify single elements within the set classes.
You could then add a click event handler which would set the selected item and show the appropriate answer.
You can see the syntax for grabbing siblings in the documentation here.


text:
Q: Statistical analysis of variable data I have the statistical research data. I have 6 treatments with 3 boxes for each treatment. I am raining on the treatments every week and collecting data. The data is variable within boxes and also with time. For eg: on 20 July, value for seeded treatment was 4500 and after the end of August, the value becomes 2000 with the increase in vegetation. The standard deviation of the treatment for the whole study period is sometimes more than mean due to higher variability. the sample size for the whole study period is close to 350. The data comes out to be normal. out of 6 treatments, 4 treatments have very lower values than other 2 treatments. for eg: 4 treatments have the values in range of 50-500 and other 2 have the values in range of 2200-2500. When I performed Tukey Kramer on all 6 treatments, there is no significance among the 4 treatments. When I apply Tukey Kramer on just the 4 low value treatments, there is some significance among the treatments. How is it possible? What exact analysis or test can I perform on this kind of data? I would be highly obliged if someone has some suggestions or solutions. I need to defend soon and i need to finish this statistical analysis. Data is a non uniform time series data also and I don't know which statistical analysis or test need to be performed on this kind of data. I am really confused. I will really appreciate any help.
Thanks

A: Repeated-measures ANOVA is a possibility. Not clear: "data is variable within boxes and also with time", where there multiple subsamples at each time point?
Since Tukey test corrects for experiment-wise error rate, reducing the SE, eg dropping the two treatments as described above, can increase the test statistic/decrease the p-value.
It is not unheard of to follow up an ANOVA with multiple treatment levels by another one, where the 'larger' and the 'smaller' groups are compared. It is not very prudent, because it reformulates the question after testing, but not impossible.


text:
Q: phabricator: nothing in blocking tasks or linked task views I installed phabricator, and I'm trying to link a parent task to a child.  From the defect, whenever I click on "merge duplicates in" or "Edit blocking tasks", I see a dialog with a filter, but the list of tasks is always empty.
I definitely have tasks that can/should be merged; is there something else I have to do to "allow" them to be merged?
Edit:  I figured out that it's only my user that has this issue.  Other users are fine.  Any one else seen this?

A: I can't reproduce this, offhand. If you think it's a bug, please file it in the upstream and we'd be happy to help.
Note that "Assigned to Me" is the default filter, so if you have no tasks, the list will be blank. You can change it to "All Tasks" to widen search scope.


text:
Q: Neural network: how to normalize user behavior as input I am working on a neural network project which reads server log files and tries to categorize users into candidate buyers and random surfers buckets.
The log file looks like
timestamp, user_id, event, page
1454973364, user_A, enter, http://some_url/?page=dashboard
1454973365, user_A, enter, http://some_url/?page=search&q=tablet
1454973366, user_A, enter, http://some_url/?page=faq&item=1234
1454973366, user_B, enter, http://some_url/?page=about_us
1454973366, user_A, enter, http://some_url/?page=order_placed
...
1454973368, user_A, exit, http://some_url/?page=order_placed
1454973368, user_B, exit, http://some_url/?page=about_us

All users like user_A should be positively targeted as candidate buyers and user_B should be negatively targeted and categorized as random surfers. Of course, the goal of my project is to make a prediction before the user hits the conversion page order_placed.

*

*What is the best way to model series of events like this into inputs?

*A more general question. From the log data we can obtain the info about how users engage our site (drag a widget, click a link, scroll down/up, time spent on page, etc.). Given an array of actions like these, what is the general approach in machine learning to model them as inputs?


text:
Q: Jackson : Read json entry (with missing fields) into a POJO I have a json entry like :
{
    "name" : "tom"
    "age" : 10
}

Some json entries have an additional field of address.
I'm trying to read it to a POJO defined as follows :
public class StudentDetails {

    @NonNull
    private final String name;

    @NonNull
    private final int age;

    private final String address;

I'm unable to deserialise this. What Jackson annotation can I use to accomplish this ? Some of the entries will have the field of address whereas others won't.
Tried using @NonNull, @Nullable, @JsonIclude, @JsonIgnoreProperities, Optional<>

A: Try to use this:
@JsonInclude(JsonInclude.Include.NON_NULL)

This indicates that only properties with non-null values are to be included.


text:
Q: How to ignore children classes when extracting text from a class using Selenium in Python? I am trying to extract the text from a class on html page using Selenium in Python. While doing so, my code is also extracting the text from its child class.
Below is the code I am using:
monthlyprice = browser.find_element_by_class_name('tila-container').text

HTML Snippet:

+ $8
25
x 24/mo. If you cancel wireless service, remaining balance on phone becomes due. 0% APR O.A.C for well-qualified buyers. Qual'g service req'd.

Above pasted piece of HTML code is the one which is causing problem, I want to extract text value + $8 mentioned under tila-container class but my code is giving me text present under its child class super-decimal-price and I also don't want text mentioned after this child class starting from "x 24/mo."
Folks help me in resolving this.

A: It's difficult. As far as webdriver is concerned, the text before and after the child  is equally validly part of the text content; and it doesn't have methods to just return bits and pieces of the text content.
What I'd try is:

*

*Use a method to get the full inner html of the div.

*Use string manipulation to divide it up into three parts; before the , the  itself, and after the .

The first part is reasonably straightforward; see Get HTML Source of WebElement in Selenium WebDriver using Python for how to get the html source of a single element.
The second part is not too difficult either; it should be easy enough with python's string functions. It will get complicated, however, if the format of the inner text is more variable (i.e. not just text-span-text each time).
Good luck!


text:
Q: Find out what or who calls/triggers shockwave/activeX/flash We sometimes see this bar "A plugin (shockwave flash) is not responding" on web pages which often freezes the page.

While trying to debug it, I can't figure out who is calling this shockwave flash, Are there any tools that can give a clue who initiated this or any flash?
Are there any tools that can give a hint of what is the cause of this?

A:
Are there any tools that can give a hint of what is the cause of this?

You can try installing the Flash Player Debugger version which might give you hint messages.
See this Adobe guide for setting up in Chrome browser. Also you can try the 2015-dated solutions in this other Question.

...what is the cause of this?

Usually it's the running code in the SWF (Flash file) that causes this error. Not so much caused by an external caller/callee of the SWF.
For example : A while loop that does not get all required conditions to end/break will run forever (freezing the system) so browser eventually gives you the timeout error & option to stop plugin as shown in your image.
Other examples include code that should really be in a try / catch format but if there's only some "do this task" command & no error is caught or handled then the app is stuck for a long time.


text:
Q: Cannot Open fi-site-init.el Lately i've been trying to install ELI on my Linux computer!
I've followed the guide from http://www.franz.com/emacs/ to make it work! I've also searched for similar errors and found this thread http://ubuntuforums.org/showthread.php?t=1646855
However unlike the person in the forum I cannot load the fi-site-init.el file from the scratch buffer.
By opening emacs with the --debug-init flag i get the following error messege
  Debugger entered--Lisp error: (file-error "Cannot open load file" "fi-site-init.el")
  load("fi-site-init.el")
  eval-buffer(#<buffer  *load*> nil "/home/simon/.emacs" nil t)  ; Reading at buffer position 82
  load-with-code-conversion("/home/simon/.emacs" "/home/simon/.emacs" t t)
  load("~/.emacs" t t)
  #[nil "\205\264

What can be worth noticing is that in the guide they have

"/usr/local/acl82express/eli"

as the search path while i'm having

"/usr/Documents/acl82express/eli"

as path (since Allegro CL is installed there)
All in all this is what I've writed in the .emacs file
 (push "/usr/Documents/acl82express/eli" load-path)
  (load "fi-site-init.el")
  (setq fi:common-lisp-image-name "/usr/Documents/acl82express/alisp")
  (setq fi:common-lisp-image-file "/usr/Documents/acl82express/alisp.dxl")
  (setq fi:common-lisp-directory "/usr/Documents/acl82express")

I am thankful for any help!
Simon Nyström

A: Notice the leading "/"-symbol. I'm quite sure it'd have to be "/usr/Documents/acl82express/eli" for you.

A: Documents is typically the name of the directory in the user home directory. It is customary to find it under /home/{user}/Documents where {user} is the currently logged in user. who am i | awk '{ print $1 }' - this is the way to find out, unless you forget :)
This directory is often times aliased with ~ (tilde) or $HOME environmental variable, so that when doing path expansion happens these "$HOME/Documents", "~/Documents" and "/home/{user}/Documents" will all point to the same directory.


text:
Q: Sequelize not updating a row in table I am using sequelize for the first time. I have a table called feed in my DB, with columns ID, caption, and url. In my controller I have a simple function where I am updating a row in a table:
router.patch('/:id',
    requireAuth,
    async (req: Request, res: Response) => {
        let { id } = req.params;
        const item =  await FeedItem.update({ ...req.body }, {
            where: {
              id: id
            }
        });
        if (item === null) {
            return res.status(404).send({ message: 'Feed not found' });
        }
        res.send(item);
});

I am sending json body that looks like this:
{
    "caption": "NewTest",
    "url": "Newtest.jpg"
}

I see that data is sent correctly in the console, but when I post to the endpoint with an id of 2, I get as a response:
[
    1
]

I can also see in the DB, that the row has not been updated.
What am I doing wrong here, how can I updated a row in the table and return the new updated value?

A: FeedItem.update method returns count of affected rows. That is why you are getting 1. If you need to have FeedItem instance itself you can retrieve it first and update the instance:
let feedItem = await FeedItem.findById(id);
if (!feedItem) {
   return res.status(404).send({ message: 'Feed not found' });
}
feedItem = await feedItem.updateAttributes(req.body);

return res.send(feedItem);


text:
Q: Cut data (seasonal component) I'm looking for R code which cut my data.
My initial data looks like that :

Here are the first 300 rows :
c(0.096, 0.088, 0.082, 0.078, 0.06, 0.057, 0.048, 0.047, 0.044,
0.044, 0.039, 0.038, 0.037, 0.037, 0.035, 0.035, 0.034, 0.034,
0.033, 0.033, 0.032, 0.032, 0.031, 0.031, 0.031, 0.031, 0.03,
0.03, 0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.2, 1100,
1100, 27, 15, 3.2, 2.2, 1, 0.65, 0.37, 0.3, 0.19, 0.16, 0.12,
0.12, 0.099, 0.096, 0.085, 0.082, 0.064, 0.06, 0.051, 0.05, 0.046,
0.045, 0.041, 0.041, 0.039, 0.038, 0.037, 0.036, 0.035, 0.035,
0.034, 0.033, 0.032, 0.032, 0.032, 0.031, 0.031, 0.031, 0.03,
0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.029, 0.028, 0.028,
0.028, 4.4, 1100, 1100, 120, 21, 9.4, 3.1, 1.6, 0.85, 0.51, 0.33,
0.23, 0.18, 0.18, 0.13, 0.11, 0.1, 0.092, 0.085, 0.077, 0.065,
0.058, 0.053, 0.05, 0.047, 0.045, 0.043, 0.042, 0.039, 0.038,
0.037, 0.036, 0.035, 0.035, 0.034, 0.033, 0.033, 0.032, 0.031,
0.031, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.028,
0.028, 0.028, 0.028, 0.028, 37, 1100, 98, 17, 6.2, 2.7, 1.3,
1, 0.47, 0.31, 0.23, 0.16, 0.14, 0.11, 0.1, 0.093, 0.087, 0.079,
0.066, 0.057, 0.053, 0.049, 0.046, 0.044, 0.041, 0.04, 0.037,
0.036, 0.035, 0.035, 0.033, 0.033, 0.032, 0.032, 0.031, 0.031,
0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.028, 0.028, 0.028,
0.027, 0.027, 0.027, 0.026, 0.026, 0.026, 2.6, 1100, 1100, 190,
22, 7.8, 3.2, 2.2, 0.91, 0.51, 0.37, 0.23, 0.18, 0.14, 0.12,
0.11, 0.098, 0.09, 0.085, 0.071, 0.061, 0.055, 0.051, 0.049,
0.045, 0.043, 0.04, 0.039, 0.037, 0.036, 0.035, 0.034, 0.033,
0.032, 0.032, 0.031, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.028,
0.028, 0.028, 0.027, 0.027, 0.027, 0.026, 0.026, 0.026, 0.026,
0.026, 8.8, 1100, 160, 21, 7.5, 3.4, 1.6, 0.89, 0.52, 0.33, 0.23,
0.17, 0.14, 0.13, 0.1, 0.094, 0.087, 0.078, 0.065, 0.056, 0.051,
0.049, 0.045, 0.043, 0.039, 0.039, 0.036, 0.035, 0.034, 0.033,
0.032, 0.032, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.028, 0.028,
0.027, 0.027, 0.026, 0.026, 0.026, 0.026, 0.025, 0.025, 0.025,
0.025, 0.025, 0.025, 13, 1100, 170)

And here is data structure :
> dput(head(.data))
structure(list(y = c(0.096, 0.088, 0.082, 0.078, 0.06, 0.057),
    x = 1:6), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))

And if I zoom on it :

And the result I would like to have is this (this graphic only represents the first 300 rows. I didn't use any algorithm ) :

I tried to cut my data with this algoritm :
find_cycle <- function(x, y) {
  dy <- diff(c(0, y))
  cut(
    x = x,
    breaks = c(min(x), which(dy > mean(dy) + 3 * sd(dy)), max(x)),
    include.lowest = TRUE,
    right = FALSE
  )
}
.data <- .data %>%
  mutate(cycle = find_cycle(x, y)) %>%
  group_by(cycle) %>%
  mutate(x_cycle = 1:n()) %>%
  ungroup()

p <- ggplot(data = .data, mapping = aes(x = x_cycle, y = y, colour = cycle)) +
  geom_point() +
  geom_line() +
  theme(legend.position='none')

p

But the result is not what I expected :

Do you have some idea ? Thanks.
I apologize for not being word-perfect in English.

A: Your function only works if you have a previous x-axis. Which was only possible to know how you build it based on your data structure.
But seems everything is working.
d <- tibble(y = c(0.096, 0.088, 0.082, 0.078, 0.06, 0.057, 0.048, 0.047, 0.044,
  0.044, 0.039, 0.038, 0.037, 0.037, 0.035, 0.035, 0.034, 0.034,
  0.033, 0.033, 0.032, 0.032, 0.031, 0.031, 0.031, 0.031, 0.03,
  0.03, 0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.2, 1100,
  1100, 27, 15, 3.2, 2.2, 1, 0.65, 0.37, 0.3, 0.19, 0.16, 0.12,
  0.12, 0.099, 0.096, 0.085, 0.082, 0.064, 0.06, 0.051, 0.05, 0.046,
  0.045, 0.041, 0.041, 0.039, 0.038, 0.037, 0.036, 0.035, 0.035,
  0.034, 0.033, 0.032, 0.032, 0.032, 0.031, 0.031, 0.031, 0.03,
  0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.029, 0.028, 0.028,
  0.028, 4.4, 1100, 1100, 120, 21, 9.4, 3.1, 1.6, 0.85, 0.51, 0.33,
  0.23, 0.18, 0.18, 0.13, 0.11, 0.1, 0.092, 0.085, 0.077, 0.065,
  0.058, 0.053, 0.05, 0.047, 0.045, 0.043, 0.042, 0.039, 0.038,
  0.037, 0.036, 0.035, 0.035, 0.034, 0.033, 0.033, 0.032, 0.031,
  0.031, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.028,
  0.028, 0.028, 0.028, 0.028, 37, 1100, 98, 17, 6.2, 2.7, 1.3,
  1, 0.47, 0.31, 0.23, 0.16, 0.14, 0.11, 0.1, 0.093, 0.087, 0.079,
  0.066, 0.057, 0.053, 0.049, 0.046, 0.044, 0.041, 0.04, 0.037,
  0.036, 0.035, 0.035, 0.033, 0.033, 0.032, 0.032, 0.031, 0.031,
  0.03, 0.03, 0.029, 0.029, 0.029, 0.029, 0.028, 0.028, 0.028,
  0.027, 0.027, 0.027, 0.026, 0.026, 0.026, 2.6, 1100, 1100, 190,
  22, 7.8, 3.2, 2.2, 0.91, 0.51, 0.37, 0.23, 0.18, 0.14, 0.12,
  0.11, 0.098, 0.09, 0.085, 0.071, 0.061, 0.055, 0.051, 0.049,
  0.045, 0.043, 0.04, 0.039, 0.037, 0.036, 0.035, 0.034, 0.033,
  0.032, 0.032, 0.031, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.028,
  0.028, 0.028, 0.027, 0.027, 0.027, 0.026, 0.026, 0.026, 0.026,
  0.026, 8.8, 1100, 160, 21, 7.5, 3.4, 1.6, 0.89, 0.52, 0.33, 0.23,
  0.17, 0.14, 0.13, 0.1, 0.094, 0.087, 0.078, 0.065, 0.056, 0.051,
  0.049, 0.045, 0.043, 0.039, 0.039, 0.036, 0.035, 0.034, 0.033,
  0.032, 0.032, 0.031, 0.03, 0.03, 0.03, 0.029, 0.029, 0.028, 0.028,
  0.027, 0.027, 0.026, 0.026, 0.026, 0.026, 0.025, 0.025, 0.025,
  0.025, 0.025, 0.025, 13, 1100, 170))

d <-  d %>% mutate( x = row_number() )

find_cycle <- function(x, y) {
  dy <- diff(c(0, y))
  cut(
    x = x,
    breaks = c(min(x), which(dy > mean(dy) + 3 * sd(dy)), max(x)),
    include.lowest = TRUE,
    right = FALSE
  )
}
d %>%
  mutate(cycle = as.character(find_cycle(x, y))) %>%
  group_by(cycle) %>%
  mutate(x_cycle = 1:n()) %>%
  ungroup() %>%
  ggplot(aes(x = x_cycle, y = y, colour = cycle)) +
  geom_point() +
  geom_line()


text:
Q: How to "frankenstine" wires? How do I make a different usb wire type out of two different usb wires? For example, say I have two standard usb-to-micro-usb wires and I want to make one usb-to-usb and then one micro-usb-to-micro-usb. Could I just cut and strip both of the wires and then solder the two remaining usb heads together to make a usb-to-usb? (Same thing goes with the other micro USB heads)
With that, I can charge my device through my makeshift usb-to-usb connected to a female usb hub!

A: Yes, it's possible in a pinch.
You will need make sure the pinouts correspond to the correct wires after you have cut the cable. They need to be matched with the other connector.
An example, here is a USB 2.0 pinout:

You'll need to use a multimeter or ohmmeter to check for continuity of the wires and the pins and ensure they match with the correct pins on the other connector.
However, I would strongly advise against doing that; it's much less trouble (and more importantly, time) to just purchase your needed cables. The cables are also made to specific electrical specifications (e.g. current rating, resistance, etc.) that may or may not be to standard with a home made cable.


text:
Q: how to write to a directory C I'm trying to copy directory contents to another directory
but I'm having a problem with writing to the second directory without using sprintf; Any suggestions?
void Copying(char *folder1, char *folder2) {
    DIR *s1, *s2;
    struct dirent *dep;

    if ((s1 = opendir(folder1)) == NULL) {
        printf("Error\n");
        return;
    }
    if ((s2 = opendir(folder2)) == NULL) {
        printf("Error \n");
        return;
    }

    while ((dep = readdir(s1)) != NULL) {
        //write(s2 , dep->d_name , sizeof(dep) ) ; // <-
    }
    closedir(s1);
    closedir(s2);

    return;
}

A: This approach won't work. Directory handles are not writable.
If you want to copy the contents of a directory, you will need to copy each file, directory, and link in the source directory individually. To copy each file, you will need to create a new file in the target directory and write the contents of the source file into it.


text:
Q: Counting monomials in skew-symmetric+diagonal matrices This question is motivated by Richard Stanley's answer to this MO question.
Let $g(n)$ be the number of distinct monomials in the expansion of the determinant of an $n\times n$ generic "skew-symmetric $+$ diagonal" matrix.
For example, $g(3)=4$ since
\begin{align*}
\det\begin{pmatrix} x_{1,1}&x_{1,2}&x_{1,3} \\
-x_{1,2}&x_{2,2}&x_{2,3} \\ -x_{1,3}&-x_{2,3}&x_{3,3}
\end{pmatrix}
&=x_{1, 1}x_{2, 2}x_{3, 3}+x_{1, 1}x_{2, 3}^2+x_{1, 2}^2x_{3, 3}
+x_{1, 3}^2x_{2, 2}.
\end{align*}
The sequence $g(n)$ seems to have found a match in OEIS with the generating function
  $$ \sum_{n\geq 0} g(n)\frac{x^n}{n!} = \frac{e^x}{1-\frac12x^2}.$$

QUESTION. Is it true and can you furnish a proof for
  $$g(n)=\sum_{k=0}^{\lfloor \frac{n}2\rfloor}\frac{n!}{(n-2k)!\,\,2^k}?$$

POSTSCRIPT. I'm convinced by Stanley's reply below, so let's correct the above as follows:
$$g(n)=\sum_{k=0}^{\lfloor n/2\rfloor}\binom{n}{2k}\frac{(2k)!}{k!}\cdot\prod_{i=1}^k\frac{4i-3}4\cdot\sum_{j=0}^{\lfloor n/2-k\rfloor}
\binom{n-2k}{2j}\frac{(2j)!}{4^j\,j!}.$$

A: The correct generating function is
 $$ \exp\left( x +\frac{x^2}{2}+\frac 12\sum_{n\geq 2}\frac{x^{2n}}{2n}\right)
   =\frac{\exp\left(x+\frac{x^2}{4}\right)}{(1-x^2)^{1/4}}. $$
This appears in http://oeis.org/A243107, but without a combinatorial or algebraic interpretation. For skew symmetric matrices just multiply by $e^{-x}$.


text:
Q: How to handle Azure App Service WebSockets timeout? I have 2 app services instances set up in Azure, with one connecting to the other through a WebSocket connection. Some of the connections are long-running (multiple minutes) as the processing takes time. After approx. 2 minutes and a few seconds (I assume it's about the 230 second idle timeout Azure has) the connections time out with ECONNTIMEDOUT. Is there any way to circumvent this with WebSockets? Locally, everything works as expected.

A: The Azure apps have an 'idle timeout.'
According to Microsoft, this is usually between 4 and 30 minutes long, after this time, your client's connection is removed.
Apparently, this is configurable.
You should be able to go into the app's config settings i.e,  app.config for app service and change the idle timeout property on any endpoints you have open on the app like so.
Ex:
<InputEndpoint name="MyEndpoint" protocol="tcp" localPort="80" port="80" idleTimeoutInMinutes="30" />

A: If its an ASP.Net (Framework) app you can setup a heartbeat message to push down the WebSocket to keep the connection open. .net core also has something similar I believe.
You can use the HttpRuntime.Cache to set this up really easily as Jeff Atwood explains on the Stackoverflow Blog: https://stackoverflow.blog/2008/07/18/easy-background-tasks-in-aspnet/


text:
Q: Python paramiko SSH nothing returned when blocked by dialog I'm using paramiko to ssh into a server and then from this server ssh into another one just to get the fingerprint, so I'd like to see the message that asks if I want to accept that fingerprint or no.
I'm using this code:
    stdin,stdout,stderr = self.ssh.exec_command(command)
    outlines = stdout.readlines()
    resp = ''.join(outlines)
    return resp

but it returns me nothing. I think it's because at some point the ssh command wait for me to input yes/no if I want to accept the fingerprint. I did man ssh and didn't find a way to automatically answer no for this question.
I've found this: Reading output of Top command using Paramiko which teaches how to invoke a shell. But what if I want to receive the text just up to the stopping point?


text:
Q: C++ Bank Project; How do I read string from file convert to float and sum all Problem statement: C++ program that reads a customer's checking account information calculates his/her account balance. menu based application should be developed to perform the following functionalities iteratively until the user request to quit the program: 1. Display, 2. Deposit, 3. Withdraw, 4. Quit.
This is what I have so far.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

//Main function
int main()
{
    //Identify type variables
    int x=0;
    float amountinput,famount,sum;
    string firstname, lastname,date,filename,input,ID,amount;
    fstream file;
//Program loop
    while(true)
    {
        //Main menu loop
        do
        {

        cout<<"Enter the number of the option you would like carried out.\n";
        cout<<"1. Summary\n";
        cout<<"2. Deposit\n";
        cout<<"3. Withdraw\n";
        cout<<"4. Quit\n";
        cin>>x;
    }
    while(!x);

    //When Quit is input, break
    if(x==4)
    {
        break;
    }
        //Summary display
        if (x==1)
        {
            cout<<"You have selected option number 1. Summary.\n"<<endl;
            cout<<"Enter your Cust_ID: ";
            cin>>ID;
            file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
                       \\Cust_"+ID+".dat", ios::in|ios::out|ios::app);

            //IF not found error.
            if(!file)
            {
                cout<<"Sorry your account could not be found\n";
            }
            //Else display all content.
            else
            {
                    cout<<endl<<file.rdbuf()<<"\n";
                    file.close();

            }
        }
        //Deposit
        else if(x==2)
        {
            cout<<"You have selected option number 2. Deposit.\n";
            cout<<"Please enter you account ID: ";
            cin>>ID;
            file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement
                        \\Cust_"+ID+".dat", ios::in|ios::out|ios::app);

            if(!file)
            {
                cout<<"Sorry the requested account could not be located.\n";
            }
            else
            {
            file>>firstname>>lastname;
            cout<<endl<<firstname<<" "<<lastname<<endl;
                while(!file.eof())
                {
                    file>>date>>amount;
                    //
 %%%%%%%%%%%%%%%%%%%//This is mainly where I am missing the lines of code..
                    //
                    float atof(string& amount);
                    cout<<date<<"\t\t"<<amount<<endl;
                }

                    cin.get();cin.get();
                cout<<"How much would you like to deposit today.";
                cin>>amountinput;

                cout<<endl;
                file.close();

            }
        }

            else if(x==3);
            else if(x==4);

}
cin.get();cin.get(); //or system("PAUSE");
return 0;
}

A sample text file looks like this but has different number of lines.
James Bond
01/01/12 200010
03/30/12 -40000
04/30/12 -40000
05/30/12 -40000
06/30/12 -40000
07/30/12 -40000

I have set amount = string, I then want each string to be individual from each other (so that I may add them) and have them converted to float or double, whichever.
Basically, something like:
fstream file;
do
file>>date>>amount++; //I know this doesn't work, what will..
while(!file.eof());
float deposit;
finalAmount= deposit+amount;

A: The nice thing about the C++ input operator >> is that it can take different types of arguments, like e.g. a double:
std::string date;
double amount;

file >> date >> amount;

However, I rather recommend using std::getline and std::istringstream to parse it:
std::string line;
std::getline(file, line);

std::istringstream iss(line)
iss >> date >> amount;

On a somewhat related note, don't use while (!file.eof()). The eof flag will not be set until an actual input operation fails, so unless you check for errors inside the loop you will attempt to read once to many.
Instead do e.g.
while (std::getline(file, line))
{
    ...
}


text:
Q: WPF Label not updating while performing a time consuming method I am nearly ashamed to ask this, but...
EDIT:
I edited the question to show the code I have come up with. It does not work... No "test" caption becomes visible on the main form.
Private _dispatcher As Dispatcher
Delegate Sub SetLabelText(caption As String)
Private _setLabelText As SetLabelText

Public Sub New()
    _setLabelText = New SetLabelText(AddressOf SetConnectionStatus)
    _dispatcher = Dispatcher.CurrentDispatcher
    ',,,
End Sub

Public Sub Connect
   Try
         _dispatcher.BeginInvoke(DispatcherPriority.Normal, _setLabelText, "test")
        ConnectionStatus = "Connecting to server..."
        _client = WCFClient.GetClient
        Response = _client.GetInfo(Request)
        ConnectionStatus = "Connected to server"
    Catch ex As System.TimeoutException
        ConnectionStatus="Timeout"
    Catch ex As System.ServiceModel.EndpointNotFoundException
        ConnectionStatus="Server down"
    End Try
End Sub

 Private Sub SetConnectionStatus(statusMessage As String)
    ConnectionStatus = statusMessage
 End Sub

Private _connectionStatus As String
Public Property ConnectionStatus() As String
    Get
        Return _connectionStatus
    End Get
    Set(ByVal value As String)
        _connectionStatus = value
        OnPropertyChanged("ConnectionStatus")
    End Set
End Property

Private Sub OnPropertyChanged(propertyName As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub

Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

This bit of code lives in my ViewModel for a WPF form, change notification is implemented through INotifyPropertyChanged. The ConnectionStatus property is bound to the Content of a Label on the form.
The 'Connecting to server..' message is never shown, only one of the three resulting statusmessages. Obviously I have to move some task to an other thread. What is the easiest way to do it?

A: Either use Dispatcher or a BackgroundWorker.
Dispatcher:
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx
BackgroundWorker:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx


text:
Q: If $f : (a,b) \to \mathbb{R}$ is differentiable, then $f$ is continuous: prove using $\epsilon$-$\delta$ Let $f : (a,b) \rightarrow \mathbb{R}$ be differentiable on $(a,b)$.
Prove that $f$ is continuous by showing that
$\forall x_0 \in (a,b) \qquad \forall \epsilon>0 \qquad \exists \delta >0  $ s.t.$ \; \;(x\in (a,b), |x-x_0| < \delta) \implies |f(x)-f(x_0)|<\epsilon$
This is a 6 mark question on a practice Analysis 2 module.
Frustratingly there are no solutions and I'm not sure where to start.
Any help is greatly appreciated.

A: Observe that for all $x \neq x_0$, $x, x_0 \in (a,b)$, we have
$$
\begin{align}
|f(x) - f(x_0)| &= |f(x) - f(x_0)| - |(x - x_0)f'(x_0)| + |(x-x_0)f'(x_0)|\\
&\leq |f(x) - f(x_0) - (x-x_0)f'(x_0)| + |(x-x_0)f'(x_0)|\\
&= |x - x_0| \frac{|f(x) - f(x_0) - (x-x_0)f'(x_0)|}{|x-x_0|} + |(x-x_0)| |f'(x_0)|
\end{align}
$$
Now, for every $\epsilon > 0$ there exists $\delta > 0$ such that
$$
\left| \frac{f(x) - f(x_0) - (x-x_0)f'(x_0)}{x-x_0} \right| < \epsilon
$$
for all $|x - x_0| < \delta$. This is just a restatement of the existence of the derivative in terms of $\epsilon$'s and $\delta$'s.
So, for this $\epsilon > 0$, we have that
$$
|f(x) - f(x_0)| < \delta \epsilon + \delta |f'(x_0)|.
$$
Therefore, choosing $$\delta < \frac{\epsilon}{\epsilon + |f'(x_0)|},$$
we see that $|f(x) - f(x_0)| < \epsilon$ whenever $|x - x_0| < \delta$.

A: Fix $x_0 \in (a,b)$. $f$ is differentiable at $x_0$ means the limit $\lim_{x \rightarrow x_0} \frac{f(x)-f(x_0)}{x-x_0}=L$ exists.
By definition of limit, for any $\varepsilon>0$, there exists some $\delta>0$ such that $|\frac{f(x)-f(x_0)}{x-x_0}-L|<\varepsilon$ as $|x-x_0|<\delta$.
Can you rearrange the above inequality and use triangle inequality so that the above inequality becomes $|f(x)-f(x_0)|<M|x-x_0|<M\delta$ for some constant $M$?
Then the proof is done. (How?)


text:
Q: Sharepoint Infopath plus one extra database I have the following setup:
Sharepoint 2010 with SQL Server and Office 2010.
This is the situation I have. Non programmers are supposed to create simple infopath forms. Admins then upload those to sharepoint, which will get served to users as simple webpages.
When a user submits the form it's fields are supposed to be stored in a separate SQL database, and after saving an email gets sent out to some address.
Whatever I try ends up with a situation that will not work.
Here are some of the problems I have had.
- Creating the Infopath form, from a database, prevents the fields to be stored in the database, because that is not supported from a webpage.
- Creating a normal form and uploading it to sharepoint, prevents me from getting access to the fields in the form, so that I could store them in a separate database. This is so because new completed forms get saved as documents in sharepoint, not as database rows.
- Using code in an infopath form, means that the form needs to deployed as sandboxed project, which prevents using it as webpage.
Any help on how to accomplish this would be appreciated.

A: Option 1: create a webservice on top of your database. You infopath form can send it's data to the webservice, the webservice can store the data in SQL server.
Option 2: save the forms to a forms library. Attach an eventhandler to that forms library that deserializes the XML and put the data in SQL server.


text:
Q: Add css to an ID in php I'm working in wordpress, and I am having a bit of trouble.
As you see: in the page "articles" managed with page.php, it shows the categories widget at this point (see image 1),

Then, inside the page "articles", if you click in any subpage, managed by single.php, the categories widget should appear in a different position.
(image 2 is where it should appear and image 3 where it appears). I'm using a plugin to be able to manage structures through the dashboard, so I need to do it inside a php file.
Image 2:

Image 3:

I'm trying to include:
  if ( is_page_template( 'single.php' ) ) {
                 echo '<style type=\"text/css\"> #sub_categories_widget-2 { margin-top: -150%; } </style>';

positioning it in my single.php or in my page.php but nothing seems to happen. Does anyone know what I'm doing so wrong? I make the widget appear though a plugin that creates a shortcode and I can add it in the editor.
Thank you

A: What you are doing can be achieved with css.
If you are in a single.php file, you should probably have a single class on your body or html tag. If not check this out.
So with this class at the top, now you can target your widget by page, single, page template etc...
.widget {
  margin-top:0;
}

 .single .widget {
   margin-top: 300px //or whatever the height of the image;
}

A: What you want to do can be simply done by Javascript.
in jQuery use this code.
$('#id_name').css('property_name','property_value');

if you want to add class on particular element you can use .addClass method
$('#id_name').addClass('class_name');

Good Luck!


text:
Q: Error("invalid type: map, expected a sequence", line: 1, column: 1),    Error("invalid type: map, expected a sequence", line: 1, column: 1),

    0{
    symbol  "ETHBTC"
    priceChange "0.00068700"
    priceChangePercent  "0.874"
    weightedAvgPrice    "0.07908580"
    prevClosePrice  "0.07864600"
    lastPrice   "0.07933400"
    lastQty "0.18460000"
    bidPrice    "0.07933400"
    bidQty  "4.49640000"
    askPrice    "0.07933500"
    askQty  "54.13430000"
    openPrice   "0.07864700"
    highPrice   "0.07945000"
    lowPrice    "0.07846100"
    volume  "56892.20330000"
    quoteVolume "4499.36548634"
    openTime    1662288072375
    closeTime   1662374472375
    firstId 369847410
    lastId  370015037
    count   167628
    }

My request function makes a cURL request and receives the above JSON. I then use serde_json to deserialize the JSON>. Please help in solving this issue
main.rs
use serde::Deserialize;
use std::error::Error;

#[derive(Deserialize, Debug)]
struct Peers {
    num: Vec<Peer>,
}

#[derive(Deserialize, Debug)]
struct Peer {
    symbol: String,
    count: u32,
}

fn get_node(url: &str) -> Result<Peer, Box<dyn Error>> {
    let response = ureq::get(url).call()?.into_string()?;
    let node: Peers = serde_json::from_str(&response)?;

    dbg!(node);
    todo!()
}

fn main() {
    let url = "https://api.binance.com/api/v1/ticker/24hr";
    let num = get_node(url);
    dbg!(num);
    todo!()
}

I'm getting  the following error message in my terminal
       num = Err(
            Error("invalid type: map, expected a sequence", line: 1, column: 1),
        )
        thread 'main' panicked at 'not yet implemented',
        note: run with `RUST_BACKTRACE=1` environment variable to display a

I'm certain I'm making a stupid mistake in deserializing my JSON structure, I've tried a number of permutations and combinations but I couldn't get anything to work. Please help me solving this issue in Rust

A: Your issue is that you're trying to deseralize the top level array ([{...}, {..}]) into a struct (Peers).
You noted in your struct that it should be a vec, which is the right thing to deserialize into, so you're close. All you need to do is change your:
let node : Peers = serde_json::from_str(&response)?;

into
let node : Vec<Peer> = serde_json::from_str(&response)?;

If you want to keep your Peers struct in the function, you could do something like:
let peers = Peers {
    num: serde_json::from_str(&response)?,
};

By the way ureq has a tool that will simplify your usage of serde_json.


text:
Q: How remove specific div code from html using java or jquery I want to remove the below 2 codes from my html on page load using java or jquery...
Important: I only want to remove these 2 lines - don't want to remove the content associated with it.

This is the link to my main code which has the above strings as well, view code on this link

A: You can use:
$("#mainpage, #left").remove();

Or
$("#mainpage").attr('style', '');
$("#left").attr('style', '');

Or
var htmlInMainPage = $("#mainpage").html().remove();
$('table').append(htmlInMainPage);

Or explain better your question.

A: If you know elements class or ID, you can use
display:none

If you know element order within the parent, for example third .btn
.btn-nth-of-type(3) {display:none}


text:
Q: Create Excel workbook in asp.net I need to generate an excel file for a user on the fl upon button click. I was using Netoffice before which worked fine for desktop applications.
But now I want to do the same thing with an asp.net app. This way my server code doesn't have an access to the client's copy of excel. What approach should I take?

A: Use EPPlus. It allows you to create Excel spreadsheets on the server. I've used it and it worked great. It supports advanced functions.
using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
    ws.Cells["A1"].LoadFromDataTable(tbl, true);

    //Format the header for column 1-3
    using (ExcelRange rng = ws.Cells["A1:C1"])
    {
        rng.Style.Font.Bold = true;
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;

        //Set Pattern for the background to Solid
        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));

        //Set color to dark blue
        rng.Style.Font.Color.SetColor(Color.White);
    }

    //Example how to Format Column 1 as numeric
    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
    {
        col.Style.Numberformat.Format = "#,##0.00";
        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
    }

    //Write it back to the client
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;  filename=file.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.End();
}

A: The most flexible and likely to do exactly what you need is going to take some work, but it's free -- and really works.  Use the toolkit to look at existing documents to see how to create the features you want.
Open XML 2.0 SDK

A: You can try simple HTML table (inlcude html, head, and body tags).
Just save it with XLS extension.

A: Netoffice requires MS Office on executing machine. Does your server has it?

A: You can use a DataGrid to create Excel files on the fly. It doesn't require Excel.
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
    HttpResponse response = HttpContext.Current.Response;

    // first let's clean up the response.object
    response.Clear();
    response.Charset = "";

    // set the response mime type for excel
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader(
        "Content-Disposition",
        "attachment;filename=\"" + filename + "\""
    );

   // create a string writer
   using (StringWriter sw = new StringWriter())
   {
       using (HtmlTextWriter htw = new HtmlTextWriter(sw))
       {
            // instantiate a datagrid
            DataGrid dg = new DataGrid();
            dg.DataSource = ds.Tables[0];
            dg.DataBind();
            dg.RenderControl(htw);
            response.Write(sw.ToString());
            dg.Dispose();
            ds.Dispose();
            response.End();
       }
    }
}


text:
Q: Limitar exibição de texto em PHP Quero limitar o tamanho de caracteres que aparecem, mas não estou conseguindo. Uso o:
<? echo $row["catname"] ?>

Ele pega um texto do phpMyAdmin e mostra, só que quero limitar a exibição de caracteres na página, como faço?

A: A solução mais universal é esta:
mb_substr ( string $str , int $start , [ int $length [, string $encoding ]] )

A função substr é limitada a encodings single byte, e vai ter problemas com strings com caracteres especiais em encodings como 'UTF-8' (para ISO ela funciona bem). Já a mb_substr conta por caracteres, e não bytes, sendo mais adequada para código portável.
Uso com ISO-8859-1:
echo mb_substr( 'Acentuação faz diferença', 4, 10, 'ISO-8859-1' );

Uso com UTF-8:
echo mb_substr( 'Acentuação faz diferença', 4, 10, 'UTF-8' );

Importante: o último parâmetro normalmente pode ser omitido, para casos em que a aplicação esteja globalmente configurada para usar um encoding específico (o que é desejável).
Mais detalhes no manual:

http://php.net/manual/pt_BR/function.mb-substr.php

Relacionadas:

Como mostrar somente "x" caracteres em uma div?

Nao consigo limitar texto com caracteres japoneses

A: Faça assim:
<?php
echo substr($row["catname"], 0, 20);//Apenas os primeiros 20 caracteres

A: Para casos em que se precise por um indicador que a string foi truncada,
há uma outra opção (que é quase desconhecida), que seria a função mb_strimwidth.
Parece que ela já foi feita para esse fim:
mb_strimwidth("Hello World", 0, 10, "...");

Resultado

"Hello W..."

Nesse caso, é preciso notar que você tem que adicionar o número do limitador somado ao número de caracteres que serão a indicação da limitação.
Por exemplo:
 mb_strimwidth("Oi mundo", 0, 5, "...")

Exibe:

"Oi..."

A: Pode usar o substr(), esta função tem 3 parâmetros.

substr(string, inicio, fim);

A string é o input que tem, o inicio é a posicao inicial e o fim é a posicao final.
No caso do segundo ou terceiro parametros: sendo negativo, ele conta posicoes a partir do fim. Se fôr positivo, conta a partir do inicio.
Exemplos:
echo substr("abcdef", 0, 2); // ab
echo substr("abcdef", 0, 4); // abcd
echo substr("abcdef", 0, -2); // abcd


text:
Q: Rigorously prove that electric field is zero in a perfect conductor I have ran into a problem while trying to prove that the electric field is zero in a perfect conductor
My argument went something like this:

We know that: $$\vec J = \sigma \vec E$$
In a perfect conductor $\sigma = \infty$
Therefore to maintain a constant current, $\vec E$ must be zero.

While this $\infty \times 0$ is a constant argument is not never seen before, I feel ike this can be made much rigorous.
Can someone help provide me with an argument why the electric field must be zero in a perfect conductor?

A: Suppose we impose a current density $\newcommand{\j}{\mathbf{J}}\j$, then the resulting electric field $\newcommand{\e}{\mathbf{E}}\e$ is given by $\e = \rho \j$, where $\rho$ is the resistivity. In a perfect conductor, $\rho=0$. So in a perfect conductor with some fixed current $\j$, the electric field satisfies $\e = \rho \j = 0 \j =  \mathbf{0}$. I don't know if this is any more satisfying, but it doesn't use infinity.

A: The electrical field $\mathbf{E}$ is an external field, which "drags" the conductor electrons through the conductor "lattice". The conductivity $\sigma$ describes the resistance of the "lattice". When the resistance is zero, a non zero current can exist in the conductor without necessity to support it with an external field.
If $\mathbf{E}$ is non zero, the current will be growing (or varying), just like a solution to $m\mathbf{a}=\mathbf{F}_{ext}$.

A:
Can someone help provide me with an argument why the electric field
  must be zero in a perfect conductor?

It's not clear exactly what you're looking for.  In a sense, any argument attempting to prove that the electric field must be zero in a perfect conductor will beg the question.
For example, here's an excerpt from "Electromagnetics for High-Speed Analog and Digital Communication Circuits":

We could in fact define a perfect conductor as a material with zero
  electric field inside the material.  This is an alternative way to
  define a perfect conductor without making any assumptions about
  conductivity.

From this starting point, one reasons that
(1) if there's an electric field inside, it's not a perfect conductor
(2) if the material has a finite conductivity and there is a steady current through, there is an electric field inside proportional to the current density
(3) thus, if the material has finite conductivity, it's not a perfect conductor
Again, it's not clear to me precisely what you're looking for.  If the above fails to address your question, please update and clarify your question.

A: Consider a metal sheet placed in a uniform electrical field normal to the sheet surface. The electrons will be "dragged" by the electrical field and form an excess of negative charges on one side of the metal sheet and an excess of positive charges on the other side of the metal sheet.
The excess charges produce an electrical field that cancels the applied field in the interior of the metal sheet.
The same consideration applies for a metallic half space.


text:
Q: Juggling multiple object instances This question is coded in pseudo-PHP, but I really don't mind what language I get answers in (except for Ruby :-P), as this is purely hypothetical. In fact, PHP is quite possibly the worst language to be doing this type of logic in. Unfortunately, I have never done this before, so I can't provide a real-world example. Therefore, hypothetical answers are completely acceptable.
Basically, I have lots of objects performing a task. For this example, let's say each object is a class that downloads a file from the Internet. Each object will be downloading a different file, and the downloads are run in parallel. Obviously, some objects may finish downloading before others. The actual grabbing of data may run in threads, but that is not relevant to this question.
So we can define the object as such:
class DownloaderObject() {
    var $url = '';
    var $downloading = false;

    function DownloaderObject($v){ // constructor
        $this->url = $v;
        start_downloading_in_the_background(url=$this->$url, callback=$this->finished);
        $this->downloading = true;
    }

    function finished() {
        save_the_data_somewhere();
        $this->downloading = false;
        $this->destroy(); // actually destroys the object
    }
}

Okay, so we have lots of these objects running:
$download1 = new DownloaderObject('http://somesite.com/latest_windows.iso');
$download2 = new DownloaderObject('http://somesite.com/kitchen_sink.iso');
$download3 = new DownloaderObject('http://somesite.com/heroes_part_1.rar');

And we can store them in an array:
$downloads = array($download1, $download2, $download3);

So we have an array full of the downloads:
array(
  1 => $download1,
  2 => $download2,
  3 => $download3
)

And we can iterate through them like this:
print('Here are the downloads that are running:');
foreach ($downloads as $d) {
    print($d->url . "\n");
}

Okay, now suppose download 2 finishes, and the object is destroyed. Now we should have two objects in the array:
array(
  1 => $download1,
  3 => $download3
)

But there is a hole in the array! Key #2 is being unused. Also, if I wanted to start a new download, it is unclear where to insert the download into the array. The following could work:
$i = 0;
while ($i < count($downloads) - 1) {
    if (!is_object($downloads[$i])) {
        $downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');
        break;
    }
    $i++;
}

However, that is terribly inefficient (and while $i++ loops are nooby). So, another approach is to keep a counter.
function add_download($url) {
    global $downloads;
    static $download_counter;

    $download_counter++;
    $downloads[$download_counter] = new DownloaderObject($url);
}

That would work, but we still get holes in the array:
array(
  1  => DownloaderObject,
  3  => DownloaderObject,
  7  => DownloaderObject,
  13 => DownloaderObject
)

That's ugly. However, is that acceptable? Should the array be "defragmented", i.e. the keys rearranged to eliminate blank spaces?
Or is there another programmatic structure I should be aware of? I want a structure that I can add stuff to, remove stuff from, refer to keys in a variable, iterate through, etc., that is not an array. Does such a thing exist?
I have been coding for years, but this question has bugged me for very many of those years, and I am still not aware of an answer. This may be obvious to some programmers, but is extremely non-trivial to me.

A: The problem with PHP's "associative arrays" is that they aren't arrays at all, they're Hashmaps. Having holes there is perfectly fine. You might look at a linked list, as well, but a Hashmap seems perfectly suited to what you're doing.

A: What is maintaining your array of downloaders?
If you encapsulate the array in a class that is notified by the downloader when it is finished you won't have to worry about stale references to destroyed objects.
This class can manage the organisation of the array internally and present an interface to its users that looks more like an iterator than an array.

A: "$i++ loops" are nooby, but only because the code becomes much clearer if you use a for loop:
$i = 0;
while ($i < count($downloads) - 1) {
    if (!is_object($downloads[$i])) {
       $downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');
        break;
    }
    $i++;
}

Becomes
for($i=0;$i<count($downloads)-1;++$i){
    if (!is_object($downloads[$i])) {
        $downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');
        break;
    }
}

A: Coming from a C# perspective, my first thought would be that you need a different data structure to an array - you need to think about the problem using a higher-level data structure. Perhaps a Queue, List or Stack would suit your purposes better?

A: The short answer to your question is that in PHP arrays are used for almost everything and you rarely end up using other data structures.  Having holes in your array indexes isn't anything to worry about.  In other programming languages such as Java you have a more diverse set of data structures to choose from: Sets, Hashes, Lists, Vectors and more.  It seems that you would also need to have a closer interaction between the Array and DownloaderObject class.  Just because the object $download2 has "destroyed()" itself the array will maintain a reference to that object.

A: Some good answers to this question, which reflect on the relative experience on the answerers. Thank you very much — they proved very educational.
I posted this question nearly three years ago. In hindsight, I can see my knowledge in that area was severely lacking. The biggest problem I had was that I was coming from a PHP perspective, which does not have the ability to arbitrarily pop elements. Something the other answers to this question helped me to discover was that a fundamentally superior model is 'linked lists'.
For C, I wrote a blog post about linked lists which contains code samples (too numerous to post here) but would neatly fill the original question's use case.
For PHP, a linked list implementation appears here, which I have never tried, but imagine it would also be the right way to deal with the above.
Interestingly, Python lists contain the pop() method which, unlike PHP's array_pop(), can pop arbitrary elements and keep everything in order. For example:
>>> x = ['baa', 'ram', 'ewe'] # our starting point
>>> x[1]                      # making sure element 1 is 'ram'
'ram'
>>> x.pop(1)                  # let's arbitrarily pop an element in the middle
'ram'
>>> x                         # the one we popped ('ram') is now gone
['baa', 'ewe']
>>> x[1]                      # and there are no holes: item 2 has become item 1
'ewe'


text:
Q: Cpp define in classes I started C++ programming few weaks ago and i have a question about defining the file of a class in a separate file. This is my code.
main.cpp
#include <iostream>
#include "Maths.h"
int main() {
  Maths m;
  int s = m.sum(1,2);
  std::cout << s << std::endl;
  return 0;
}

Maths.h
#ifndef Maths_H
#define Maths_H

class Maths
{
  public:
    int sum(int a, int b);
};

#endif

Maths.cpp
#include <iostream>
#include "Maths.h"
int Maths::sum(int a, int b)
{
  return a + b;
}

Why is it that you can't #define the same name as your class name. For example in my script Maths?
https://repl.it/repls/UnwillingFreeHeterodontosaurus

A: What you #define is called a macro, and the preprocessor replaces the macros with something.
For example, you define the macro Maths to be replaced by nothing, and that's what the preprocessor will do. The definition class Maths { ... } will be replaced by class   { ... }. Which is not valid.
Since preprocessor macros doesn't live in any specific namespace (they really handled separately from the actual C++ parser) they are global. And to avoid clashes in symbol names, macros are usually spelled with all upper-case letter. In your case you should use MATHS instead.

A: Macros have the compiler replace the text with a defined value. So if for instance you have this macro:
#define Math
It will replace all the "Math" occurences with nothing, since you didn't define a value to replace it. Defining it like:
#define Math 1
Will replace all occurences of "Math" with the value 1.
As for having to include the base class: The compiler has to know where to find the base class. If you don't include the header containing the base class, the header of the derived class has no way to know where to get the base class from, so it will give a Undefined reference to ... error.
You should also place the include guards above any other code. So not like this:
#include "Enemy.h"
#ifndef Ninja_H
#define Ninja_H
//...
#endif

But like this:
#ifndef Ninja_H
#define Ninja_H
#include "Enemy.h"
//...
#endif

The include guards are basically there to tell the compiler that it's already parsed that file. If you place code outside of the guards it will likely cause errors. Placing an include like that will disable certain optimisations, which in turn leads to longer compile time. Simply put: there is no benefit placing it like that.