text:
Q: Array of Widgets(TextView,RelativeLayout etc) causing Null Pointer Exception I am reposting this question as one person marked my previous queston duplicate even without reading the question.
I am creating a adapter of ListView, for loading my custom layout as list members.
The layout contains

*

*3 RelativeLayout

*and each of the latter contains a TextView

*and a Button.
In the ListView there will be at max 2 rows, in short at max 6 RelativeLayout. As the need is recursive I have used array of TextView,RelativeLayout,Button. For assigning Id through findViewById(), I am using int array which contains all ids defined in layout. Now after I assign the widgets their Id, when I am invoking any method it is giving null pointer exception, which mean that the widget is not assigned Id but I cannot understand why it is not assigned.
One more point that the ListView is populated within an RecyclerView.Adapter.
The whole scene is like this:
i) I have a activity with Tabs & Pager. Hence it uses fragments for each tab. Here I am talking about first tab only.
ii) In the fragment I have a RecyclerView which will load cards.
iii) The card has many widget, one of them is ListView. So In RecyclerView.Adapter I will call the ArrayAdapter for this List
My code is as follow:
1) ArrayAdapter (which shows error)
public class ElectionOptionAdapter extends ArrayAdapter<String> {

    Activity context;
    int noOption;
    String[] options, description;
    TextView[] optionText, optionDescription;
    RelativeLayout[] optionImage;
    Button[] optionButton;

    int[]
    text = new int[]{R.id.ERowOption1,R.id.ERowOption2,R.id.ERowOption3},
    des = new int[]{R.id.ERowOption1des,R.id.ERowOption2des,R.id.ERowOption3des},
    img = new int[]{R.id.ERowOption1Img,R.id.ERowOption2Img,R.id.ERowOption3Img},
    but = new int[]{R.id.ERowOption1button,R.id.ERowOption2button,R.id.ERowOption3button};
    public ElectionOptionAdapter(Activity context, int length, String[] options, String[] description) {

        super(context, R.layout.election_type_options,options);
        this.context = context;
        this.options = options;
        this.description = description;

        noOption=options.length;
        optionText = new TextView[noOption];
        optionDescription = new TextView[noOption];
        optionImage = new RelativeLayout[noOption];
        optionButton = new Button[noOption];

    }

    @Override
    public int getCount() {
        return 1;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = context.getLayoutInflater();
        View card = inflater.inflate(R.layout.election_type_options, parent, false);

        for (int i = 1+(3*position); i <= Math.min(3+(3*position),options.length); i++) {
            optionText[i-1] = (TextView) card.findViewById(text[(i%4)-1]);
            optionDescription[i-1] = (TextView) card.findViewById(des[(i%4)-1]);
            optionImage[i-1] = (RelativeLayout) card.findViewById(img[(i%4)-1]);
            optionButton[i-1] = (Button) card.findViewById(but[(i%4)-1]);

            //The error message points here
            optionImage[i-1].setVisibility(View.VISIBLE);
            optionText[i-1].setText(options[i-1]);
            optionDescription[i-1].setText(description[i-1]);
        }

        optionButton[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(0);
            }
        });
        optionButton[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(1);
            }
        });
        optionButton[2].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(2);
            }
        });
        optionButton[3].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(3);
            }
        });
        optionButton[4].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(4);
            }
        });
        optionButton[5].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visibilityChange(5);
            }
        });

        return card;
    }

    private void visibilityChange(int pos){
        if(optionDescription[pos].getVisibility()==View.VISIBLE)
            optionDescription[pos].setVisibility(View.INVISIBLE);
        else
            optionDescription[pos].setVisibility(View.VISIBLE);
    }

}

2) The Error Message:
       java.lang.NullPointerException:
    Attempt to invoke virtual method 'void android.widget.RelativeLayout.setVisibility(int)'
on a null object reference at com.package.ElectionOptionAdapter.getView(ElectionOptionAdapter.java:72)

3) The Layout File :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="5dp"
    android:paddingTop="5dp">

    <RelativeLayout
        android:tag="@+id/ERowOption1Img"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="4dp"
        android:visibility="invisible">

        <TextView
            android:tag="@+id/ERowOption1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="25dp"
            android:textStyle="bold"
            android:text=" A) Gaurav Jindal"
            android:layout_alignParentBottom="true" />
        <TextView
            android:background="#FFFFFF"
            android:tag="@+id/ERowOption1des"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"/>

        <Button
            android:tag="@+id/ERowOption1button"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:background="@drawable/info_election_option"/>
    </RelativeLayout>

    <RelativeLayout
        android:tag="@+id/ERowOption2Img"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="4dp"
        android:visibility="invisible">

        <TextView
            android:tag="@+id/ERowOption2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="25dp"
            android:textStyle="bold"
            android:text=" A) Gaurav Jindal"
            android:layout_alignParentBottom="true" />
        <TextView
            android:tag="@+id/ERowOption2des"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"/>

        <Button
            android:tag="@+id/ERowOption2button"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:background="@drawable/info_election_option"/>
    </RelativeLayout>

    <RelativeLayout
        android:tag="@+id/ERowOption3Img"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="4dp"
        android:visibility="invisible">

        <TextView
            android:tag="@+id/ERowOption3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="25dp"
            android:textStyle="bold"
            android:text=" A) Gaurav Jindal"
            android:layout_alignParentBottom="true" />
        <TextView
            android:tag="@+id/ERowOption3des"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"/>

        <Button
            android:tag="@+id/ERowOption3button"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:background="@drawable/info_election_option"/>
    </RelativeLayout>
</LinearLayout>

4) The RecyclerAdapter which calls ListAdapter mentioned above is:
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {

    JSONArray jsonArray;
    Activity context;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView userid,question;
        ImageView userdp;
        ListView optionList;

        public ViewHolder(View card) {
            super(card);
            userid = (TextView) card.findViewById(R.id.useridInCard);
            question = (TextView) card.findViewById(R.id.questionInCard);
            optionList = (ListView) card.findViewById(R.id.optionInCard);
        }
    }

    FeedAdapter(Activity context,JSONArray jsonArray){
        this.context=context;
        this.jsonArray = jsonArray;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ques_card,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return  viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        try {
            JSONObject currentFeed = jsonArray.getJSONObject(position);

            holder.userid.setText(currentFeed.getString("_id"));
            holder.question.setText(currentFeed.getString("Question"));
            int noOptions = currentFeed.getInt("noOption");
            String[] option = new String[noOptions];
            for(int i=1;i<=noOptions;i++)
                option[i-1]=optionName(i)+currentFeed.getString("Option"+i);

           String[] description = new String[noOptions];
           for(int i=1;i<=noOptions;i++)
               description[i-1]=currentFeed.getString("Description"+i);
           ElectionOptionAdapter electionAdapter;
                if(noOptions<=3)
                    electionAdapter= new ElectionOptionAdapter(context,1,option,description);
                else
                    electionAdapter= new ElectionOptionAdapter(context,2,option,description);

                holder.optionList.setAdapter(electionAdapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return 1;
    }
}

A: In the Layout's xml file you should be using the attribute
android:id="@+id/foobar"

instead of
android:tag="@+id/foobar"


text:
Q: UIActivityViewController Crash i have no idea why the uiactivityviewcontroller crash when i use the prensentViewController method.
it is weird, anyone has any clue?
the program is running fine not untile when i use the presenviewcontroller.
#import "ActivityViewController.h"

@interface ActivityViewController ()

@end

@implementation ActivityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self createTextField];
    [self createButton];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) createTextField
{
    self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(20.0f, 35.0f, 280.0f, 30.0f)];
    self.myTextField.translatesAutoresizingMaskIntoConstraints = NO;
    self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.myTextField.placeholder =@"Enter text to Share";
    self.myTextField.delegate = self;
    [self.view addSubview:self.myTextField];
}

- (void) createButton
{
    self.myButtonShare = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.myButtonShare.frame = CGRectMake(20.0f, 80.0f, 280.0f, 40.0f);
    self.myButtonShare.translatesAutoresizingMaskIntoConstraints = NO;

    [self.myButtonShare setTitle:@"Share" forState:UIControlStateNormal];
    [self.myButtonShare addTarget:self action:@selector(handleShare:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:self.myButtonShare];

}

- (void) handleShare:(id)sender
{

    NSArray *activities = @[UIActivityTypeMail,UIActivityTypeMessage];

    self.myActivityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[self.myTextField.text] applicationActivities:activities];

    [self presentViewController:self.myActivityViewController animated:YES completion:nil];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.myButtonShare resignFirstResponder];
    return YES;
}

A: What ccjensen said is all correct, except you can actually restrict your share sheet to just Mail & Message by excluding activities, this way for example:
activityController.excludedActivityTypes = @[ UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList ];

This would only show the email sharing by default.

A: The documentation for UIActivityViewController's initWithActivityItems:applicationActivities: states that the NSArray passed as the second parameter (applicationActivities) should be an "array of UIActivity". You are passing in an array containing the two objects UIActivityTypeMail and UIActivityTypeMessage which are of type NSString *const. It seems that you were hoping that you could restrict the share sheet to only show the mail and messages activity, which is currently not possible.
To stop the crash from happening, change your code to:
<...>
self.myActivityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[self.myTextField.text] applicationActivities:nil];
<...>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calendar specified week keeps resetting I have a function to return all dates for a specific week.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, week);
String[] dates = new String[7];
currentlySelectedYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
// i = 2 because MONDAY is day two in week
for (int i = 2; i < 9; i++) {
    cal.set(Calendar.DAY_OF_WEEK, i);
    //i-2 to start the array at index 0
    dates[i - 2] = sdf.format(cal.getTime());
}

it works fine on all devices except samsung where each time the for loop is entered again after the first iteration the WEEK_OF_YEAR field in the calendar is reset to current week instead of the week set three lines above.
Is this a known bug for samsung or am I missing something?
Is there another way to do the same thing that maybe work on all devices?


text:
Q: Model factory is misbehaving in laravel tests My laravel application is built on Laravel 8.12 and uses pest php for tests,
I have two tables groups and meetings and the their relation is one to many, where a meeting belongs to a group and group has many meetings,
I have a test case where I have to assert if a group can be created successful with it's meeting, the test case works well if I create only group without it's meeting but if I create the group with it's meeting using their relation the groups table contains two records of groups instead of one.
This is my test case when I create only group record
test('user see all meetings and registered groups successful', function () {

   Group::factory()->create();

    dd(Group::pluck('id'));

        actingWithPermission($this->user, $this->permission)
        ->get($this->route)
        ->assertViewHasAll([
            'totalRegistered' => 1,
            'totalMeetings' => 1,
        ]);
});

When I create the group record the groups table contains only one record as shown below
^ Illuminate\Support\Collection^ {#3995
  #items: array:1 [
    0 => 36
  ]
  #escapeWhenCastingToString: false
}

Test case when I create group and it's meeting record
test('user see all meetings and registered groups successful', function () {

   Group::factory()
   ->hasMeetings(1)
   ->create();

    dd(Group::pluck('id'));

        actingWithPermission($this->user, $this->permission)
        ->get($this->route)
        ->assertViewHasAll([
            'totalRegistered' => 1,
            'totalMeetings' => 1,
        ]);
});

When I dump the database contains two records of the groups instead of 1 as shown below:
^ Illuminate\Support\Collection^ {#1847
  #items: array:2 [
    0 => 36
    1 => 37
  ]
  #escapeWhenCastingToString: false
}

This is one to many relation ship between group and meetings
 public function meetings()
    {
        return $this->hasMany(Meeting::class);
    }

How can I fix this?


text:
Q: Operator= in Boost::Python If I have something like the following class
class Foo
{
private:
    int _bar;
public:
    Foo& operator=( const Foo& other )
    {
        _bar = other._bar;
        return *this;
    }
}

Is there an easy way to export that functionality to python using boost::python?  The documentation does not list and nice and easy
.def( self = self )

I am not an expert with python so I do not even know if this is necessary to be honest.  But I want this functionality in my python scripts, so I am posting the question just to make sure.
Edit:
here are the compiler errors when I do do .def( self = self )
.\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &,const A3 &)' : expects 5 arguments - 1 provided
        with
        [
            W=Foo
        ]
        depends\common\include\boost/python/class.hpp(265) : see declaration of 'boost::python::class_<W>::def'
        with
        [
            W=Foo
        ]
.\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &)' : expects 4 arguments - 1 provided
        with
        [
            W=Foo
        ]
        depends\common\include\boost/python/class.hpp(249) : see declaration of 'boost::python::class_<W>::def'
        with
        [
            W=Foo
        ]
.\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,A1,const A2 &)' : expects 3 arguments - 1 provided
        with
        [
            W=Foo
        ]
        depends\common\include\boost/python/class.hpp(242) : see declaration of 'boost::python::class_<W>::def'
        with
        [
            W=Foo
        ]
.\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,F)' : expects 2 arguments - 1 provided
        with
        [
            W=Foo
        ]
        depends\common\include\boost/python/class.hpp(233) : see declaration of 'boost::python::class_<W>::def'
        with
        [
            W=Foo
        ]
.\src\Python.cpp(12) : error C2784: 'boost::python::class_<W> &boost::python::class_<W>::def(const boost::python::def_visitor<Derived> &)' : could not deduce template argument for 'const boost::python::def_visitor<Derived> &' from 'boost::python::self_ns::self_t'
        with
        [
            W=Foo
        ]
        depends\common\include\boost/python/class.hpp(223) : see declaration of 'boost::python::class_<W>::def'
        with
        [
            W=Foo
        ]

A: I'm not an expert with Python, but in python the affectation with operator "=" has not the same meaning as in C++: a=b creates a new reference to the same internal object, so there is no point in exporting c++'s operator= into python interface.
What you may do is creating a "clone" member function (implemented in terms of operator=) that will return a duplicate of the object. And import this function into Python.
Alternatively, in Python, you can use a copy constructor: foo2 = Foo(foo1) (of course this constructor must be defined in the c++/python interface)

A: You should not need to expose your assignment operator to python. In python, the assignment operator doesn't re-assign an existing object as a copy of another one, it re-assigns the name to a different object. In python, you are either creating a new object, or create a new object that is a copy of another one, which is more akin to a copy constructor.
If for some reason you need to invoke the C++ assignment operator from python, you can probably (haven't tried it myself) add a member function to do that like this:
.def("reassign", &Foo::operator=);

You would then invoke it manually in python:
f1 = Foo()
f2 = Foo()
f2.reassign(f1)

A: The previous answer using Foo::operator= directly does not work. Do this instead:
void assignFoo(Foo& self, const Foo& other)
{
    self = other;
}

class_<Foo>("Foo")
    .def("assign", assignFoo);

Usage in python:
foo, other = Foo(), Foo()
foo.assign(other)


text:
Q: How to scale Kafka Stream application I am little bit confused about the wording about this subject in kafka documentation, so I want to ask here that I am interpreting the things correctly here or not?
So if I understand this correctly only way to scale a Kafka Stream application is to start a new instance of the application (or increase the number of stream threads in application ), this will insure that there will be more consumers under consumerGroup('application.id'), so I can scale my stream application up to number of partitions of the topic (actually what happens if my Stream Topology connected to several topics, lets say TopicA with 5 partition and topicB with 3 I joined the streams for TopicA and TopicB, I am guessing I can scale up to 3 instances/threads in this case).
Now lets say I have a topicA with 5 partitions and I started 3 instances of my application and if I configured KTable in my topology, every KTable will contain information from certain partition and I have to find out over Metadata on which instance(partition) my Key is, so what happens when I start a 4th instance, lets say the Key/Value that was KTable on instance3 can now go to KTable on instance4, isn't it? One side question how long will such rebalancing can be (I think it depends on Topic size, so let's say it will took 1 minute, will my application who is querying KTable will be unresponsive during this operation?)
A side question, will this mechanism works exactly same for 'streamBuilder.table(..)' and 'streambuilder.groupByKey(..).reduce(..)''?
And one final question, again a Topic with 5 partitions but instead of starting 3 instances of the application, I started one instance with 3 stream threads (num.stream.threads = 3) will I have again 3 KTable's representing 5 partitions, will it behave exactly the same as increasing the instances number if I change thread size 3 to 4.
Thx for answers..

A:
lets say TopicA with 5 partition and topicB with 3 I joined the
  streams for TopicA and TopicB, I am guessing I can scale up to 3
  instances/threads in this case).

First of all, in order to join two topics, they should have same number of partitions. That's the key requirement for joining. If you have Topic A with 5 and Topic B with 3 partition, it will never perform join. (https://docs.confluent.io/current/streams/developer-guide/dsl-api.html#join-co-partitioning-requirements)

what happens when I start a 4th instance,

Yes, Kafka streams will rebalance the workload across the instances based on the number of partitions. It will reassign the partitions and their tasks including the local state stores. Time depends on the topic size. If there is an end user querying ktable, you should prefer collecting metadata from all instances and perform look up.

will this mechanism works exactly same for 'streamBuilder.table(..)'
  and 'streambuilder.groupByKey(..).reduce(..)''?

Yeah, the same mechanism is followed whenever a ktable is created using any transformation.

again a Topic with 5 partitions but instead of starting 3 instances of
  the application, I started one instance with 3 stream threads
  (num.stream.threads = 3) will I have again 3 KTable's representing 5
  partitions, will it behave exactly the same as increasing the
  instances number if I change thread size 3 to 4.

By default, Kafka Streams will break the topology into 5 tasks(=number of partitions).If the num.stream.threads is set to 3, those tasks will be distributed across the specified threads. Hence thread-1 can run 2 tasks, thread-2 can run next 2 tasks and thread-3 can run 1 task.
KTable state will be partitioned into 5 shards(=number of partitions) and one shard will map to one task. Hence each task will create a local store excluding to the itself. These Local store contains data of the corresponding shard. Despite of number of thread, you will get local-store equals to number of partitions.
Example :

After adding one more instance


text:
Q: Scrape product details from samsclub.com I'm scraping data from SamsClub.com using PHP
    $res = file_get_contents('http://www.samsclub.com/sams/bath-towel-apple-gr-100-cotton/prod10450797.ip');

I have create function using PHP explode to fetch data.
function getData($content,$start,$end){
    $str = explode($start,$content);
    $str = explode($end,$str[1]);
    return $str[0];
}

All required data fetched successfully but only one thing is remaining. That is variations of product mean other colors as u can see in snapshot, there are different colors available.

When we select an other color the item # & Model # of product also changed as shown in following snapshot

I just want to also fetch information like "item # & model #" of other colors too.
Waiting for your great response guys.

A: to do this you will need to use a library (PHP Simple HTML DOM Parser). Just upload simple_html_dom.php somewhere were you are able to include it (in my code, it's in the same folder).
<?php

$url = 'http://www.samsclub.com/sams/bath-towel-apple-gr-100-cotton/prod10450797.ip';

include('simple_html_dom.php');

$html = file_get_html($url);
$colour = array(); $item = array(); $model = array();
$script = $html->find('div[id=variance] script', 0)->innertext;
$script = preg_replace('/\s+/', ' ', $script);
$scripts = explode (";", $script);

$script = $scripts[2];
$id = $scripts[4];
$type = $scripts[5];

$script = str_replace("skuJson.skuVariantJson = $.parseJSON('", "", $script);
$script = str_replace("')", "", $script);

$colours = json_decode($script);

preg_match("/'([a-z0-9]*)'/", $type, $types); $type = $types[1];
preg_match("/'([a-z0-9]*)'/", $id, $ids);     $id   = $ids[1];

$script = $html->find('script', -1)->innertext;
$scripts = explode (";", $script);

$time = $scripts[0];
preg_match('/"([0-9]*)"/', $time, $times);    $time   = $times[1];

foreach ($colours as $key => $value) {
    $url = 'http://www.samsclub.com/sams/shop/product/ajax/ajaxSkuVariant.jsp?skuId='. $value .'&productId='. $id .'&productType='. $type .'&_='. $time;
    $html = file_get_html($url);
    preg_match('/"legacyItemNumber":"([0-9]*)"/', $html, $match); $item[] = $match[1];
    preg_match('/"model":"([a-z-]*)"/i', $html, $match); $model[] = $match[1];
    $colour[] = substr($key, 0, -1);
}

//Print results
echo "
"; print_r($colour); echo "
";
echo "
"; print_r($item);   echo "
";
echo "
"; print_r($model);  echo "
";

?>

The only thing you need to change is the $url variable at the beginning. Why all this code, you may ask ... because the data you are looking for isn't on the same page and it's called via ajax every time you click on a colour, so basically we are making a lot of requests (one for each color). This is the output:
Array
(
    [0] => White
    [1] => Burgundy
    [2] => Apple Green
    [3] => Lilac
    [4] => Chocolate
    [5] => Sage
    [6] => Grey
    [7] => PckBlue
    [8] => Linen
    [9] => null
    [10] => Plum
    [11] => Clay
    [12] => Light Blue
)

Array
(
    [0] => 252368
    [1] => 252505
    [2] => 252414
    [3] => 433076
    [4] => 252389
    [5] => 117268
    [6] => 252438
    [7] => 613317
    [8] => 252382
    [9] => 433083
    [10] => 252541
    [11] => 117175
    [12] => 252400
)

Array
(
    [0] => SAMW-B
    [1] => SAMB-B
    [2] => SAMA-B
    [3] => SAMLC-B
    [4] => SAMCH-B
    [5] => SAMSS-B
    [6] => SAMGR-B
    [7] => SAMPB-B
    [8] => SAMLI-B
    [9] => SAMDR-B
    [10] => SAMP-B
    [11] => SAMTC-B
    [12] => SAMLB-B
)

A: I would recommend scraping using .NET and Browser Class. This way you can make the bot click on each color and then grab the required value.


text:
Q: Rolles theorem word problem - find the c - double checking my answer Problem:
Find the relationship of $a$ and $b$ so that Rolles theorem applies for the function $f(x) = ax^2 + b(\ln x)$ on $[1,e]$. Find the value of $c$ for which it is verified.
Answer:
the relationship between $a$ and $b$ is $b = a(1 - e^2)$
the value of $c$ is $c = \pm\frac 1 2\sqrt{e^2 - 1})$
I would like to double check my answer on this problem
Any feedback would be appreciated.
Thank you

A: Since $f(1)=a$ and $f(e)=ae^2+b$, one condition is $f(1)=f(e)$, so $b=a(1-e^2)$.
The function is indeed differentiable on $[1,e]$, so for $b=a(1-e^2)$, Rolle's theorem applies.
Since
$$
f'(x)=2ax+\frac{a(1-e^2)}{x}
$$
you just need to find $x\in(1,e)$ such that $2ax^2+a(1-e^2)=0$.
If $a=0$, there is obviously no problem. If $a\ne0$…


text:
Q: Unexpected Token : (colon) in Typescript file I am new to TypeScript. I m getting some error while runing a simple TypeScript program.
When using any form of "variable: type; " in my TypeScript code.
I m getting Syntax error about an unexpected token ':' while running the file.
For eg :
File - main.ts
class Greeter {
    greeting: string;
    greet() {
        return "Hello, " + this.greeting;
    }
}
let greeter = new Greeter("World");

I m able to compile the file but at time of running, getting following error :
SyntaxError: Unexpected token :
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)

The expected output should be :
Hello World
Can anyone please let me know what i m missing here ?
Thanks.

A: Given your code, what I encounter is that:
 1. greeting should be initialised
 greeting: string = '';
 2. Greeter does not require a parameter.
 Add a constructor.
class Greeter {
  greeting: string = '';
  constructor(message: string) {
    this.greeting = message;
  }
}

You can remove the initialisation of the greeting if you added the constructor (given the example above.
I am using typescript v3.4.2 and tsc v1.20150623.0
Already answered by Vivek See comments above.


text:
Q: Continous data replication between two databases(same RDS instance) in AWS RDS We have multiple databases in a single RDS instance. Forex A, B, C
A and B DB contains the plans table. But some of the fields will be missing under the plans table in B DB.
What is the smart way to keep these tables in sync(like continuous replication)?
I check AWS DMS When I created a source point using the RDS instance for A DB. It gets successfully created.
But when I tried to create a target endpoint for the same RDS instance with a different DB. It is throwing this error.
SYSTEM ERROR MESSAGE:ReplicationEndpoint "database-1" already in use with endpoint ARN "arn:aws:dms:ap-southeast-1:59351853185:endpoint:VLRTOQM7LBW5M7YUKPOENBTFDUC32N7B5737I"

Am I looking into the right tool or is there any other tool available for this scenario?
Any insight on how to achieve this will be greatly appreciated. Thanks


text:
Q: explorer on Google Chart does not work - Polymer I'm using the google-chart web components but the explorer (that allow zooming in and out) does not work. Here is the code :

options: {
    type:Array,
    value:{
        title: 'Today Consumption',
        curveType: 'function',

        chartArea:{
            backgroundColor: '#E2E8ED',
            height: 300,
            width: 650,
        },
        explorer: {
            axis: 'horizontal',
            keepInBounds: true,
            maxZoomIn: 4.0
        },
        height: 400,
        width: 830,
        backgroundColor:'#E2E8ED',
        colors:["#4882A8"]}
    }
},
<google-chart type="line" options='{{options}}' data='{{chartData}}'></google-chart>

It looks like that :

But I'm unable to zoom in or out..? Does someone have an idea of why it doesn't work?

A: explorer only works with continuous axes (such as numbers, dates or timeofday)
for the x-axis, use type --> 'timeofday'
which should be an array with 3-4 elements...
[hour, min, second]
[hour, min, second, milli]

the following should convert your string values to a valid 'timeofday'
var timeStr = '2h19m';
var hour = timeStr.split('h');
var min = hour[1].split('m');
var timeArr = [parseInt(hour[0]), parseInt(min[0]), 0];


text:
Q: Reusable function type I'm trying declare a function type and then use that in a class, and in objects, and interfaces like this:
declare function IUpdateMode(mode: Mode): void;

Then I want to use it like this:
type Foo = {
   updateMode: IUpdateMode
}

class Foo extends React.Component<any> {

    updateRedMode(mode): IUpdateMode {}

}

function updateGreenMode(mode): IUpdateMode {

}

Is this possible in typescript?

A: I think what you really want is just this:
type UpdateMode = (mode: Mode) => void

Now you can use it anywhere as you mentioned, but with some corrections:
interface IFoo { // interface instead of a type is preferable when possible (e.g. you may extend it)
   updateMode: UpdateMode
}

class Foo extends React.Component<any> implements IFoo {

    updateMode = (mode: Mode) => {}

}

const updateGreenMode: UpdateMode = (mode) => { // there is no way to restrict a classic function to type alias or interface

}


text:
Q: Repast - PropertyGreaterThanEquals/PropertyLessThanEquals cause slow running speed I found that using the query methods "PropertyGreaterThanEquals" or "PropertyLessThanEquals" runs very much slower than using the method "PropertyEquals". below is a simple example about query a suitable dock for truck to unload goods.
    public void match_dock() {

//      Query<Object> pre_fit = new PropertyGreaterThanEquals(context,  "unload_speed", 240);
//      Query<Object> pre_fit = new PropertyLessThanEquals(context,  "unload_speed", 240);
        Query<Object> pre_fit = new PropertyEquals(context,  "unload_speed", 240);

        for (Object o : pre_fit.query()) {
            if (o instanceof Dock) {
            System.out.println("this dock's id is: " + ((Dock)o).getId());
            }
        }
}

There are only 3 docks. it took me less than one second to run total of 1920 ticks if using "PropertyEquals"; however, it took me more than 1 minute to run total of 1920 ticks if choosing the query methods "PropertyGreaterThanEquals" or "PropertyLessThanEquals". what's the underlying cause of this slow execution problem?


text:
Q: Generating functions homework question 3 This is a Homework question
Determine the Closed Form generating function for the sequence $a_0,a_1,a_2...,$ where $a_n$ is the number of partitions of the non negative integer n into
a) even summands
b)distinct odd summands
c) summands that do not exceed 10 and occurs at most $3$ times
d) summands where $1$ occurs at most once, summand $2$ occurs at most twice, and in general summand $k$ occurs at most $k$ times.
I am not looking for complete answer but perhaps a hint or some help on how to set it atleast one of these up.

A: Hints:

*

*a) In general, the closed form generating function for the partitions of a non-negative integer $n$ is given by $F(x) = (1+x+x^{2}+\cdots)(1+x^{2}+x^{4}+x^{6}+\cdots)(1+x^{3}+x^{6}+\cdots)\cdots$. (Can you see why this is?) Now, if we want to restrict this to even summands, we note that if we were to restrict $F(x)$ to include only parenthetical polynomials which contained terms of even degree, then we would restrict the corresponding sequence in $a_{n}$ to those with non-zero entries only for even indices, hence limiting the partition to even (not necessarily distinct) integers. Thus, the generating function $K(x)$ corresponding to a partition of $n$ into even summands is given by $K(x) = (1+x^{2}+x^{4}+x^{6}+\cdots)(1+x^{4}+x^{8}+\cdots)\cdots$.

*b) By the same reasoning as above, the generating function for partitioning $n$ into non necessarily distinct odd summands is $Q(x) = (1+x+x^{2}+\cdots)(1+x^{3}+x^{6}+\cdots)(1+x^{5}+x^{10}+\cdots)\cdots$. To make this distinct, we note that if we were
to restrict each parenthetical polynomial in the product to just its first two terms, we would restrict the corresponding sequence in $a_{n}$ to entries of just $0$ or $1$, hence limiting each partition to distinct integers. Thus, the generating function $N(x)$ is: $N(x) = (1 + x)(1 + x^3)(1 + x^5)\cdots$.
Can you use these suggestions to solve the other two?


text:
Q: Difference between versionName and versionNumber in Android Do the versionName and versionNumber have to be changed if a minor change is made in an Android Application or is it sufficient to change just one?
What is the difference between the two?

A: You don't need to change anything, but code looks nicer when you do it :)
versionName is only for user purpose, they can see it, and it need to be a string
versionCode is an integer and it's to determine which version is more recent. As long as it will be rising everything will be OK ;)
Reference Link

A: Setting Application Version
To define the version information for your application, you set attributes in the application's manifest file. Two attributes are available, and you should always define values for both of them:
* android:versionCode — An integer value that represents the version of the application
  code, relative to other versions.

The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative.
Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.
* android:versionName — A string value that represents the release version of the
  application code, as it should be shown to users.

The value is a string so that you can describe the application version as a .. string, or as any other type of absolute or relative version identifier.
As with android:versionCode, the system does not use this value for any internal purpose, other than to enable applications to display it to users. Publishing services may also extract the android:versionName value for display to users.
This link contains more information and the following example:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.package.name"
      android:versionCode="2"
      android:versionName="1.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        ...
    </application>
</manifest>

A: Android App Manifest documentation:
android:versionCode

An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. [...]

android:versionName

The version number shown to users. This attribute can be set as a raw string or as a reference to a string resource. The string has no other purpose than to be displayed to users. The versionCode attribute holds the significant version number used internally.


text:
Q: JPA Join table with SELECT I have a SQL query like this:
SELECT h.name, h.created_date,  tbl.*
FROM my_table tbl
  LEFT JOIN
  (SELECT name, max(created_date) created_date FROM my_table GROUP BY name) h
  ON tbl.name = h.name;

It returns the row from my_table (which has multiple for name="") along with the maximum created_date for that name.
Is there a way to replicate this in a JPQL query?
Here is the gist of the Entity class, it's quite simple:
@Entity
@Table(name = "MY_TABLE")
@XmlRootElement
public class MyTable implements Serializable {

  private BigDecimal tableId;
  private String name;
  private Date createdDate;

  // ...

  @Id
  @Basic(optional = false)
  @Column(name = "TABLE_ID")
  @GeneratedValue(generator = "TBL_ID_SEQ")
  public BigDecimal getTableId() {
    return tableId;
  }

  @Basic(optional = false)
  @Column(name = "NAME")
  public String getName() {
    return name;
  }

  @Basic(optional = false)
  @Column(name = "CREATED_DATE", insertable = false)
  @Temporal(TemporalType.TIMESTAMP)
  public Date getCreatedDate() {
    return createdDate;
  }

  // ... getters/setters

}

A: Just reading your question I guess you do not need another entity. Entities in JPA are the same like tables in SQL. Usually there is a 1:1 relationship between entities and tables. You just have to know how to invoke a query using JPQ. You need a entity manager, which invokes your statement.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit");
EntityManager em = emf.createEntityManager();

You have to define your persistence unit, i.e. in a pom file, or a config java file. So done you can go on coding something like this:
Query q = em.createQuery( "Your query in sql syntax as a string object" );

In respect to your entities and invoked query you will receive a List using
List<object> resultOfMyQuery = q.getResultList();
This is only one short example. But hopefully you got some buzzwords to look for ;)


text:
Q: TAPI in ASP.NET webpage I am currently working on a project where I need to implement some sort of telephony services in a webpage. The project is written on VB.net and postback is disabled since clients dont want the page to be reloaded every time something happens. Server architecture is Windows 2012 R2 X64. Cant give you exact model of the modem but its normally USB/Serial data modems.
I have been reading articles/blogs on TAPI for the last few days. Many people have said it is impossible to integrate TAPI in a webpage but on Julmar.com i found a sample. (http://julmar.com/blog/programming/utilizing-tapi-from-an-asp-net-application/)
Now my questions are:

*

*If above code works (which i havent tried yet) then how can i get incoming caller id without refreshing the page (possibly using jquery or some sort of script/activex)?

*There will be only one modem connected to the network (possibly with the server PC) so is it possible to control the modem (including capturing caller id) from the client pcs?

I am going to share my own thinking so that you can suggest me if theres anything better. Since the project has already using SignalR so I can make a winform application to capture caller id and pass it to the connected clients through SignalR. But is it possible/wise to make and receive call via signalr?
Appreciate any help and should you require further information, please feel free to ask.
Thanks a lot.

A: I have done 2 TAPI projects so far.
Your question is hard because it's not really a specific question. However I have made a similar service in VB.NET.
I'm now working on a service also.
Try looking into events like:
MyTAPI.TE_CALLSTATE
MyTAPI.TE_CALLNOTIFICATION
A nice example:
https://www.codeproject.com/Tips/636769/VB-NET-ITAPI-TAPI-Incoming-call-and-caller-ID
No idea why you need modem stuff.


text:
Q: Without using pandas I need to remove certain characters from my list output I want to print the date on the left in date order with the amount to the right, however with my current code it includes the special characters and datetime.date with the output. My desired output is:
dd/mm/yyyy   'amount'
however current output is as below:
[datetime.date(2016, 6, 22), ' 52.52']
[datetime.date(2016, 10, 2), ' 65.75']
[datetime.date(2016, 11, 1), ' 15.00']
[datetime.date(2016, 11, 3), ' 25.00']
[datetime.date(2016, 11, 3), ' 25.00']
Can anyone help me to remove the special characters and datetime.date, it is for an assignment so I cannot use pandas. Thanks for the help in advance.
import csv
from datetime import datetime, date

def betdate():
    data = [[*i[:2], datetime.strftime(*map(int, i[2:5])), *i[5:]] for i in
csv.reader(open('results.csv'))]
    result = sorted(data, key=lambda x:x[2])
    new_data = [i[2:-1] for i in result]

    print('\n'.join(map(str, new_data)))

betdate()


text:
Q: What is wrong with this CFIF structure? I have the following at the top of a page...
<cfif isdefined("session.loggedin") and session.loggedin eq true>

    <cfinclude template="includeUserInfo.cfm">

    <cfinclude template="includeSideBar.cfm">

<cfelse>

    <cflocation url="../sign-in.cfm">

</cfif>

When I execute the page and session.loggedin DOES equal true it executes as expected and adds the included files.
If I hit the page without logging in - I'm not being redirected to the sign in page - I'm just getting a completely blank page - zero html in the view source.
Session management is enabled in my application.cfc file
I'm not sure if what I am doing is wrong - appreciate any advice.

A: OK - so (as is often the case) I had missed the underlying cause of the problem - and while focussing on the imagined problem with the CFIF statement itself, missed the small cfinvoke that was before it in the code. That was trying to execute a database lookup, but failing when a user was not logged in.
swapping these around and making sure the block above is before everything else on the page has done the trick. Go me. Thanks everyone for the input.


text:
Q: Is it possible to dynamically create and execute a java file in android. I was wanting to create a android application where I could quickly write basic java code and get it to output in a TextView.  I originally got this idea up and running messing around in intellij and thought it would be a cool app so I started building it in android studio. What I was planning to do was create a 'dummy' java file, parse my code into the file, then execute the file. That way java would do all of the heavy lifting.
I am a student so I want this app as a way to practice writing sorting algorithms/recursive functions... basically the stuff they ask you to program in job interviews. I should also mention that this is research for my final school project.
Here is what I have already tried to do.
I have added permission in my manifest
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/ >

and this is how I am trying to create the file.
String FILENAME = "Interpreter.java";
String string = "hello world!";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}catch(Exception e){

}

I do not know where the file is being created if at all...
Am i going in the right direction?  does anyone know if this is even possible in android?
Thank you in advance!


text:
Q: All possible combinations of a,b,c,d (lenght 4) with conditions (java) So I need this algorithm to work but I can't seem to find where the problem is... I need to print all the possible combinaison of [a,b,c,d] (with a lenght of 4) with some condition (already in the algorithm). So what am I missing ? I'm still a begginer in Java, so thanks a lot for your help !
public class Test {

//Method saying that 'a' always have to follow 'b'
public static boolean aFollowsB(String s) {
      char[] set1 = s.toCharArray();

      for (int i = 0; i < set1.length; i++) {
        // If B is the last char, A can't possilby follow
        if (i == set1.length - 1) {
          if (set1[i] == 'b') { return false; }
        // Else if we encounter B, make sure next is an A
        } else {
          if (set1[i] == 'b') {
            if (set1[i+1] != 'a') { return false; }
          }
        }
      }

      return true;
    }

//Method saying that we can't have 'a' and 'd' in the same string
    public static boolean hasOnlyAOrD(String s) {
      char[] set1 = s.toCharArray();

      boolean hasA = false;
      boolean hasD = false;

      for (int i = 0; i < set1.length; i++) {
        if (set1[i] == 'a') {
          hasA = true;
        } else if (set1[i] == 'd') {
          hasD = true;
        }
      }

      if (hasA && hasD) {
        return false;
      }

      return true;
    }

//Method printAllKLength to print all possible strings of k lenght
    static void printAllKLength(char[] set, int k) {
        int n = set.length;
        printAllKLengthRec(set, "", n, k);
    }

    static void printAllKLengthRec (char[] set,
                                   String prefix,
                                   int n, int k)
    {

        if (k == 0)  {
            System.out.println(prefix);
              System.out.println(prefix);
            return;

        }
        for (int i = 0; i < n; ++i) {
            String newPrefix = prefix + set[i];
            printAllKLengthRec(set, newPrefix,
                                    n, k - 1);
        }
    }
    //Method to print with the conditions
    public static void main(String[] args) {
        char[] set1 = {'a', 'b', 'c', 'd'};
        int k = 4;
        if (aFollowsB(set1) && hasOnlyAOrD(prefix)) {
            printAllKLength(set1, k);
            }

}}
EDIT
Ok, so thanks to some help, I changed my code to a way more simple one, but now instead of giving me an error, it gives me nothing. I don't know what's missing.
Here's the new code :
//// Méthode principale printAllKLength pour imprimer tous les strings possible de longueur k

static void printAllKLength(char[] set, int k) {
    int n = set.length;
    printAllKLengthRec(set, "", n, k);
}

static void printAllKLengthRec (char[] set,
                               String prefix,
                               int n, int k)

{    if (k == 0)  {
    if  (aFollowsB(prefix) && hasOnlyAOrD(prefix) == true ) {
        System.out.println(prefix);
        return;

    }
    for (int i = 0; i < n; ++i) {
        String newPrefix = prefix + set[i];
        printAllKLengthRec(set, newPrefix,
                                n, k - 1);
    } }}

//Création de la méthode permettant de dire que 'a' doit toujours suivre 'b'

public static boolean aFollowsB(String str) {
    return str.indexOf('a') > str.indexOf('b');
}

    //Création de la méthode permettant de dire qu'on ne peut avoir 'a' et 'd' dans la même string
public static boolean hasOnlyAOrD(String str) {
    return str.indexOf('a') == -1 || str.indexOf('d') == -1;
}

//Création de la méthode principale

    public static void main(String[] args) {
    char[] set1 = {'a', 'b', 'c', 'd'};
    int k = 4;
    printAllKLength(set1, k);

}}

A: First, fix printAllKLengthRec:
Don't print everything twice (so remove one of the system.out's):
static void printAllKLengthRec(char[] set, String prefix, int n, int k) {
    if (k == 0) {
        System.out.println(prefix);
        return;
    }
    ...

Then, call aFollowsB for each result (not in the main method where it is only called once):
static void printAllKLengthRec(char[] set, String prefix, int n, int k) {
    if (k == 0) {
        if (aFollowsB(prefix)) {
            System.out.println(prefix);
        }
        return;
    }
    ...

public static void main(String[] args) {
    char[] set1 = { 'a', 'b', 'c', 'd' };
    int k = 4;
    printAllKLength(set1, k);
}

This means aFollowsB will take a String argument, and maybe look like this:
public static boolean aFollowsB(String str) {
    return str.indexOf('a') > str.indexOf('b');
}

Finally, do the same thing for hasOnlyAOrD (might wanna rename that method)
public static boolean hasOnlyAOrD(String str) {
    return str.indexOf('a') == -1 || str.indexOf('d') == -1;
}

static void printAllKLengthRec(char[] set, String prefix, int n, int k) {
    if (k == 0) {
        if (aFollowsB(prefix) && hasOnlyAOrD(prefix)) {
            System.out.println(prefix);
        }
        return;
    }
    ...

Then consider using the 'public' and 'static' keywords a lot less. But I guess that is out of scope for your assignment.


text:
Q: spring security doesn't load the resources (images, css) I'm new to spring security, and I try to implement an athorisation in my project. Everything work's fine, but the images and css files are not loaded. I'm using the (annotations) way to configure it.
Here is my project structure:

The configuration of resource mapping in dispatcher spring-web-servlet:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

My web.xml
<servlet>
    <servlet-name>spring-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
    <servlet-name>spring-web</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/errors/error404.jsp</location>
</error-page>

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

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Spring Security configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    PersistentTokenRepository tokenRepository;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()

            .antMatchers("/").permitAll()
            .antMatchers("/resources/**").permitAll() .anyRequest().permitAll()
            .antMatchers("/*.css","/*.jpg").permitAll().anyRequest().permitAll()
            .antMatchers("/css/**", "/js/**","/img/**", "/webjars/**", "**/favicon.ico", "/index").permitAll().anyRequest().permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
            .antMatchers("/users/**").access("hasRole('ROLE_USER')")
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username").passwordParameter("password")
            .loginProcessingUrl("/j_spring_security_check")
            .defaultSuccessUrl("/users/users_page")
                .and()
            .logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login?logout")
                .and()
            .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository).tokenValiditySeconds(86400)
                .and()
            .csrf().disable();

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            return encoder;
    }

    @Bean
    public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
        PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
                "remember-me", userDetailsService, tokenRepository);
        return tokenBasedservice;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/*.css");
        web.ignoring().antMatchers("/*.jpg");
    }
}

I'm trying to load the css file like this:
 <link rel="stylesheet" type="text/css"
       href="<c:url value="${pageContext.request.contextPath}/resources/static/css/test_style.css"/>"

and the images like this:
<img src="<c:url value='/resources/static/img/head.jpg' />" type="image/jpg"  alt="BigLogo" height="650"  width="1000"/>

As a result, the images are not displayed, and the css files are getting error:
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

What am I doing wrong?
Are there some configuration problems?
I searched a lot, but I didn't find some solutions that can help me.
I will be very thankful for your help.

A: In Spring boot add image folder in /src/main/webapp/WEB-INF/images
In Config file
@Configuration
public class AppConfig implements WebMvcConfigurer {

......
......

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

 registry.addResourceHandler("/images/*").addResourceLocations("/WEB-INF/images/");

    }
}

In Security
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/images/*").permitAll()

//To display the image on first landing page to all users
}

A: I suggest you to add the beans:
<mvc:resources mapping="/css/**" location="/resources/static/css/" />
<mvc:resources mapping="/img/**" location="/resources/static/img/" />

in your dispatcher spring-web-servlet.xml and then simply call
<link rel="stylesheet" type="text/css" href="./css/test_style.css"/>"


text:
Q: what is the best way to laod data in cloudsearch domain using java sdk after its creation Hi I want to load data into cloudsearch domain using java sdk from database.
I am using terraform for creating cloudsearch domain. how can I trigger event which will load data into cloud search domain. for uploading data I will using java sdk.


text:
Q: Noun or non-finite subordinate clause? Consider the following sentence:

The government wants to encourage understanding of science.

Now, "to encourage understanding of science" is a non-finite subordinate clause functioning as an object. What about "understanding of science"? Is that also a non-finite clause? Or is "understanding" considered to be a noun?

Learning is an easy process for some.

Here, is "learning" a noun or a non-finite subordinate clause functioning as the subject of the whole clause?
I'm inclined to say that "understanding" is a noun, whereas "learning" is a non-finite clause. However, I don't know what this intuition is based on.

A: In your examples, understanding and learning are both nouns. Understanding is the object of the verb encourage and it is post-modified by the prepositional phrase of science. Learning is the subject of the verb is.

A: Understanding is a noun. You could put 'the' in front of it:

to encourage the understanding of science

A: In these cases, you chose words (understanding & learning) that are nouns, and the sentences work best if they are interpreted as nouns.


text:
Q: Scrolling navbar with gradient I'm trying to create a navigation bar with a fading gradient for the mobile version of a page. For a demonstration of what I'm describing, take a look at the mobile version of the Google search result page. The when you scroll the horizontal navbar (with links to news, shopping, images, etc. subpages), the far left and right of the text fades out.

As you can see, each of the navbars show fading gradients, at the same places relative to the viewport and at different places relative to the navigation links. On the first, the gradients are on 'alles' and 'shopping', on the second, the gradients are on 'alles' and the 'm' in maps, and on the third the gradient is on 'news' and no text is far enough to the right to have a gradient.
The challenge here is that the text needs to be scrollable, and the gradient needs to stay in the same place in the viewport. The position of the gradient relative to the text needs to change as the text scrolls.
All of the solutions I've found for gradient text with CSS involve using a -webkit-linear-gradient background with -webkit-background-clip: text;, and -webkit-text-fill-color: transparent;. This basically creates a gradient background which contours the text, and then makes the text invisible so the background can be seen. The background doesn't scroll.
Are there any solutions to this problem using CSS?
Thanks!

A: I would create an overflowing div on top of your bar with pointer-event: none;. This div would contain a gradient background from white to transparent to white again. It can be done using css or an image.

.bar {
  position: relative;
  width: 100%;
  background-color: white;
}

.gradient {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  pointer-events: none;
  background: linear-gradient(90deg, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 1) 100%);
}

  test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test

A:

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: sans-serif;
}

.nav-outter {
    position: relative;
}

.nav-outter::before {
    position: absolute;
    top: 0;
    left: 0;
    width: 80px;
    height: 100%;
    content: '';
    background: linear-gradient(to right, #fff, transparent);
    pointer-events: none;
}

.nav-outter::after {
    position: absolute;
    top: 0;
    right: 0;
    width: 80px;
    height: 100%;
    content: '';
    background: linear-gradient(to left, #fff, transparent);
    pointer-events: none;
}

.nav {
    width: 100%;
    display: flex;
    background-color: #ddd9d9;
    box-shadow: 0 2px 10px rgba(128, 128, 128, 0.336);
    overflow: auto;
}

.nav-link {
    padding: 10px 20px;
    border-bottom: 3px solid transparent;
}

.nav-link:hover {
    border-bottom-color: dodgerblue;
    cursor: pointer;
    transition: .3s;
}

Home

Images

News

Videos

Home

Images

News

Videos

Home

Images

News

Videos

Home

Images

News

Videos


text:
Q: Erro no "se então" estão aceitando todos na resposta algoritmo "tinder"

var

   l, m, i, b, c, s: logico

   pri, seg, ter: caracter

   andressa, monica, leticia, eduarda, maria, ana, clarisse, joana: logico

inicio

      escreval ("----------------------------------")

      escreval ("        PAR PERFEITO              ")

      escreval ("----------------------------------")

      escreval ("Qual tipo de garota você procura? ")

      escreval ("Loira ou Morena? [L]/[M]")

      l <- verdadeiro

      leia(pri)

      escreval ("Inteligente ou Bonita? [I]/[B]")

      i <- verdadeiro

      leia(seg)

      escreval ("Carinhosa ou Safada? [C]/[S]")

      c <- verdadeiro

      leia(ter)

      andressa <- pri=="l" e seg=="i" e ter=="c"

      eduarda <- pri=="l" e seg=="b" e ter=="s"

      clarisse <- pri=="l" e seg=="i" e ter=="s"

      maria <- pri=="l" e seg=="b" e ter=="c"

      monica <- pri=="m" e seg=="b" e ter=="s"

      leticia <- pri=="m" e seg=="b" e ter=="c"

      ana <- pri=="m" e seg=="i" e ter=="c"

      joana <- pri=="m" e seg=="i" e ter=="s"

      se (andressa = verdadeiro) entao

         escreva ("Seu par perfeito é Andressa")

      fimse

      se (eduarda = verdadeiro) entao

         escreva ("Seu par perfeito é Eduarda")

      fimse

      se (clarisse = verdadeiro) entao

         escreva ("Seu par perfeito é Clarisse")

      fimse

      se (Maria = verdadeiro) entao

         escreva ("Seu par perfeito é Maria")

      fimse

      se (monica = verdadeiro) entao

         escreva ("Seu par perfeito é Mônica")

      fimse

      se (Leticia = verdadeiro) entao

         escreva ("Seu par perfeito é Letícia")

      fimse

      se (ana = verdadeiro) entao

         escreva ("Seu par perfeito é Ana")

      fimse

      se (joana = verdadeiro) entao

         escreva ("Seu par perfeito é Joana")

      fimse

fimalgoritmo

A: Depurando seu código notei que as variáveis que representam os nomes femininos do tipo logico estavam recebendo a variável l que por sua vez estava sendo alimentada com verdadeiro após a impressão da primeira solicitação. Veja a seguir:

Usando seu próprio modelo, desfiz a forma como você alimentou as variáveis e eliminei as variáveis l, m, b, i, c, s: logico. Veja como ficou:
se ((pri = "l") e (seg = "i") e (ter = "c")) entao
   andressa <- verdadeiro
senao
   se ((pri = "l") e (seg = "b") e (ter = "s"))entao
      eduarda <- verdadeiro
   senao
      se ((pri = "l") e (seg = "i") e (ter = "s")) entao
         clarisse <- verdadeiro
      senao
         se ((pri = "l") e (seg = "b") e (ter = "c")) entao
            maria <- verdadeiro
         senao
            se ((pri = "m") e (seg = "b") e (ter = "s")) entao
               monica <- verdadeiro
            senao
               se ((pri = "m") e (seg = "i") e (ter = "c")) entao
                  ana <- verdadeiro
               senao
                  se ((pri = "m") e (seg = "b") e (ter = "c")) entao
                     leticia <- verdadeiro
                  senao
                     se ((pri = "l") e (seg = "i") e (ter = "s")) entao
                        joana <- verdadeiro
                     senao
                        se (((pri <> "l") ou (pri <> "m")) ou ((seg <> "i") ou (seg <> "b")) ou ((ter <> "c") ou (ter <> "s"))) entao
                           escreval("Erro: O caracter informando não é válido, tente novamente")
                        fimse
                     fimse
                  fimse
               fimse
            fimse
         fimse
      fimse
   fimse
fimse

Veja que funcionou:

E completei verificando se o que foi digitado é válido:

Segue abaixo o código usado completo:
algoritmo "semnome"
// Função :
// Autor :
// Data : 20/04/2018
// Seção de Declarações
var
   pri, seg, ter: caracter
   andressa, monica, leticia, eduarda, maria, ana, clarisse, joana: logico

inicio
// Seção de Comandos
escreval ("----------------------------------")
escreval ("        PAR PERFEITO              ")
escreval ("----------------------------------")

escreval ("Qual tipo de garota você procura? ")
escreval ("Loira ou Morena? [L]/[M]")
leia(pri)

escreval ("Inteligente ou Bonita? [I]/[B]")
leia(seg)

escreval ("Carinhosa ou Safada? [C]/[S]")
leia(ter)

se ((pri = "l") e (seg = "i") e (ter = "c")) entao
   andressa <- verdadeiro
senao
   se ((pri = "l") e (seg = "b") e (ter = "s"))entao
      eduarda <- verdadeiro
   senao
      se ((pri = "l") e (seg = "i") e (ter = "s")) entao
         clarisse <- verdadeiro
      senao
         se ((pri = "l") e (seg = "b") e (ter = "c")) entao
            maria <- verdadeiro
         senao
            se ((pri = "m") e (seg = "b") e (ter = "s")) entao
               monica <- verdadeiro
            senao
               se ((pri = "m") e (seg = "i") e (ter = "c")) entao
                  ana <- verdadeiro
               senao
                  se ((pri = "m") e (seg = "b") e (ter = "c")) entao
                     leticia <- verdadeiro
                  senao
                     se ((pri = "l") e (seg = "i") e (ter = "s")) entao
                        joana <- verdadeiro
                     senao
                        se (((pri <> "l") ou (pri <> "m")) ou ((seg <> "i") ou (seg <> "b")) ou ((ter <> "c") ou (ter <> "s"))) entao
                           escreval("Erro: O caracter informando não é válido, tente novamente")
                        fimse
                     fimse
                  fimse
               fimse
            fimse
         fimse
      fimse
   fimse
fimse

se (andressa = verdadeiro) entao
   escreval ("Seu par perfeito é Andressa")
senao
   se (eduarda = verdadeiro) entao
      escreval ("Seu par perfeito é Eduarda")
   senao
      se (clarisse = verdadeiro) entao
         escreval ("Seu par perfeito é Clarisse")
      senao
         se (Maria = verdadeiro) entao
            escreval ("Seu par perfeito é Maria")
         senao
            se (monica = verdadeiro) entao
               escreval ("Seu par perfeito é Mônica")
            senao
               se (Leticia = verdadeiro) entao
                  escreval ("Seu par perfeito é Letícia")
               senao
                  se (ana = verdadeiro) entao
                     escreval ("Seu par perfeito é Ana")
                  senao
                     se (joana = verdadeiro) entao
                        escreval ("Seu par perfeito é Joana")
                     fimse
                  fimse
               fimse
            fimse
         fimse
      fimse
   fimse
fimse

fimalgoritmo


text:
Q: Silex and htaccess to /web I m actually creating a simple application using Silex and I m having some problems.
Actually, I run on an Apache 2 server and I have the fallback /index.php set in my ht access at the root of my application.
In fact, I actually have to get these kind of routes :

http://127.0.0.1/appname/web/index.php/route

And I need something like

http://127.0.0.1/route

I absolutely don't know how to proceed...
Can you help me a bit ?

A: Modify your .htaccess to change your root directory and to replace the index.php.
RewriteEngine On
RewriteBase /appname/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %2index.php [QSA]


text:
Q: Error by using @ in PHP for Error Surpass in my project old developer used @ at many places so now i have to upload project on server but at server @ does not support i dont why
Porject is developed in codeigniter
Parse error: syntax error, unexpected '@' in
A PHP Error was encountered
Severity: Parsing Error
Message: syntax error, unexpected '@'

Please guys guide me
Thanks in Advance

A: Just update PHP version it will sort out


text:
Q: Flask Error: Unable to load celery application Please help me to get out of this problem I am getting this when I am running
celery -A app.celery worker --loglevel=info

Error:
Unable to load celery application.
The module app.celery was not found.

My code is--
#  Celery Configuration
from celery import Celery
from app import app
print("App Name=",app.import_name)

celery=Celery(app.name,broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

@celery.task
def download_content():
    return "hello"

directory structure--
newYoutube/app/auth/routes.py and this function is present inside routes.py
auth is blueprint.

A: When invoking celery via
celery -A app.celery ...

celery will look for the name celery in the app namespace, expecting it to hold an instance of Celery. If you put that elsewhere (say, in app.auth.routes), then celery won't find it.
I have a working example you can crib from at https://github.com/davewsmith/flask-celery-starter
Or, refer to chapter 22 of the Flask Mega Tutorial, which uses rx instead of celery, but the general approach to structuring the code is similar.


text:
Q: How to reset IAM user passowrd on multiple AWS acounts with one ansible command I am trying to reset one user password on multiple AWS accounts. Here we have 100 AWS accounts and when we get request for user reset password then we are login manual on the 100 AWS accounts and reset the user password.
I am looking how we can mange it by ansbible. Even how we can create user with command on all the 100 AWS accounts

A: You want to create a script using the aws SDK.
I've normally used python's boto3 and it's pretty simple.
here you have the link of the documentation.
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.create_access_key


text:
Q: 2D Spline and Nearest-Neighbor Adjustment examples not running in sommer package I recently installed the sommer package, but the 2D Spline and nna examples provided would not run for me. I updated my version of R to see if that would resolve the issue, but it did not. These are the examples I have been trying to run:
2D Spline:
data(CPdata)
head(CPpheno)
CPgeno[1:4,1:4]
#### create the variance-covariance matrix
A <- A.mat(CPgeno) # additive relationship matrix
#### look at the data and fit the model
head(CPpheno)

mix1 <- mmer2(Yield~1,
              random=~g(id)
                      + Rowf + Colf
                      + spl2D(Row,Col),
              rcov=~units,
              G=list(id=A), silent=TRUE,
              data=CPpheno)
summary(mix1)

###Warning message: In data(CPdata) : data set 'CPdata' not found

Nearest-Neighbor Adjustment
Found the dataset in agridat by doing a web search for yates.oats, otherwise warning states yates.oats not found
library(agridat)
# NOT RUN {
data(yates.oats)
head(yates.oats)
newyates <- nna(yates.oats, trait="Y")
head(newyates)

plot(newyates$Y, newyates$nnx)
cor(newyates$Y, newyates$nnx)

#### now fit the models and compare #####

m3 <- mmer2(fixed=Y ~ V+N+V:N, random = ~ B + B:MP,
            data = yates.oats)
yates.oats$res <- residuals(m3)

m4 <- mmer2(fixed=Y ~ V+N+V:N + nnx, random = ~ B + B:MP,
            data = newyates)
newyates$res <- residuals(m4)

# library(lattice)
# wireframe(res~row*col,yates.oats)
# wireframe(res~row*col,newyates)

# }

Error Message:

library(agridat)
data(yates.oats)
head(yates.oats)
  row col yield nitro        gen block grain straw
1  16   3    80     0 GoldenRain    B1 20.00 28.00
2  12   4    60     0 GoldenRain    B2 15.00 25.00
3   3   3    89     0 GoldenRain    B3 22.25 40.50
4  14   1   117     0 GoldenRain    B4 29.25 28.75
5   8   2    64     0 GoldenRain    B5 16.00 32.00
6   5   2    70     0 GoldenRain    B6 17.50 27.25
newyates <- nna(yates.oats, trait="Y")

Error in nna(yates.oats, trait = "Y") : could not find function "nna"

A: Please use the documentation from your current version. If you have the newest version installed you may notice that the mmer2() function doesn't exist anymore. If you check the recent documentation from the spl2D() function is this:
data(DT_cpdata)
DT <- DT_cpdata
GT <- GT_cpdata
MP <- MP_cpdata
A <- A.mat(GT)
mix <- mmer(Yield~1,
            random=~vs(id, Gu=A) +
              vs(Rowf) +
              vs(Colf) +
              spl2Db(Row,Col),
            rcov=~units,
            data=DT)
summary(mix)$varcomp

That should work well. The error seems to be that you use a new version of sommer with code from an old script. All the best.
Eduardo


text:
Q: What's the best way to read/write array contents from/to binary files in C#? I would like to read and write the contents of large, raw volume files (e.g. MRI scans).  These files are just a sequence of e.g. 32 x 32 x 32 floats so they map well to 1D arrays.  I would like to be able to read the contents of the binary volume files into 1D arrays of e.g. float or ushort (depending on the data type of the binary files) and similarly export the arrays back out to the raw volume files.
What's the best way to do this with C#?  Read/Write them 1 element at a time with BinaryReader/BinaryWriter?  Read them piece-wise into byte arrays with FileStream.Read and then do a System.Buffer.BlockCopy between arrays?  Write my own Reader/Writer?
EDIT: It seems it's not possible to work with > 2GB arrays, but the question still stands for smaller arrays (around 256 MB or so)

A: You're not going to get arrays with more than 2GB data. From what I remember, there's a CLR limit of 1GB per object. It's possible that's been lifted for .NET 4 on 64-bit, but I haven't heard about it.
EDIT: According to this article the limit is 2GB, not 1GB - but you still won't manage more than 2GB.
Do you really have to have all the data in memory at one time? Can you work on chunks of it at a time?
EDIT: Okay, so it's now just about reading from a file into a float array? It's probably simplest to read chunks (either using BinaryReader.Read(byte[], int, int) or BinaryReader.ReadBytes(int)) and then use Buffer.BlockCopy to efficiently convert from bytes to floats etc. Note that this will be endian-sensitive, however. If you want to convert more robustly (so that you can change endianness later, or run on a big-endian platform) you'd probably want to call ReadFloat() repeatedly.
How convinced are you that you actually have a performance issue in this area of the code? It's worth doing the simplest thing that will work and then profiling it, to start with...


text:
Q: What is the nearest point on a line segment in a map? Assuming I have a list of nodes that have position x,y, each node has an index, and each node stores all its connections, how could I find the nearest point on a line segment? I was able to come up with something but it isn't able to differentiate between line segments and two nodes that aren't connected.
Example Picture
For example, assume I have node 1, 2, and 3. Node 1 is connected to node 2 and node 2 is connected to node 3. I have point A that I want to find the nearest point on line segments. In this case, it is some point between node 1 and 2. How could I find that point? How could I make sure that it doesn't try to check between 1 and 3?


text:
Q: Django edit button redirects to create form My Django edit button always redirects to my Create form and creates a new record. I want an edit function that allows me to edit an existing record. No idea why it keeps returning the create form instead!
home.html:
{% extends 'base.html' %}

{% block content %}

{% for task in tasks %}

{{ task.title }}

{{ task.pub_date_pretty }}

{{ task.summary }}

{{ task.user }}

    Edit

{% endfor %}

Create

{% endblock %}

views.py:
    from django.shortcuts import render, redirect, get_object_or_404
    from django.contrib.auth.decorators import login_required
    from .models import Task
    from django.utils import timezone

    def home(request):
        tasks = Task.objects
        return render(request, 'home/home.html', {'tasks': Task.objects.all().order_by('-pub_date')})

    def taskdetail(request, task_id):
        task = get_object_or_404(Task, pk=task_id)
        return render(request, 'home/taskdetail.html', {'task':task})

    @login_required
    def create(request):
        if request.method == "POST":
            if request.POST['title'] and request.POST['description']:
                task = Task()
                task.title = request.POST['title']
                task.description = request.POST['description']
                task.pub_date = timezone.datetime.now()
                task.completed = False
                task.user = request.user
                task.save()
                return render(request, 'home/taskdetail.html', {'task':task})

            else:
                return render(request, 'home/create.html', {'error':'All fields are required'})
        else:
            return render(request, 'home/create.html')

    @login_required
    def edit(request, task_id):
        if request.method == "POST":
            if request.POST['title'] and request.POST['description']:
                task = Task(pk=task_id)
                task.title = request.POST['title']
                task.description = request.POST['description']
                task.pub_date = timezone.datetime.now()
                task.completed = False
                task.user = request.user
                task.save(pk=task_id)
                return render(request, 'home/taskdetail.html', {'task':task})

            else:
                return render(request, 'home/create.html', {'error':'All fields are required'})
        else:
            return render(request, 'home/create.html')

    @login_required(login_url="/accounts/signup")
    def delete(request, task_id):
        if request.method == "POST":
            task = get_object_or_404(Task, pk=task_id)
            task.delete()
            return render(request, 'home', {'task':task})

urls.py:
from django.urls import path, include
    from . import views

    urlpatterns = [
        path('create', views.create, name='create'),
        path('<int:task_id>', views.taskdetail, name='taskdetail'),
        path('edit/<int:task_id>', views.edit, name='edit'),
        path('delete/<int:task_id>', views.delete, name='delete'),
    ]

I reset the server a number of times and cleared the browser cache, but
I have no idea why it doesn't send me to my edit view

A: When you copied your edit() method, you forgot to change the template names at the bottom.
return render(request, 'home/create.html')

A: This line in edit function: return render(request, 'home/create.html')
When you open the page, it's a GET request by default so it goes to this line. You should render the edit page. And, it's better to use forms to handle the data in the function.


text:
Q: Drawing a rectangle (or line, or bitmap) on the camera preview stream (.NET Compact Framework) I'm working on a .NET CF 2.0 application that uses the camera, showing the preview and allowing the user to take a photo. I'm using the CameraCaptureDialog component and I wanted to draw a rectangle on the preview screen, but I wasn't able to do it... Any ideas?
Do you think the Overlay mixer filter in DirectShow can be useful? If so, do you have any example? (The problem is I work on the CF 2.0, so many solutions that work ok for the normal framework here don't work...).
Thanks in advance,
Giacomo

A: You need to look for samples showing VMR Mixer Bitmap capability and mixing presented video with custom overlay

*

*Drawing video with text on top

*Drawing on top of DirectShow - desperate

*Displaying an Application-Supplied Bitmap on the Composited Image


text:
Q: I dont know why 'Doub' isn't updating I'm working on a program to count every time the dice
roll a double but my variable I'm trying to add to the listbox isn't updating and I don't know why.
Here's the code:
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'declare vars
        Dim teal, red, doub As Integer
        Dim rand As New Random
        teal = rand.Next(6)
        red = rand.Next(6)
#Region "Clear"
Irrelevant stuff
#End Region
        'green dice
            irrelevant if statement
        'red dice
            irrelevant if statement
        'doubles
        **If red = teal Then
            doub = doub + 1
            output.Items.Clear()
            output.Items.Add("Doubles: " & doub)
        End If**
    End Sub
End Class

In the if statements about the dice part
there is nothing to influence the 'doub' variable
so thats why i put "irrelevant if statement"
also because stackoverflow said the post was mostly code

A: Your doub variable is declared inside the button click handler so its scope is only within that procedure. That means it's getting released after every click. You need to have it outside your button click handler:
Dim doub As Integer

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' Declare variables
    Dim teal As Integer
    Dim red As Integer
    Dim rand As New Random

    teal = rand.Next(6)
    red = rand.Next(6)

    Debug.Print(teal & "-" & red)

    ' Doubles
    If red = teal Then
        doub += 1
        Debug.Print("Doubles: " & doub)
    End If

End Sub

You can learn about variable scope in this link: How to: Control the Scope of a Variable
Output (got a double on first try!):
4-4
Doubles: 1
1-5
0-5
5-0
2-2
Doubles: 2
3-0

This quick test shows another problem in your code: you can roll 0, 1, 2, 3, 4, 5 and 6. You should use rand.Next(1,6) instead, assuming you are trying to simulate a dice throw.


text:
Q: Json having "-" in key var data = {
    "train": {
        "number": "12155",
        "days": [
            {
                "runs": "Y",
                "day-code": "SUN"
            },
            {
                "runs": "Y",
                "day-code": "MON"
            },
            {
                "runs": "Y",
                "day-code": "TUE"
            },
            {
                "runs": "Y",
                "day-code": "WED"
            },
            {
                "runs": "Y",
                "day-code": "THU"
            },
            {
                "runs": "Y",
                "day-code": "FRI"
            },
            {
                "runs": "Y",
                "day-code": "SAT"
            }
        ],
        "name": "BHOPAL  EXPRESS"
    },
    "response_code": 200
};
$(document).ready(function(){

var datalist = data.train.days;

      for(var i in datalist)
      {
           $(".train").append("<p> Run on" +datalist[i].day-code +"-" + datalist[i].runs +"</p>");
      }

});

This code give me a error datalist[i].day-code "code is not define".How i can access a key which contains "-" .As it is running fine if am only using datalist[i].runs.Please suggest.

A: You need to replace
datalist[i].day-code

with
datalist[i]['day-code']


text:
Q: $\tan(\theta+i\phi)=\tan(\beta)+i\sec(\beta)$ with conditions Given $θ,ϕ,β$ are real and $0<β<π$,
$$\tan(\theta+i\phi)=\tan(\beta)+i\sec(\beta)$$
Prove that,
$$e^{2\phi}=\cot(\beta/2)$$
$$\theta=n\pi+\pi/4+\beta/2$$
I have tried expanding the L.H.S. of the given with the exponent form of sin/cos, and also using the addition of angles identity of $\tan$. I took the conjugate of the given and added it, resulting in $$\tan(\beta)=\frac{\tan\theta+\tan\theta\tan^2i\phi}{1-(\tan\theta\tan i\phi)^2}$$

A: $$\tan(\theta+i\phi)=\tan\beta+i\sec\beta$$
thus
$$\tan(\theta-i\phi)=\tan\beta-i\sec\beta$$
we can then arrive at,
$$\tan(2i\phi)=\frac{2i\sec\beta}{1+\tan^2\beta+\sec^2\beta}$$
$$\frac{\tanh2\phi}{-i}=\frac{2i\sec\beta}{1+\tan^2\beta+\sec^2\beta}$$
$$\frac{e^{2\phi}-e^{-2\phi}}{e^{2\phi}+e^{-2\phi}}=\frac{1-tan^2\beta}{1+tan^2\beta}$$
$$e^{2\phi}=\pm\cot(\beta/2)$$
and similarly,
$$\tan(2\theta)=\frac{2\tan\beta}{1-(\tan^2\beta+\sec^2\beta)}$$
$$\tan(2\theta)=-\cot\beta$$
$$\tan(2\theta)=\tan(n\pi+\pi/2+\beta)$$
$$\theta=n\pi/2+\pi/4+\beta/2$$
I think, the question is wrong, it should be $n\pi/2$ instead of $n\pi$.


text:
Q: Does pointwise convergence of CDFs imply convergence in distribution? Casella & Berger  define convergence in distribution as follows:
$X_n \rightarrow X $ (in distribution) if
$$\lim_{n\rightarrow \infty} F_{X_n}(x)=F_X(x)$$ for all $x$ such that $F_X(x)$ is continuous.
This resembles pretty much the concept of pointwise convergence of a sequence of functions, so is it fair to say that if $\{F_{X_n}\}$ converges pointwise to $F_X$ then $\{X_n\}$ converges in distribution to $X$? (the converse may not be true since the convergence in distribution requires only convergence in the continuity points).
Is my reasoning ok?
Thanks in advance.

A: Pointwise convergence gives convergence at every point. In particular we have  convergence at continuity points so we surely have $X_n\to X$ in distribution. To show that the converse is not true take $X_n =\frac 1 n, X=0$ and consider convergence at $0$.


text:
Q: Errors of nokogiri "Load Error" with docker-compose up I am running a rails app with docker-compose on a m1 mac.
Kept getting 2 specific errors,
/usr/local/bundle/gems/bootsnap-1.12.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:15:in `require': cannot load such file -- nokogiri/nokogiri (LoadError)

This is the first one
/usr/local/bundle/gems/nokogiri-1.13.6-aarch64-linux/lib/nokogiri/extension.rb:7:in `require_relative': Error loading shared library ld-linux-aarch64.so.1: No such file or directory (needed by /usr/local/bundle/gems/nokogiri-1.13.6-aarch64-linux/lib/nokogiri/3.1/nokogiri.so) - /usr/local/bundle/gems/nokogiri-1.13.6-aarch64-linux/lib/nokogiri/3.1/nokogiri.so (LoadError)

This is the second one.
The errors started showing after all the gems are installed, I have reinstalled nokogiri countless times, rebuilt the image and container, and made sure bundle installs in my dockerfile as well.

A: This problem was resolved by adding platform: linux/x86_64 into my docker-compose.yml file


text:
Q: Rotating body from spherical coordinates Is it possible to rotate body which has its vertices defined in spherical coordinates.
Currently I am doing collage project in VHDL and is about rotating dodecahedron and presenting over VGA.
I applied pinhole camera model equations and that required just two sin/cos calculation and two multiplication per vertice.
I was just thinking about rotating around 3rd axis using 3 steps over two angles but i am unable to figure out proper equations and even if this is possible.
Edit
I think I got it.
Rotating over 3rd axis which is in same direction as camera is just 2D transform of camera coordinates once you you compute them. That mean than for rotating in 3 axes (ok two axis and one inclination) you need to apply total of 4 sin/cos computations and 4 multiplications. If somebody came up whit something better, fell free to post answer.

A: You can rotate around the y-axis by changing θ, and rotate around the z-axis by changing φ.  Rotating around the x-axis, though, is a bit tougher.
One simple way would be to convert everything to catesian coordinates, perform the rotation, and convert back.
The equations for (x,y,z) (spherical-to-cartesian) are

x = r sin θ cos φ
y = r sin θ sin φ
z = r cos θ

The equations for rotating (x,y,z) to new points (x', y', z') around the x-axis by an angle α are

x' = x
   = r sin θ cos φ
y' = y cos α - z sin α
   = (r sin θ sin φ) cos α - (r cos θ) sin α
z' = y sin α + z cos α
   = (r sin θ sin φ) sin α + (r cos θ) cos α

The equations for (r, θ, φ) (cartesian-to-spherical) are

r' = sqrt(x'2 + y'2 + z'2)
   = r
θ' = cos-1(z'/r')
   = cos-1(sin θ sin φ sin α + cos θ cos α)
φ' = tan-1(y'/x')
   = tan-1(tan φ cos α - cotan θ sin α sec φ)

I don't know if there is a way to reduce that any further, but it should work.

A: Hopefully this will be helpful to someone in the future, but there is a small mistake in the above answer.  It should be:
φ' = tan-1(y'/x')
   = tan-1(tan φ cos α - cotan θ sin α sec φ)

I don't have the rep points to post this in the comment, but thought it would be useful.


text:
Q: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' I am trying to compare a month of date stored in the sql while fetching the records but it throws me the exception.
public partial class LateRequest
{
    public int LateRequestID { get; set; }
    public Nullable<int> EmpID { get; set; }
    public Nullable<int> TeamLeadAppr { get; set; }
    public Nullable<int> DeptLeadAppr { get; set; }
    public Nullable<System.DateTime> lateDate { get; set; }
}

in my calculations Class I have;
public int getMonthlyLatesApproved(int empId)
{
    DateTime today = DateTime.Now;
    var getMonth = today.Month
    var lateApproved = (from obj in db.LateRequests
                        where obj.EmpID == empId
                        && obj.TeamLeadAppr == 1 && obj.DeptLeadAppr == 1
                        && obj.lateDate.Value.ToString("mm") == getMonth.ToString()
                        select obj).Count();
    return lateApproved;
}

This did not work so I tried with LINQ like:
return db.LateRequests.Where(x => x.EmpID == empId && x.TeamLeadAppr == 1 && x.DeptLeadAppr == 1 &&
                                  x.lateDate.Value.ToString("mm") == getMonth.ToString()).Count();

This failed and I read it here and tried with AsEnumerable()
like below;
 return db.LateRequests.Where(x => x.EmpID == empId && x.TeamLeadAppr == 1 && x.DeptLeadAppr == 1 &&
                                  x.lateDate.Value.ToString("mm") == getMonth.ToString()).AsEnumerable().Count();

`LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method.when i try to format my date
I need to understand how am I mixing the c-sharp with sql commands while retrieving the records?

A: What you need is the SqlFunctions.DatePart method.
&& SqlFunctions.DatePart("month", obj.lateDate) == getMonth


text:
Q: Can I group * things from this data? I got data with ASCII form.
I ran it with R, and these data have * marked when it is under other condition.
enter image description here
V1, V2, V3, V4, V5 don't mean anything different. All that matters is to classify between *-ed things.
I tried c(V1,V2,V3,V4,V5) but it returns only the levels.
I have no idea. Help me with it.
Question. Can I specify *-ed things via some code?
Is there a way to make these columned things in one data?

A: Select the values marked with *. I guess these values come with the symbol from the original file, right?
In this case use:
position <- grep('\\*', as.matrix(distress[]))
selectedValues <- as.matrix(distress[])[position]
numericValues <- as.numeric(gsub('\*', '', selectedValues))


text:
Q: get last occurrence of first pattern I am trying to fetch the last occurrence of the patterns where the string contains similar patterns in between.
E.g: my string is : "abc abc abc efg 123 abc 123 abc abc xyz 123"
I want to capture the pattern between abc and 123.
My desired output is:
 ['abc efg 123', 'abc 123', 'abc xyz 123']
So I used regex 'abc.*?123'. But this is giving as follows:
 ['abc abc abc efg 123', 'abc 123', 'abc abc xyz 123']
I don't want first occurrence of first pattern to second pattern, I need last occurrence of first pattern to second pattern
import re
a="abc abc abc efg 123 abc 123 abc abc xyz 123"
print a
b=re.findall(r'abc.*?123',a)
print "Output is: "+str(b)

Output is:  ['abc abc abc efg 123', 'abc 123', 'abc abc xyz 123']
I expect the output as:  ['abc efg 123', 'abc 123', 'abc xyz 123']

A: To match the last occurrence of abc in abc abc abc, you could use a negative lookahead (?! abc) to assert abc is not followed by a space and abc. Use word boundaries \b to prevent abc being part of a larger word.
If there can be a single occurrence of abc after efg you might use:
\babc\b(?! abc\b).*?\b123\b

Regex demo | Python demo
import re
a="abc abc abc efg 123 abc 123 abc abc xyz 123"
b=re.findall(r"\babc\b(?! abc\b).*?\b123\b",a)
print (b)

Result

['abc efg 123', 'abc 123', 'abc xyz 123']


text:
Q: Finding out what's slowing down ASP.NET pages I have a rather 'heavy' ASP.NET page, and currently the speed is fairly unacceptable - there is a lot of database communication, and displaying large grids. But I effectively want to find out what's actually causing the most slowdown, and working from there.
Are there any tools built into Visual Studio 2008, or any third party tools, that'll allow me to do this?

A: You could use ASP.Net Trace to figure out what is slowing down in the page.

A: Another good tool and easy to use, https://addons.mozilla.org/en-US/firefox/addon/yslow/
Not aimed directly at code, but is very helpful with resources

A: Have you heard about profiling?
My favorite tool is RedGate's Ants Performance Profiler.

A: An easy approach is using Stopwatch. Something like this:
void SlowMethod()
{
   Stopwatch timer = new Stopwatch();
   timer.Start();
   //a lot of DB operations
   timer.Stop();
   //record timer.Elapsed

   //restart the timer and check another piece of code
   //at last find the bottle neck of the method
}

A: What Muhammad said - add tracing to your code to identify the slowest bits.
Also if you think db activity could be responsible, you could run SQL profiler to identify any long running queries - this will also help you correct indexes.

A: Some ideas:
Visual Studio Team System has a built in profiler. In VS 2010 this is available in premium and above.
Otherwise red-gate has a good profiler available. (for a fee).
Try using the tracing functionality built into asp.net.
Try using client side developer tools like Yslow and Page Speed or fiddler to see the requests for a page and their size and timings.
If you haven't already done so, make sure your server is serving gzipped content. This is an easy win.
Use SQL Server Profiler to profile your database requests.

A: There are many profiling tools available, I personally like ANTS Profiler, it is quite good.  Check out the following link for more information on out to use it: ANTS Profiler
And here is a link to the ANTS Profiler download: 14 Day Free Trial
But if there is a lot of database communication, it is most likely the cause.  Try minimizing the number of database calls and improving the performance of your database queries.
Also make good use of cacheing!