text:
Q: Object of abstract class type "Animal" is not allowed: (C++) I'm trying to store things into vector but there're few problems.
These are my code.
Animal.cpp
#include "Animal.h"
#include "Cattle.h"
#include "Sheep.h"
#include <iostream>
#include <string>
using namespace std;

Animal::Animal(int newid, double newweight, int yy, int mm, int dd, double newaccDose, char newsex)
{
    id = newid;
    weight = newweight;
    yy = yy;
    mm = mm;
    dd = dd;
    dose = newaccDose;
    sex = newsex;
}

Animal::Animal()
{
    id = 0;
    weight = 0;
    yy = 0;
    mm = 0;
    dd = 0;
    dose = 0;
    sex = ' ';
}

Animal::~Animal(){}

double Animal::getDaysDifference(){
    jdate dateOfBirth(dd,mm,yy);
    jdate now;
    double diff = now-dateOfBirth;
    return diff;
}

void Animal::addAnimal(){
    int select=0;
    int id;

    cout << "1.  Cattle    2.  Sheep" << endl;
    cout << "Select a type of animal: ";
    cin >> select;

    if(select==1){
        Cattle* c1;
        cout << "Please answer following questions" << endl;
        cout << "Type the animal's ID: ";
        cin >> id;

        c1->setID(id);

        //vector<Animal> vec;
        //vector<Animal>::iterator vec_ite;

    }else if(select==2){
        Sheep* s1;
        cout << "Please answer following questions" << endl;
        cout << "Type the animal's ID: ";
        cin >> id;

        s1->setID(id);
    }
    else{
        cout << "Invalid number please try again" << endl;
    }
}

First off, in the code above, Cattle* c1 and Sheep* s1, it doesn't have an error.
and even if I code like s1->setID(id) it's fine. However,
Cattle.cpp
#include "Cattle.h"

Cattle::Cattle(int newid, double newweight, int yy, int mm, int dd,
           double newdose, char newsex, string newcategory)
    : Animal(id, weight, yy,mm,dd, dose, sex)
{
    id = newid;
    weight = newweight;
    dose = newdose;
    sex = newsex;
    Cattle::category = newcategory;
}

Cattle::Cattle(){
    id = 0;
    weight = 0;
    dose = 0;
    sex = ' ';
    Cattle::category = "";
}

Cattle::~Cattle(){}

string Cattle::getCategory(){
    return category;
}

double Cattle::calcDose(){
    Cattle* c1;
    if(c1->getDaysDifference() < 90 || c1->getCategory() == "Meat"){
        c1->dose = 0;
        return c1->dose;
    }
    else if(c1->getCategory() == "Dairy"){
        if (c1->weight < 250 || c1->dose > 200){
            c1->dose = 0;
        }
        else{
            c1->dose = c1->weight * 0.013 + 46;
        }
        return c1->dose;
    }
    else if(c1->getCategory() == "Breeding"){
        if (c1->weight < 250 || c1->dose > 250){
            c1->dose = 0;
        }
        else{
            c1->dose = c1->weight * 0.021 + 81;
        }
        return c1->dose;
    }
    else
    {
        cout << "It is not valid category" << endl;
    }
}

Animal.h
#ifndef ANI_H
#define ANI_H
#include <vector>
#include "Treatment.h"
#include "jdate.h"

class Animal{
protected:
    int id;
    double weight;
    int yy;
    int mm;
    int dd;
    double dose;
    char sex;
    //Treatment treatArray[];
public:
    Animal();
    Animal(int newid, double newweight, int yy, int mm, int dd, double newdose, char newsex);
    ~Animal();

    virtual double calcDose() = 0;
    void addAnimal();
    double getDaysDifference();
};
#endif

DrugAdmin.cpp (main)
#include <iostream>
#include "Animal.h"
#include "Cattle.h"
using namespace std;

int main(){
    Animal* a1=new Animal;
    delete a1;

    a1->addAnimal();
}

The problem is here, when I try to define Animal* a1=new Animal;
        delete a1; it says Object of abstract class type "Animal" is not allowed:
I've Googled and Binged here and there, and I figured out I cannot define the abstract base class itself but subclasses.
So I tried the same thing in Cattle.cpp using Cattle c1=new Cattle; but it doesn't work either..
I'm really not sure what's wrong with that..
Could you help me please?
Cheers

A: virtual double calcDose()
This says "It is possible to calcDose() for everything which is an Animal, and different Animals may do it differently..."
= 0;
"... but there is no 'generic' way to do it for Animals; each one must specify its own method".
You may not construct an unspecified sort of Animal because, by definition, a key piece of information is missing: how to calcDose for it.
This is all well and good. Chances are, you don't really want to construct an unspecified Animal, for the same reason that in real life, you wouldn't go to a farm (Zoo? Pet store?) to buy "an animal" without having any specific preconception of what kind of Animal you want.
The type Animal exists so that you can omit the information about what kind of Animal something is when it is appropriate to do so. Creating the instance is not one of those times, in your case.

Also, addAnimal makes absolutely no sense as a member function of Animal, no matter how much you might think it does. There are three fundamental problems:
1) since it's a non-static member function, you already require an Animal to call the function. That's kind of a catch-22.
2) You don't have anywhere to add the animal to. You need some kind of container.
3) Conceptually, making a list of Animals is not the animals' responsibility. It's the responsibility of whoever needs the list.
4) In general, it is good policy to have clean separation between the code that asks the user for information, and the code which acts upon that information. Write a free (meaning, not part of a class) function that asks for the information, constructs the Animal and returns that pointer; then in the calling code, store the pointer in a container.
Except you don't really want to use raw pointers for this anyway. You should be using some kind of smart pointer, or else putting the pointers into one of the boost ptr_container s.

A: Animal is an abstract class, which means it has pure virtual function(s). This is the pure virtual function in Animal.
virtual double calcDose() = 0;

Object of an abstract class cannot be created. It is true not only in C++, rather in all object oriented languages whichever support  pure virtual function (some languages, such as C#, calls it abstract method.)
If you remove the pure specifier which is =0 part in the declaration, as marked below:
virtual double calcDose() = 0;
                       //^^^^ this is called pure specifier

then it will become virtual function (as opposed to pure virtual function). Now, you've to define the virtual function, and you can create objects of Animal then, as it is no more an abstract class.

A: In Animal, you have:
virtual double calcDose() = 0;

So that class is abstract and cannot be instantiated. You can only construct objects of classes that derive from it and implement that method.


text:
Q: how to shuffle XML layouts I'm very new in developing an application in Android
How can i randomly change the current activity Layout when i click a Button ? i don't really know how and where to start coding
public class RandomSample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button random = (Button) findViewById(R.id.button1);

    random.setOnClickListener(new View.OnClickListener() {
    int [] layouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3};
    Random r = new Random();

        @Override
        public void onClick(View v) {
            setContentView(r.nextInt(layouts.length));
        }
    });
}
}

here's what I did but noting seems to be working at all

A: Declare an array of ids of layouts and then change it setContentView()
int[] layouts={R.layout.l1, R.layout.l2, R.layout.l3, R.layout.l4};
Random r=new Random();

in your onClick() method of particular button
setContentView(r.nextInt(layouts.length));

A: The issue with your posted is that you are trying to set the random index as the content view rather than its associated layout. I've modified your code below.
private static final int[] layouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3};
Random r = new Random();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button random = (Button) findViewById(R.id.button1);
    random.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // This is just a number 0 - 2. It should not be set to content view.
            int index = r.nextInt(layouts.length);
            int nextLayout = layouts[index];
            setContentView(nextLayout);
        }
    });
}

A: In your activity
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn=(Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
                      setContentView(R.layout.second);
                      }
              });
        }

A: Each id mapped on R class is an integer. So, you can use the method nextInt() from Random class to pick a random layout.
Try something like this:
int firstLayout = R.layout.l1; //your first layout
int numberOfLayouts = 5; // the number of layouts that you have

myButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        Random r = new Random();
        setContentView(r.nextInt(numberOfLayouts) + firstLayout);
    }
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: anybody know how to choose the mnumber of paremetrs passed on a method in python class filler (object):
def init(self, you):
    self.you = you

def Family(self, sibling, ):
    pass

where the user can decide how many siblings they have
I know this is probably a stupid question but I am a beginner and any help is appreciated

A: try:
def Family(self, *args):
    pass

You can then iterate over args like this
def Family (*args):
    for sibling in args:
        print(sibling)


text:
Q: Python - reassign priority list with the lowest possible values The priorities range can be from 1 to 99.

A: Try the following:
def reassignedPriorities(priorities):
    ordered_raw_priorities = sorted(set(priorities))
    priority_dict = {ordered_raw_priorities[i]: i + 1 for i in range(len(ordered_raw_priorities))}

    return [priority_dict[e] for e in priorities]

Using enumerate the code could be even simplified:
def reassignedPriorities(priorities):
    ordered_raw_priorities = sorted(set(priorities))
    priority_dict = {
        e: i for i, e in enumerate(ordered_raw_priorities, start=1)
    }

    return [priority_dict[e] for e in priorities]

Then if you call
reassignedPriorities([1,3,7,3])

the output will be
[1, 2, 3, 2]


text:
Q: How to add local folder as dependency for firebase functions in the package.json? I have a scenario where , I have to compile an npm package to es2015 for using in firebase functions . So What I did was , I just downloaded the package from npm and compiled to es2015 using babel and added the relative path to package.json .
Tried a lot , but nothing working.
I tried a lot of paths like
{
  ...
   "dependencies": {
   "[package name]":"/[edited package folder name]"
  }
}

It would be great if anyone could throw some light on this .
Thanks.

A: Yes , I figured it out .
I packed the package using npm pack
Than added the package as
"lib": "file:packages\\lib-3.1.1.tgz"
Thanks


text:
Q: Proc means - Calculating the share / weight I am using a proc means to calculate the share of the payments made by business line, the data looks like this:
data Test;
input ID Business_Line Payment2017;
Datalines;
1 1 1000
2 1 2000
3 1 3000
4 1 4000
5 2 500
6 2 1500
7 2 3000
;
run;

i'm looking to calculate an additional column which, by group (business_line) calculates the percentage share (weight) of the payment as such:
   data Test;
input ID Business_Line Payment2017 share;
Datalines;
1 1 1000 0.1
2 1 2000 0.2
3 1 3000 0.3
4 1 4000 0.4
5 2 500 0.1
6 2 1500 0.3
7 2 3000 0.6
;
run;

the code I have used so far:
proc means data = test noprint;
class ID;
by business_line;
var Payment2017;
output out=test2
sum = share;
weight = payment2017/share;
run;

I have also tried
proc means data = test noprint;
class ID;
by business_line;
var Payment2017 /weight = payment2017;
output out=test3 ;
run;

appreciate the help.

A: Proc FREQ will compute percentages.  You can divide the PERCENT column of the output to get the fraction, or work with percents downstream.
In this example id crosses payment2017 in order to ensure all original rows are part of the output.  If the id was not present, and there were any replicate payment amounts, FREQ would aggregate the payment amounts.
proc freq data=have noprint;
 by business_line;
 table id*payment2017 / out=want all;
 weight payment2017 ;
run;

A: It is convenient to do with proc sql:
proc sql;
   select *, payment2017/sum(payment2017) as share from test group by business_line;
quit;

data step:
data have;
    do until (last.business_line);
    set test;
    by business_line notsorted;
    total+payment2017;
    end;
    do until (last.business_line);
    set test;
    by business_line notsorted;
    share=payment2017/total;
    output;
    end;
    call missing(total);
    drop total;
run;


text:
Q: How to get all parameters' types from parameter pack? I have the following piece of code where I define struct quick with templated static method random with some specializations:
( I used function_traits from other SO answer. Attached on the bottom for reference.)
struct quick
{
  template <typename T>
  static T random();

  template <typename F>
  static void check(F f)
  {

    constexpr auto arity = function_traits<F>::arity; // easy :)
    std::cout << arity << std::endl;
    typedef typename function_traits<F>::template arg<0>::type type0; // easy:)
    // how to get all types of all F's parameters?
  }
};

template <>
std::string quick::random<std::string>()
{
  return std::string("test");
}

template <>
int quick::random<int>()
{
  return 1;
}

I would like to get all types of F's parameters inside check so that I can generate a tuple with random entries (based on my random method specializations).
Like so:
auto t0 = std::make_tuple(quick::random<AllTypes>()...); //pseudo code
auto t =
    std::make_tuple(quick::random <
                                  function_traits<F>::template arg<std::make_index_sequence<arity>>::type...
                                  >
                                  ()...
                     );

I tried with something like:
template<typename F, typename ...TIdxs>
using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;

// ...
// inside check

typedef ArgTypes<F, std::make_index_sequence<arity>> types;

but failed miserably:
main.cpp:80:72: error: expected ';' before '...' token
 using ArgTypes = typename function_traits<F>::template arg<TIdxs>::type...;
                                                                        ^
main.cpp: In static member function 'static void quick::check(F, D)':
main.cpp:98:15: error: 'ArgTypes' does not name a type
       typedef ArgTypes<F, std::make_index_sequence<arity>> types;

I have used function traits utilities from this SO answer.
template <typename T>
struct function_traits : function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    enum { arity = sizeof...(Args) };
    // arity is the number of arguments.

    typedef ReturnType result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
        // the i-th argument is equivalent to the i-th tuple element of a tuple
        // composed of those arguments.
    };
};

A: Note that in function_traits, you already have all the argument types. All you have to do is expose them:
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    enum { arity = sizeof...(Args) };

    using result_type = ReturnType;

    using all_args = std::tuple<Args...>; // <-- add this

    template <size_t i> // <-- consider making this an alias template
    using arg = std::tuple_element_t<i, all_args>;
};

And now, getting all the function arguments is just function_traits<F>::all_args.

If you don't want to change function_traits, we just have to add an external metafunction:
template <class F, class = std::make_index_sequence<function_traits<F>::arity>>
struct all_args;

template <class F, size_t... Is>
struct all_args<F, std::index_sequence<Is...>> {
    using type = std::tuple<typename function_traits<F>::template arg<Is>::type...>;
};

template <class F>
using all_args_t = typename all_args<F>::type;

A: template<class=void,std::size_t...Is>
auto tupler(std::index_sequence<Is...>){
  return [](auto&&f){
    return std::make_tuple(
      f(std::integral_constant<std::size_t,Is>{})...
    );
  }
}
template<std::size_t N>
auto tupler(){
  return tupler(std::make_index_sequence<N>{});
}

This lets you expand parameter packs inline and produce a tuple.
Simply
auto t = tupler<ArgCount>()([&](auto i){
  return random<typename func_trait::arg<i>::type>();
});

Where func_trait is an alias to the thing above.
As an aside, replace struct arg with a using alias.  Cleaner.

A: Not sure that is what you want but... what about modifying quick in the following way?
struct quick
{
  template <typename T>
  static T random();

  template<typename F, std::size_t I>
     using ArgTypes = typename function_traits<F>::template arg<I>::type;

  template<typename F, std::size_t ... Is>
     using ArgTuple = std::tuple< ArgTypes<F, Is>... >;

  template <typename F, std::size_t ... Is>
  static ArgTuple<F, Is...> makeArgTuple ()
   { return make_tuple(quick::random<Is>()...); }

  template <typename F>
  static void check(F f)
  {

    constexpr auto arity = function_traits<F>::arity; // easy :)
    std::cout << arity << std::endl;

    typedef typename function_traits<F>::template arg<0>::type type0; // easy:)

    auto t = ArgTuple<F, std::make_index_sequence<arity>::type> ();

    auto t2 = makeArgTuple<F, std::make_index_sequence<arity>::type>();
  }

};

You were wrong passing typenames TIdxs to arg; arg needs a std::size_t.
Take into account that std::make_index_sequence it's a C++14 feature (but it's easy to create it in C++11 too).
p.s.: sorry for my bad English.


text:
Q: Kerr Metric and Asymptotically Static Frame Suppose we are given a Kerr spacetime (e.g. containing a single uncharged rotating black hole). How does one know that the coordinates chosen is rotating or non-rotating as seen from infinity? And how does one compute the angular velocity as seen by observer at infinity?
The standard choice of metric is written in Boyer-Lindquist coordinates: I presume this is a "asymptotically rotating coordinates". If coordinates are not an invariant concept, I should be able to, for instance, go into a "non-rotating" frame and write the metric differently. But I am confused as to how this can be done.


text:
Q: Opencv 3.1 compiled with FFMPEG, but won't open https urls I work on a 16.04 system, and have successfully installed opencv 3.1 with FFMPEG flags enabled. I double checked this was actually the case by cv2.getBuildInformation() and I got FFMPEG = YES.
I am trying to open a video that is hostel on a private server by my workplace (I am logged in to the VPN, in case thats a concern) and I can access this video over the browser. But videocapture with cv2 fails.
>>> cap = cv2.VideoCapture("https://xxx.mp4", cv2.CAP_ANY) #dummy url
>>> cap
<VideoCapture 0x7f63300fa4b0>
>>> cap.isOpened()
False

This is always the case for https urls. It seems to be able to work with local videos just fine.
I have tried a bunch of different thing: initially thought it was a gstreamer problem so I checked my plugins, had some gst-bad versions (ref: https://github.com/GStreamer/gst-plugins-ugly), removed those and replaced with good versions, no joy.
Also tried to explicitly tell videoCapture to use cv2.CAP_ANY and cv2.CAP_FFMPEG flags while reading the video, still no luck.
I disabled the Gstreamer flag while compiling opencv, but even with it set to ON, there was no difference in my problem.
I haven't been able to find a solution to this issue and have been looking and trying different things for days now! Any ideas?

A: Eventually, I gave up on trying to install and reinstall opencv3.1, and switched to opencv 3.4.1. With that, and my current (as original question post) configuration for gstreamer and ffmpeg, I only had to create symlinks for libopencv_core.so.2.4 that gstreamer was looking for, and the rest of it worked fine.
Hope this helps someone!
I haven't managed to figure out what exactly was the issue with opencv3.1 (like I mentioned, that is the configuration my other colleagues have, and the functionality works just fine for them) but this is what I ended up doing after spending days on the issue.


text:
Q: How to programmatically add a 'shortcut' to my app from users' Facebook profiles? I'd like an icon and label to appear in the section marked in red below, that links to my application canvas page:

Is this possible using any of the current Facebook APIs? No legacy APIs as this is a new app.

A: No this is no longer possible; the ability to add Apps to profile tabs was announced as deprecated in August 2010 and removed entirely in November 2010. (ref https://developers.facebook.com/blog/post/415/ )
The bookmarks section (visible in approximately the same place you've highlighted, but on the Home / News Feed page rather than the profile) is automatically populated and will have an entry there for your app once users authorise it; this links back to your canvas page or to your bookmark URL if you have one defined


text:
Q: Grails get list of A's where searching with B's in many to many relationship I have the following domain objects:
class Blog {
   String foo
}

class Comment {
   String bar
}

class BlogComment {
   Blog blog
   Comment comment
}

So far I've written this:
def getComments(Blog blog) {
    def blogCommentCriteria = BlogComment.createCriteria()

    def blogCommentResults = blogCommentCriteria.list {
        eq 'blog.id', blog.id
    }

    List<Comment> comments = new Vector<Blog>()

    blogCommentResults.each { i ->
        if(i.blog == blog) {
            comments.add(i.comment)
        }
    }

    comments
}

What would be the most efficient method? I want the method to be clean and simple, but also efficient in terms of time taken.

A: You can add a method to the Blog class to get the comments associated with a given blog:
class Blog {
   String foo

   def getComments() {
        BlogComment.findAllByBlog(this)*.comment
   }
}


text:
Q: Is type inference based off the shape of an object possible in typescript? Lets say I have 3 Interfaces:
interface Animal {
  height: number
  name: string
}

interface Dog extends Animal {
  numberOfTeeth: number
  hasTail: boolean
}

interface Cat extends Animal {
  sizeOfPaw: number
}

and lets say I query an api like this:
function getAnimal(id:string, animalType:string) : Animal {
  const res = await (axios.get(`http://animalapi.com/${animalType}/${id}`));
  return res.data; // Could be a cat, could be a dog, based on animal type
}

If I try to do:
const animal:Dog = getAnimal("1", "dog"); // Would it be possible to not need to pass the string dog? Perhaps store the "dog" value within the interface and pass it from there?

I get errors that 'Animal is missing the following types', followed by the types that are in Dog.
Is it possible to be able to obtain both Dog and Cat from the same function, without having to duplicate the call?

A:
Is type inference based off the shape of an object possible in typescript?

Yup, this is called type narrowing, and you can do it with a discriminated union that joins the Dog and Cat shapes but gives each shape a unique "tag" that distinguishes it from the others (this might be a property like id, type, or whatever you want to call it):
interface AnimalBase {
  height: number
  name: string
}

interface Dog extends AnimalBase {
  type: 'dog';
  numberOfTeeth: number
  hasTail: boolean
}

interface Cat extends AnimalBase {
  type: 'cat';
  sizeOfPaw: number
}

type Animal = Dog | Cat;

Now, when you go to create an Animal, TypeScript will expect you to identify the specific shape by specifying the type property. Then you can pass along animal.type wherever you want since it's a string literal:
const dog: Animal = {
  type: 'dog',
  numberOfTeeth: 100,
  hasTail: true,
  height: 100,
  name: 'Roofus'
};

getAnimal("1", animal.type)

This pattern has the added benefit of allowing you to narrow a generic Animal type to a specific sub-type. For example, you can use it to write a type predicate to check if an animal is of a particular constituent type:
const isDog = (animal: Animal): animal is Dog => {
  return animal.type === 'dog';
}

const dog: Animal = {
  type: 'dog',
  numberOfTeeth: 100,
  hasTail: true,
  height: 100,
  name: 'Roofus'
};

// here, TypeScript knows that animal is now of type Dog
if (isDog(dog)) {
  // myAnimal shape is now Dog
}

Without discriminated unions, you'd need to do a type assertion and check a property that you know is absolutely unique to dogs (maybe hasTail, but that's true for cats too):
const isDog = (animal: Animal): animal is Dog => {
  return typeof (animal as Dog).numberOfTeeth !== 'undefined';
}


text:
Q: Subquery returns more than 1 row on 2nd insert I have 2 tables:
tblUser:
+------+-----------+
|  id  |   Name    |
+------+-----------+

tblItems(this table accepts multiple checkbox value depending on how many user selected):
+------+-----------+---------------+
|  id  |  items    |    name_id    |
+------+-----------+---------------+

name_id will get the value of id in tblUser.
I use this code to get the value of id of tblUser to name_id:
for ($i=0; $i<sizeof($checkbox);$i++){
    $sql2="INSERT INTO tbl_trainings VALUES (NULL, '".$checkbox[$i]."', (SELECT id FROM tbl_info))";
    $result2=mysql_query($sql2);
 }

It works fine on the first INSERT of data that will look like this in database:
+------+-----------+---------------+
|  id  |  items    |    name_id    |
+------+-----------+---------------+
|  1   |  Bucket   |    1          |
+------+-----------+---------------+
|  2   |  Tree     |    1          |
+------+-----------+---------------+
|  3   |  House    |    1          |
+------+-----------+---------------+

But in the next or second INSERT of data will be an error. The error is
Subquery returns more than 1 row from the mysql_error();
By the way, this is the full codes:
if($_POST["Submit"]=="Submit"){
    $sql1="INSERT INTO tblUser VALUES (NULL, '$fname', '$lname')";
    $result1=mysql_query($sql1);
    for ($i=0; $i<sizeof($checkbox);$i++){
    $sql2="INSERT INTO tblItems VALUES (NULL, '".$checkbox[$i]."', (SELECT id FROM tblUser))";
        $result2=mysql_query($sql2);
    }
}

if($result2 && result1){
    echo"";
    echo"
";
    echo "SUCCESSFUL!";
    echo"
";
    echo"";
}
else {
    echo "ERROR". mysql_error();
}

And the desired output in the database would be:
+------+-----------+---------------+
|  id  |  items    |    name_id    |
+------+-----------+---------------+
|  1   |  Bucket   |    1          |
+------+-----------+---------------+
|  2   |  Tree     |    1          |
+------+-----------+---------------+
|  3   |  House    |    1          |
+------+-----------+---------------+
|  4   |  Tree     |    2          |
+------+-----------+---------------+
|  5   | Air plane |    2          |
+------+-----------+---------------+
|  6   | Bucket    |    3          |
+------+-----------+---------------+

Any help would be appreciated.
Thanks in advance.

A: SELECT id FROM tblUser

returns all ids from the table.
You need use mysql last_insert_id instead:
$sql1="INSERT INTO tblUser VALUES (NULL, '$fname', '$lname')";
$result1=mysql_query($sql1);
$user_id = mysql_insert_id();
for ($i=0; $i<sizeof($checkbox);$i++){
    $sql2="INSERT INTO tblItems VALUES (NULL, '".$checkbox[$i]."', $user_id)";
    $result2=mysql_query($sql2);
}

Please note that the standard mysql functions are deprecated.

A: cause of securety reasons you should use prepared statements
http://php.net/manual/en/pdo.prepared-statements.php


text:
Q: What is the minimum time you need to Thread.Sleep( ) to ensure DateTime.Now differs? What is the minimum time you need to Thread.Sleep( ) to ensure DateTime.Now differs ?
Given a DateTime has a Ticks property you could argue the following would suffice:
Thread.Sleep(TimeSpan.FromTicks(1));

which would be fine but does this guarantee subsequent calls to DateTime.Now are not equal?
UPDATE:
Appears DateTime precision is hardware dependent so instead I am going to use the following method:
public static void SleepUntilDateTimeChanges()
    {
        DateTime now = DateTime.Now;
        while(now == DateTime.Now)
            Thread.Sleep(TimeSpan.FromMilliseconds(1));
    }

A: A "tick" is 100 nanoseconds.  Or 1/10,000th of a millisecond.  Thread.Sleep operates on milliseconds.  While it's true it accepts a TimeSpan, a value less than a millisecond will be ignored (i.e. same as zero).  According to @wal the resolution of only 10 milliseconds can be guaranteed.  If you wait that amount you should get unique DateTime instances.
See also this explanation by Eric Lippert which sheds some more light on DateTime precision.


text:
Q: CRUD program to read,write and append the details in txt file It's a school assignment, an event management system. It will write the data to a txt file and retrieve it. Its mostly a CRUD program but not sure why it is not running. It shows space as an error on VS CODE IDE.
It will Create a customer, ask for the seats that he want to book. He can also delete the seats as per ref number before 24 hours.

import random
print("Welcome to the Event System")

def menu():
    print("Choose the number from menu")
    print("1:Create Customer")
    print("2:Reserve a seat")
    print("3.Cancel the seat")
    print("4.Exit the Event System")
    option = input("put down the number")
return option

def executingmenuinputchoice(option):
    if(option == 1):
        createcust()
    elif(option == 2):
        reserveseat()
    elif(option == 3):
        cancelseat()
    elif(option == 4):
        exit()
    else:
        print('you have chose a wrong option')
        menu()

def createcust():
    print('Provide Customer details')
    name = input('Full name? --> ')
    pno = input('phone number? -> ')
    email = input('Email Id? --> ')
    try:
        file = open("cust.txt", "r")
        lines = file.read().splitlines()
        last_lines = lines[-1]
        content = last_lines.split()
        refno = random.randint(10001, 99999)
        file.close()
        file = open("cust.txt", "a")
        file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
        file.close()
        print(refno + 'is your reference number')
        print('Added Customer to file')
    except IOError:
        print("File doesn't exist at location")
    except TypeError:
        print('input proper data')
    return createcust()

def customerexist(refno):
    try:
       file = open("cust.txt", "r")
       for line in file:
            content = line.split()
            if (refno == int(content[4])):
                file.close()
                return True,int(content[5])
    except IOError:
            print("File doesn't exist")
            file.close()
    return False,0

def reserveseat():
    referencenumber=input("Enter the Reference Number-->")
    refexist =referenceexist(referencenumber)
    if(refexist==True):
            seatsyouwantbook=input("Number of seats you want to book? ->")
            date=datetime.datetime.now()
            seats=seats+seatsyouwantbook
            newline=""
    try:
        file=open("cust.txt","r")
        lines=file.read().splitlines()
        last_linesno=len(lines)
        currentLine=1
        for line in lines:
            content=line.split
            if(currentline!=last_linesno):
                if(refno==int(content[4])):
                    file.close()
                    return True,int(content[5])
    except IOError:
            print("FIle never existed")
            file.close()
    return False,0

def cancelseat():
    try:
        file=open("cust.txt","r")
        for line in file:
            content=line.split()
            if (refno==int(content[4])):
                file.close()
                return True,int(content[5])
    except IOError:
        print("File doesn't exist")
        file.close()
        return False,0

invalid syntax (<unknown>, line 41)

I want it to run properly so, I can submit it again.

A: I haven't checked your whole code, but at least got it running to the point that you could further rectify it:-
import random
print("Welcome to the Event System")

def customerexist(refno):
    try:
       file = open("cust.txt", "r")
       for line in file:
            content = line.split()
            if (refno == int(content[4])):
                file.close()
                return True,int(content[5])
    except IOError:
            print("File doesn't exist")
            file.close()
    return False,0

def reserveseat():
    referencenumber=input("Enter the Reference Number-->")
    refexist =referenceexist(referencenumber)
    if(refexist==True):
            seatsyouwantbook=input("Number of seats you want to book? ->")
            date=datetime.datetime.now()
            seats=seats+seatsyouwantbook
            newline=""
    try:
        file=open("cust.txt","r")
        lines=file.read().splitlines()
        last_linesno=len(lines)
        currentLine=1
        for line in lines:
            content=line.split
            if(currentline!=last_linesno):
                if(refno==int(content[4])):
                    file.close()
                    return True,int(content[5])
    except IOError:
            print("FIle never existed")
            file.close()
    return False,0

def cancelseat():
    try:
        file = open("cust.txt","r")
        for line in file:
            content=line.split()
            if (refno==int(content[4])):
                file.close()
                return True,int(content[5])
    except IOError:
        print("File doesn't exist")
        file.close()
        return False,0

def createcust():
    print('Provide Customer details')
    name = input('Full name? --> ')
    pno = input('phone number? -> ')
    email = input('Email Id? --> ')
    try:
        file = open("cust.txt", "r")
        lines = file.read().splitlines()
        last_lines = lines[-1]
        content = last_lines.split()
        refno = random.randint(10001, 99999)
        file.close()
        file = open("cust.txt", "a")
        file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
        file.close()
        print(refno + 'is your reference number')
        print('Added Customer to file')
    except IOError:
        print("File doesn't exist at location")
    except TypeError:
        print('input proper data')
    return createcust()

def menu():
    print("Choose the number from menu")
    print("1:Create Customer")
    print("2:Reserve a seat")
    print("3.Cancel the seat")
    print("4.Exit the Event System")
    option = input("put down the number")
    return option

def executingmenuinputchoice(option):

    option = int(option)
    if(option == 1):
        createcust()
    elif(option == 2):
        reserveseat()
    elif(option == 3):
        cancelseat()
    elif(option == 4):
        exit()
    else:
        print('you have chose a wrong option')
        menu()

executingmenuinputchoice(menu())

REASON FOR ERRORS:-

*

*Your indentation was all over the place, python language
prioritizes indentation as it uses it to figure out a block span, so you should
keep a consistent indentation scheme throughout your code.

*Python uses top down approach for ~interpreting the
program, i.e. It only keeps track of the stuff that it had already
encountered. In your code, the function executingmeninputchoice()
and menu() (the two primary functions used for UI) were stacked
above all other function, therefore when you tried to call other
function from these two function, they aren't called. As the program
doesn't know whether these functions exists or not (as it hasn't
encountered them yet)

*A logical error existed in function
executingmenuinputchoice(option) as you were trying to take in
input a string and were comparing it with integer values, and
therefore every time the operation failed and the control got shifted
to the else block, therefore every time you got the same output
'you have chose a wrong option' regardless of whether the input was
legal or not

P.S.:- I haven't tested your full code, as this isn't a code for me service, other logical errors may also exist, so I would recommend you to find and fix those too.


text:
Q: How to disable macOS shortcut "command + right click" which triggers Mission Control? How can I disable macOS shortcut Command + right click which triggers Mission Control?
I looked in "System Preferences > Mission Control and Keyboard shortcuts" but can't find it defined anywhere. Maybe it's in some plist?
It triggers Mission Control (show all application windows).

A: It's in System Preferences > Keyboard > Shortcuts > Mission Control.
It's  Ctrl ⌃   ↑   by default.


text:
Q: MySQL Query to select from table specific rows I have a table which looks has the following values:

product_id
custom_id
custom_value

1
10
A

1
9
V

2
10
B

3
3
Q

I am looking for a mysql query to get all values from product_id once and select the row which has custom_id = "10" in case it is available. Nevertheless in case custom_id = 10 is not available for a product_id I would still like to return the product_id but also only once.
So the result I am looking for is

product_id
custom_id
custom_value

1
10
A

2
10
B

3
NULL
NULL

Could please someone direct me in the right direction.
select product_id, custom_id, custom_value from table where custom_id = 10

does of course only return the values for product_id "1" and "2"

A: You can select the first set of rows, then union by a distinct of all the other product id's
select product_id, custom_id, custom_value from table where custom_id = 10
union
select distinct product_id, NULL as custom_id, NULL as custom_value where custom_id <> 10

A: You can first generate a ROW_NUMBER to get the first element for each "product_id", then transform to NULL values for which "product_id" does not match your value 10, using the IF function.
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY product_id ORDER BY custom_id = 10 DESC) AS rn
    FROM tab
)
SELECT product_id,
       IF(custom_id=10,    custom_id, NULL) AS custom_id,
       IF(custom_id=10, custom_value, NULL) AS custom_value
FROM cte
WHERE rn = 1

Check the demo here.


text:
Q: How do you get the graph plugin for Squirrel SQL? I installed Squirrel SQL and the website claims the Graph plugin is part of the install.  It is not available nor is it in the jar.  How do I get the graph plugin?

A: As per Installation documentation the correct version of each available plugin is always provided in the SQuirreL SQL Client install jar.

Graph Plugin by Gerd Wagner
Installer Category: Standard
This plugin allows you to create and print charts of database tables and their foreign key relations. If you use it together with the SQL Scripts plugin you are able to script tables from within the charts.

You can download it from http://mvnrepository.com/artifact/net.sf.squirrel-sql.plugins/graph/3.2.1


text:
Q: Scheduling Simulation Run in Anylogic I am working on workshop model where i have set of service blocks and resource pools associated with it. I want to run the Simulation for 8 hours on daily basis but is should run for a week.
For example the run time is 80 hours, model start on 3 -sept at 8:00AM and run till 3-sept 4:00PM, now model again run on 4th sept 8:00 AM till 4th Sept 4:00PM and process continue till total run time is 80 hours.

A: There are two options to consider

*

*Simply ignore the date and time completely.
Set your model tine units to hours and run the model for 80 hours

*Have some object in the model control the work time

Like a little state chart or an event or even a schedule object

When the workingtime state is entered you simply tell machines to work, when the non_workingtime is entered you stop the machines
Option 1 is the easiest but only useable if you can post-process the actual times or don't need it inside you model


text:
Q: Message Delivery Guarantee for Multiple Consumers in Pub/Sub and Messaging Queues Requirement
A system undergoes some state change, and multiple other parts of the system has to know this(lets call them observers) so that they can perform some actions based on the current state, the actions of the observers are important, if some of the observers are not online(not listening currently due to some trouble, but will be back soon), the message should not be discarded till all the observers gets the message.
Trying to accomplish this with pub/sub model, here are my findings, (please correct if this understanding is wrong) -
The publisher creates an event on specific topic, and multiple subscribers can consume the same message. This model either provides no delivery guarantee(in redis), or delivery is guaranteed once(with messaging queues), ie. when one of the consumer acknowledges a message, the message is discarded(rabbitmq).
Example
A new Person Profile entity gets created in DB
Now,

*

*A background verification service has to know this to trigger the verification process.

*Subscriptions service has to know this to add default subscriptions to the user.

Now both the tasks are important, unrelated and can run in parallel.
Now In Queue model, if subscription service is down for some reason, a BG verification process acknowledges the message, the message will be removed from the queue, or if it is fire and forget like most of pub/sub, the delivery is anyhow not guaranteed for both the services.
One more point is both the tasks are unrelated and need not be triggered one after other.

In short, my need is to make sure all the consumers gets the same message and they should be able to acknowledge them individually, the message should be evicted only after all the consumers acknowledged it either of the above approaches doesn't do this.
Anything I am missing here ? How should I approach this problem ?

A: This scenario is explicitly supported by RabbitMQ's model, which separates "exchanges" from "queues":

*

*A publisher always sends a message to an "exchange", which is just a stateless routing address; it doesn't need to know what queue(s) the message should end up in

*A consumer always reads messages from a "queue", which contains its own copy of messages, regardless of where they originated

*Multiple consumers can subscribe to the same queue, and each message will be delivered to exactly one consumer

*Crucially, an exchange can route the same message to multiple queues, and each will receive a copy of the message

The key thing to understand here is that while we talk about consumers "subscribing" to a queue, the "subscription" part of a "pub-sub" setup is actually the routing from the exchange to the queue.
So a RabbitMQ pub-sub system might look like this:

*

*A new Person Profile entity gets created in DB

*This event is published as a message to an "events" topic exchange with a routing key of "entity.profile.created"

*The exchange routes copies of the message to multiple queues:

*

*A "verification_service" queue has been bound to this exchange to receive a copy of all messages matching "entity.profile.#"

*A "subscription_setup_service" queue has been bound to this exchange to receive a copy of all messages matching "entity.profile.created"

*The consuming scripts don't know anything about this routing, they just know that messages will appear in the queue for events that are relevant to them:

*

*The verification service picks up the copy of the message on the "verification_service" queue, processes, and acknowledges it

*The subscription setup service picks up the copy of the message on the "subscription_setup_service" queue, processes, and acknowledges it

*If there are multiple consuming scripts looking at the same queue, they'll share the messages on that queue between them, but still completely independent of any other queue.

Here's a screenshot from this interactive visualisation tool that shows this scenario:

A: As you mentioned it is not something that you can control with Redis Pub/Sub data structure.
But you can do it easily with Redis Streams.
Streams will allow you to post messages using the XADD command and then control which consumers are dealing with the message and acknowledge that message has been processed.
You can look at these sample application that provides (in Java) example about:

*

*posting and consuming messages

*create multiple consumer groups

*manage exceptions

Links:

*

*Getting Started with Redis Streams and Java

*Redis Streams in Action ( Project that shows how to use ADD/ACK/PENDING/CLAIM and build an error proof streaming application with Redis Streams and SpringData )


text:
Q: Peepcode-git.pdf: Best strategy to keep a long standing feature branch in sync with main branch with rebase In the following documentation peepcode-git.pdf located at https://github.com/pluralsight/git-internals-pdf/releases, page 39 notes different use cases for rebase. Particularly this quote:
"If you get a huge project or idea – say refactoring the entire code base to the newest version of your framework or switching database vendors or something, you create a long-term branch, continuously rebase it to keep it in line with other development, and once every - thing is tested and ready, merge it in with your master."
The thing is the examples in the e-book goes over the ideas, the abstract applications for rebase but it doesn't provide concrete commands the user can reproduce examples against it. I can follow most of it except the "continuous rebase" part. Typically, when I have rebased I found it effective when:

*

*I am working on a branch of which I don't know how many commits I will make to get to the solution. Usually when I am experimenting with some code and it doesn't work, I put a note in the commit log to squash that commit since it offers no value. When I finally figure out the desired content state of my code, I rebase the branch to just the important commits, squashing out the others as stated. I then replay those changes via rebase onto the main branch.

If I am working on a long task however, I don't quite understand the idea of rebasing main onto my branch to stay in sync with it as it means that each commit in main will be replayed into a new commit onto my feature branch but it would  the exact same content state. This seems counter intuitive as valuable information is lost when the commit hash changes. Additionally, when it comes time to put feature branch work onto main, it would replay all its changes onto main including the duplicate commits (with different hashes) onto main. I think it would make more sense to continually merge main onto your local branch to keep it in sync with main and then when complete, rebase it onto main. This would help keep the merge-base to a newer point and reduce the number of commits that are replayed onto main. What am I missing?

A: This is a simple misunderstanding. The suggestion is not what you assumed:

If I am working on a long task however, I don't quite understand the idea of rebasing main onto my branch to stay in sync...

Instead, you would regularly rebase your branch onto main. For example:
git switch my-long-lived-branch
git fetch
git rebase origin/main

Note it's possible that you could have conflicts when doing this type of rebase, if someone changed the same files on main that you changed on your branch.
You also mentioned:

When I finally figure out the desired content state of my code, I rebase the branch to just the important commits, squashing out the others as stated.

That is another kind of rebase; an interactive rebase with the intent of fixing up your in-progress commits. You can do this separately against the merge-base (starting commit of your branch) anytime without having conflicts:
# if you know the commit ID of the parent of your first commit:
git rebase -i parent-ID-of-your-first-commit
# or if you have many commits and don't want to bother looking it up
git rebase -i $(git merge-base HEAD origin/main)

As for your suggestion about merging instead of rebasing:

I think it would make more sense to continually merge main onto your local branch to keep it in sync with main and then when complete, rebase it onto main.

That would work fine, and so would the branch rebase, for bringing your branch up to date with the latest origin/main. I think it comes done personal preference. I personally prefer rebasing over merge in this situation, and if you're interactive rebasing anyway, you might as well do the branch rebase regularly as well.


text:
Q: What is faster in Java for reading/parsing console input, Scanner or BufferedReader? I have to craft a data processor able to process more than 2.5MB/s of input from STDIN, and output a number to STDOUT. What is faster, to use a BufferedReader and then conversions to data types or a Scanner and nextInt() or nextFloat()?
EMPIRICAL TEST RESULTS: BufferedReader and conversion is a little bit faster, but nothing too significant.
Thankyou!

A: The answer is most likely that it doesn't matter which way you do it from a performance perspective.  (And there's no way that someone can type at 2.5Mb per second at the console!)
If you include everything that goes on at the OS level and elsewhere when reading from the console, orders of magnitude more CPU cycles will be expended in getting the bytes from the user typing at the console than are spent parsing the characters.  If you are reading from a file (via stdin), we are no longer talking orders of magnitude difference, but I'd still be surprised if the two approaches were significantly different ... overall.
But the best thing you can do is try it out.  It shouldn't take more than a few minutes to write a benchmark that roughly approximates to what you are doing, and see which alternative is faster ... and by how much.  (Make sure that you measure total elapsed time, not just user-space CPU time for the Java application.)

A: BufferedReader reads the stream. While a Scanner breaks its input into tokens.
2.5MB/s is more suitable for the BufferedReader. It has a larger buffer than Scanner. 8 to 1
BufferedReader >>>>


text:
Q: h5file 10xdataset not opening in Seurat I am a beginner in R and I have been trying to work with this h5 file 10x dataset (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE185862) into Seurat but i am running into trouble.
This is what i did:
h5ls("/shared/ifbstor1/projects/scrnaseq_cr/Patrick/AllenBrainAdult/CTX_Hip_counts_10x.h5")

Allen_data <- h5read("/shared/ifbstor1/projects/scrnaseq_cr/Patrick/AllenBrainAdult/CTX_Hip_counts_10x.h5", "/data")

Raw.data <- Allen_data
rm(Allen_data)

enter image description here
Raw.data <- CreateSeuratObject(counts = Raw.data,
                               min.cells = 3,
                               min.features = 800,
                               project = "AllenBrain")

Raw.data$samples <- colnames(x=Raw.data)

dim(Raw.data)

This is the error im getting
Error in CreateAssayObject(counts = counts, min.cells = min.cells, min.features = min.features, :
No cell names (colnames) names present in the input matrix
I have tried also to load the dataset using Read10x_h5 but it's not working:
Raw.data<-Read10X_h5("CTX_Hip_counts_10x.h5")

Error in [[.H5File(infile, paste0(genome, "/data")) :
An object with name data/data does not exist in this group
Any brave soul can help this poor Phd student ?


text:
Q: An MCQ on Greens function $$G(x,t) =\begin{cases}
a+ b\log t  & \text{if $0<x<t$ } \\[2ex]
c+ d\log t & \text{if $t<x<1$ }
\end{cases}$$
is a Greens function for $xy''+y'=0$ subject to $y$ being bounded as $x$ tends to $0$ and $y(1)=y'(1)$ if
The options are
1) $a=b=c=d=1$
2) $a=c=1$, $b=d=0$
3) $a=c=0$, $b=d=1$
4) $a=b=c=d=0$
I don't know how to tackle the problem. I've tried to find the Green's function.
And I've got
$$
G(x,t) =\begin{cases}
a+ b(\log x)  & \text{if $0<x<t$ } \\[2ex]
a+ b(\log x)-\log t+\log x & \text{if $t<x<1$ }
\end{cases}
$$
but this is not in the above given form. Also how to apply the boundary conditions? Please help me to solve the problem.

A: I hope you meant $$G(x,t) =\begin{cases}
a+ b\log t  & \text{if $0<x\le t$ } \\[2ex]
c+ d\log x & \text{if $t\le x\le1$ }
\end{cases}$$
Now, using:

*

*$G(x,t)$ satisfies the boundary condition.

$$\implies G(1,t)=G'(1,t)\implies c+d\log 1=\frac d 1\implies c=d$$
That narrows our options to a and d.

*Derivative, $G'(x,t)$ jumps at $t$ by $1\over p(t)$=$1\over t$
$$\implies d=1$$

Hence 1.


text:
Q: htaccess redirect url with parameters to same url without parameters trying to redirect a url with ending parameter to same url without that parameter on the same domain
www.mydomain.com/efg/abc?id=303
to
www.mydomain.com/efg/abc

found this answer on the matter and try to use it but it doesn't work for me:
RewriteCond %{HTTP_HOST}  ^mydomain\.com$ [NC]
RewriteCond %{REQUEST_URI} /efg/abc
RewriteRule ^efg/abc? [L,R=302]

would appreciate any help.thanks

A: You can use this rule:
RewriteCond %{QUERY_STRING} ^id=303$ [NC]
RewriteRule ^efg/abc/?$ %{REQUEST_URI}? [NC,L,R=302]

? at the end of target URI will strip off any previous query string.

A: You will basically want to drop the query string.  The last line you have with the abc? is not correct because it doesn't redirect anywhere.
Here is what should do the trick (this line alone and be sure that you have enabled modrewrite in .htaccess already):
RewriteRule ^efg/abc$ /efg/abc? [L,R=301]

I tested the above on a test domain of mine and it did the trick.


text:
Q: PHP: checking which flags have been set in user defined function Could someone clarify how to check for flags within a user defined function.
These constants are predefined glob flags.

*

*GLOB_BRACE

*GLOB_MARK

*GLOB_NOSORT

*GLOB_NOCHECK

*GLOB_NOESCAPE

*GLOB_ERR

*GLOB_ONLYDIR

and I have created a new one just to test.
define('GLOB_CUSTOM', 123);

I have also tried
define('GLOB_CUSTOM',0b1111011);

The results are the same.
This function does a var_dump of the flags passed.
function flags_test($flags = NULL) {

    echo '$flags argument
';
    var_dump($flags); // int 1073746108
    echo '
';

    if($flags & GLOB_BRACE){
        echo 'FLAG : "GLOB_BRACE" is set';
        var_dump(GLOB_BRACE);
        echo '
';
    }
    if($flags & GLOB_MARK){
        echo 'FLAG : "GLOB_MARK" is set';
        var_dump(GLOB_MARK);
        echo '
';
    }
    if($flags & GLOB_NOSORT){
        echo 'FLAG : "GLOB_NOSORT" is set';
        var_dump(GLOB_NOSORT);
        echo '
';
    }
    if($flags & GLOB_NOCHECK){
        echo 'FLAG : "GLOB_NOCHECK" is set';
        var_dump(GLOB_NOCHECK);
        echo '
';
    }
    if($flags & GLOB_NOESCAPE){
        echo 'FLAG : "GLOB_NOESCAPE" is set';
        var_dump(GLOB_NOESCAPE);
        echo '
';
    }
    if($flags & GLOB_ERR){
        echo 'FLAG : "GLOB_ERR" is set';
        var_dump(GLOB_ERR);
        echo '
';
    }
    if($flags & GLOB_ONLYDIR){
        echo 'FLAG : "GLOB_ONLYDIR" is set';
        var_dump(GLOB_ONLYDIR);
        echo '
';
    }
    if($flags & GLOB_CUSTOM){
        echo 'FLAG : "GLOB_CUSTOM" is set';
        var_dump(GLOB_CUSTOM);
        echo '
';
    }
}

Test one.
flags_test(GLOB_ONLYDIR); // test one

Results
$flags argument
int 168

FLAG : "GLOB_BRACE" is set
int 128

FLAG : "GLOB_MARK" is set
int 8

FLAG : "GLOB_NOSORT" is set
int 32

FLAG : "GLOB_CUSTOM" is set
int 123

Test two.
flags_test(GLOB_CUSTOM);

Results
$flags argument
int 251

FLAG : "GLOB_BRACE" is set
int 128

FLAG : "GLOB_MARK" is set
int 8

FLAG : "GLOB_NOSORT" is set
int 32

FLAG : "GLOB_NOCHECK" is set
int 16

FLAG : "GLOB_CUSTOM" is set
int 123

I have a few questions.

*

*In test one why is GLOB_CUSTOM showing as set ?

*In test two why is GLOB_BRACE,GLOB_MARK,GLOB_NOSORT and GLOB_NOCHECK showing as set ?

*What does the value of the var_dump($flags) represent(where did that number come from)?

How to implement a bitmask in php? is where i started, i build my example from the accepted answer. Unfortunately it doesn't explain any of the points above.
Edit :

Flags must be powers of 2 in order to bitwise-or together properly.PHP function flags, how?

This should solve the problem
define('GLOB_CUSTOM', 64);

A:
In test one why is GLOB_CUSTOM showing as set ?

while GLOB_CUSTOM is defined as 123 and $flags is set to 168. The masking result in
$flags & GLOB_CUSTOM -> 40
and because you just test if($flags & GLOB_CUSTOM) and not if($flags & GLOB_CUSTOM === GLOB_CUSTOM) your functions shows the wrong result.
you should better use a switch case.
i think this solves also the question number 2

What does the value of the var_dump($flags) represent(where did that number come from)?

if you take the binary representation of this number, you'll see all the defined bits of your flags.


text:
Q: nstableview how to fit text The problem is to fit text into cell. With cell.textfield.sizetofit() and layouts I can create text on more than 1 line, but visible is only one

if I make text size small I can see second line but cut by half


text:
Q: App won't uninstall from Smartwatch 2 I've deployed an Android app that interfaces with the Sony Smartwatch 2, and generally, it's working well. However, I have a user reporting that when he uninstalls the app from his phone, the watch component is not uninstalled.
I understand that the un/installation of the two should be linked, and in my testing (and for most of my users), that works fine. What might this user try to force the app to uninstall from the watch?

A: The user could be right. I've observed the issue only once for ca. twenty (20) installing/uninstalling rounds. However I did not found the way to reproduce it and I can't state what circumstances can cause such behaviour.
Did you've got information from the user on what phone, Android release, Smart Connect or SmartWatch 2 software version this issue occurred?
The only thing he can do to remove Wearable Widgets instance from SmartWatch is to reset the watch (Settings -> Reset SmartWatch).


text:
Q: Recently viewed products in sap commerce cloud How can we add the recently viewed products in sap commerce cloud as it is not an ootb.
Can any one explain.

A: If you want to list these products based on user you can use cookie or local storage to save viewed products. Then use this cookie/localstorage to show them.


text:
Q: Swagger UI showing "Fetch error Not Found" in my asp.net core 2.1 api I have added static files serving and Swashbuckle, but apparently can't find the generated .json
services.AddSwaggerGen(x =>
    x.SwaggerDoc("Swagger", new Info { Title = "Asp.Net Core 2 Api", Description = "Swagger Core Api" }));
----
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseStaticFiles();

app.UseSwagger();
app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/swagger.json", "Core Api"));

any idea? thanks

A: Your swagger end-point has the wrong Url, hence the 'Not Found' Error.
Swagger documents constructed via the default way have their url in the format /swagger/<document-name>/swagger.json where  is the name (first string) parameter supplied in the call to x.SwaggerDoc("Swagger", new Info {...});
In your case you supplied "Swagger", hence your endpoint url should be "/swagger/Swagger/swagger.json".
and in your ConfigureServices your call should be like
app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/Swagger/swagger.json", "Core Api"));

A: After publishing the application on IIS,
I had this same problem, here is how I solved it.
In the Startup.cs file Add in the public void ConfigureServices(IServiceCollection services)... method
services.AddSwaggerGen();
services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("OpenAPISpec",
        new OpenApiInfo()
        {
            Title = "Your Title here",
            Version = "1",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = new Uri("https://example.com/terms"),
            Contact = new OpenApiContact()
            {
                Email = "youremail@gmail.com",
                Name = "Jean Fritz DUVERSEAU",
                Url = new Uri("https://www.rezo509.com")
            }
        });

    var xmlCommentFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentFile);
    options.IncludeXmlComments(xmlCommentsFullPath);
});

and then in the public void Configure(... method
app.UseSwagger();
app.UseSwaggerUI(s =>
{
    string swaggerPath = string.IsNullOrWhiteSpace(s.RoutePrefix) ? "." : "..";
    s.SwaggerEndpoint($"{swaggerPath}/swagger/OpenAPISpec/swagger.json", "Demo API");
});

After that execute the project, then in the browser modify the url as follows:
http (s): //yourserver.com:[port]/swagger/index.html

if you dont add the correct url you will have HTTP ERROR 404

And after publication on the IIS server

A: Long story short: you must check the path prefix difference on your environments and reflect this difference in SwaggerEndpoint([different path]) option.
One of convenient ways is to automate this difference is to put this selection to #if DEBUG section

A: this worked for me
`
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "Test API",
            Version = "v1",
            Description = "List of Api's.",
            Contact = new OpenApiContact
            {
                Name = "Test site",
                Email = string.Empty
            },
        });
    });
    services.AddCors();
    services.AddHttpContextAccessor();
    services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, HttpContextAccessor>();
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("v1/swagger.json", "  API V1");
        c.RoutePrefix = "swagger";
    });

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

`

Try copy pasting your application link om a browser
e.g.  http://localhost/testsite/swagger/v1/swagger.json
compare it with the link in the error.
Tweak the url in c.SwaggerEndpoint accordingly


text:
Q: Jest: Compared values have no visual difference I use jest framework to test.
I store data to create summary in object, pass it object to service that create summary and return summary with additional data. I pick desired fields from summary and compare with object that contain data to create summary and have an error, how fix it ?
const summaryData = {
      userHash: 'some-hash',
      hash: 'hash',
      title: 'Sumary title',
      description: 'Summary Description',
      tags: [
        'js',
        'node',
      ],
    };

    const summary = await SummaryService.createSummary(summaryData);

    expect(pick(summary, Object.keys(summaryData))).toEqual(summaryData);

A: Maybe problem with mongoose model, to fix use .toObject
expect(pick(summary.toObject(), Object.keys(summaryData))).toEqual(summaryData);


text:
Q: Ajax call when clicking a radio button sometimes alternates between being instant to taking ~2 sec There are 2 radio buttons. Depending on which one you click, the drop down box will load that set of data. Depending on the first one I click, that one will take about 1-2 secs to load, while the other loads instantly. Even click back and forth. I was wondering why, and how I might be able to have it stop loading instantly (weird, I know).
$('#rblGenre').change( function() {
    $('#ddlSpecificGenre').attr('disabled','disabled').html( '<option>Loading...</option>' )
    var genre = $(this + ':checked').val();

    $.ajax({
        type: 'GET',
        url: '../bookGenres.xml',
        dataType: 'xml',
        success: function( xml ) {
            var xmlGenre = $(xml).find( genre );
            $('#ddlSpecificGenre').removeAttr('disabled').children().remove();
            xmlGenre.children().each( function() {
                $('#ddlSpecificGenre').append( '<option>' + $(this).text() + '</option>' );
            });
        }
    });
});

<asp:RadioButtonList ID='rblGenre' runat='server'>
    <asp:ListItem Text='Fiction' Value='Fiction'></asp:ListItem>
    <asp:ListItem Text='Non-Fiction' Value='Non-Fiction'></asp:ListItem>
</asp:RadioButtonList>

<asp:DropDownList ID='ddlSpecificGenre' runat='server' Enabled='false'>
    <asp:ListItem Text='Choose a Genre' Selected='True'></asp:ListItem>
</asp:DropDownList>

A: Sounds to me like your response is getting cached. If you want to turn off caching using jQuery, add "cache: false" to your list of settings in your "ajax" call.
So your function call would become:
$.ajax({
    type: 'GET',
    url: '../bookGenres.xml',
    dataType: 'xml',
    cache: false,
    success: function( xml ) {
        var xmlGenre = $(xml).find( genre );
        $('#ddlSpecificGenre').removeAttr('disabled').children().remove();
        xmlGenre.children().each( function() {
            $('#ddlSpecificGenre').append( '<option>' + $(this).text() + '</option>' );
        });
    }
});


text:
Q: Why can't my RabbitMQ cluster on K8s (multi-node Minikube) create its mnesia directory? I am attempting to get a (currently single-node) RabbitMQ cluster created inside of a local Minikube instance. However, there seems to be a permission issue when attempting to create the RMQ cluster on Minikube with two nodes.
Prerequisites:

*

*Have Minikube, kubectl, and krew installed.

Steps to reproduce:

*

*Start Minikube minikube start --memory 8192 --cpus 4 --nodes 2
  minikube v1.27.1 on Debian bookworm/sid
✨  Automatically selected the docker driver
  Using Docker driver with root privileges
  Starting control plane node minikube in cluster minikube
  Pulling base image ...
  Creating docker container (CPUs=4, Memory=8192MB) ...
  Preparing Kubernetes v1.25.2 on Docker 20.10.18 ...
    ▪ Generating certificates and keys ...
    ▪ Booting up control plane ...
    ▪ Configuring RBAC rules ...
  Configuring CNI (Container Networking Interface) ...
  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
  Enabled addons: storage-provisioner, default-storageclass

  Starting worker node minikube-m02 in cluster minikube
  Pulling base image ...
  Creating docker container (CPUs=4, Memory=8192MB) ...
  Found network options:
    ▪ NO_PROXY=192.168.49.2
  Preparing Kubernetes v1.25.2 on Docker 20.10.18 ...
    ▪ env NO_PROXY=192.168.49.2
  Verifying Kubernetes components...
  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

*Install the RabbitMQ plugin to kubectl kubectl krew install rabbitmq

*Install the RabbitMQ cluster operator into Minikube kubectl rabbitmq install-cluster-operator

*Create a default, single-node cluster with the operator kubectl rabbitmq create default
This results in the Persistent Volume (PV), Persistent Volume Claim (PVC), Stateful Set, and Service being created. After waiting a little while for the PVC to be attached to the PV, the Pod gets created. However, I end up with the following console errors with the Pod and the Pod starts a crash loop:
2023-01-19 16:31:42.993395+00:00 [warning] <0.130.0> Failed to write PID file "/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default.pid": permission denied
2023-01-19 16:31:43.520923+00:00 [info] <0.221.0> Feature flags: list of feature flags found:
2023-01-19 16:31:43.520982+00:00 [info] <0.221.0> Feature flags:   [ ] classic_mirrored_queue_version
2023-01-19 16:31:43.521013+00:00 [info] <0.221.0> Feature flags:   [ ] implicit_default_bindings
2023-01-19 16:31:43.521060+00:00 [info] <0.221.0> Feature flags:   [ ] maintenance_mode_status
2023-01-19 16:31:43.521087+00:00 [info] <0.221.0> Feature flags:   [ ] quorum_queue
2023-01-19 16:31:43.521118+00:00 [info] <0.221.0> Feature flags:   [ ] stream_queue
2023-01-19 16:31:43.521147+00:00 [info] <0.221.0> Feature flags:   [ ] user_limits
2023-01-19 16:31:43.521186+00:00 [info] <0.221.0> Feature flags:   [ ] virtual_host_metadata
2023-01-19 16:31:43.521204+00:00 [info] <0.221.0> Feature flags: feature flag states written to disk: yes
2023-01-19 16:31:43.688848+00:00 [notice] <0.44.0> Application syslog exited with reason: stopped
2023-01-19 16:31:43.689010+00:00 [notice] <0.221.0> Logging: switching to configured handler(s); following messages may not be visible in this log output
2023-01-19 16:31:43.697297+00:00 [notice] <0.221.0> Logging: configured log handlers are now ACTIVE
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0>
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0> BOOT FAILED
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0> ===========
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0> Error during startup: {error,
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0>                           {cannot_create_mnesia_dir,
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0>                               "/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/",
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0>                               eacces}}
2023-01-19 16:31:43.715974+00:00 [error] <0.221.0>
BOOT FAILED
===========
Error during startup: {error,
                          {cannot_create_mnesia_dir,
                              "/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/",
                              eacces}}
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>   crasher:
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     initial call: application_master:init/4
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     pid: <0.220.0>
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     registered_name: []
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     exception exit: {{cannot_create_mnesia_dir,
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>                          "/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/",
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>                          eacces},
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>                      {rabbit,start,[normal,[]]}}
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>       in function  application_master:init/4 (application_master.erl, line 142)
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     ancestors: [<0.219.0>]
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     message_queue_len: 1
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     messages: [{'EXIT',<0.221.0>,normal}]
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     links: [<0.219.0>,<0.44.0>]
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     dictionary: []
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     trap_exit: true
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     status: running
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     heap_size: 987
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     stack_size: 29
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>     reductions: 158
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>   neighbours:
2023-01-19 16:31:44.716751+00:00 [error] <0.220.0>
2023-01-19 16:31:44.720886+00:00 [notice] <0.44.0> Application rabbit exited with reason: {{cannot_create_mnesia_dir,"/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/",eacces},{rabbit,start,[normal,[]]}}
{"Kernel pid terminated",application_controller,"{application_start_failure,rabbit,{{cannot_create_mnesia_dir,\"/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/\",eacces},{rabbit,start,[normal,[]]}}}"}
Kernel pid terminated (application_controller) ({application_start_failure,rabbit,{{cannot_create_mnesia_dir,"/var/lib/rabbitmq/mnesia/rabbit@default-server-0.default-nodes.default/",eacces},{rabbit,start,[normal,[]]}}})

Crash dump is being written to: /var/log/rabbitmq/erl_crash.dump...done

However, if I delete my Minikube (minikube stop && minikube delete) and re-create it with a single node (minikube start --memory 8192 --cpus 4 --nodes 1) and follow the aforementioned steps to create the default RabbitMQ cluster, then there are no problems. I don't understand how adding a second node to Minikube could cause this issue.
I feel like I'm just missing something obvious, but not sure what it is.
Any sort of suggestions or feedback would be greatly appreciated. Please let me know if there are more details I should provide. Thank you in advance!

A: In typical "me" fashion, I finally found the correct phrase to search for and get results. It turns out that the storage provisioner bundled with minikube doesn't really work with 2+ nodes. Replacing it with another one (kubevirt) as explained by this GitHub issue comment allows the Pod to spin up correctly.
To add more context, in case that link goes bad someday:
I created a kubevirt-hostpath-provisioner.yaml file (contents given below) and then replaced the storage provisioner in minikube:
minikube addons disable storage-provisioner
kubectl delete storageclass standard
kubectl apply -f kubevirt-hostpath-provisioner.yaml

# kubevirt-hostpath-provisioner.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: standard
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: kubevirt.io/hostpath-provisioner
volumeBindingMode: WaitForFirstConsumer
reclaimPolicy: Delete
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: kubevirt-hostpath-provisioner
subjects:
  - kind: ServiceAccount
    name: kubevirt-hostpath-provisioner-admin
    namespace: kube-system
roleRef:
  kind: ClusterRole
  name: kubevirt-hostpath-provisioner
  apiGroup: rbac.authorization.k8s.io
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: kubevirt-hostpath-provisioner
rules:
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get"]
  - apiGroups: [""]
    resources: ["persistentvolumes"]
    verbs: ["get", "list", "watch", "create", "delete"]
  - apiGroups: [""]
    resources: ["persistentvolumeclaims"]
    verbs: ["get", "list", "watch", "update"]

  - apiGroups: ["storage.k8s.io"]
    resources: ["storageclasses"]
    verbs: ["get", "list", "watch"]

  - apiGroups: [""]
    resources: ["events"]
    verbs: ["list", "watch", "create", "update", "patch"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kubevirt-hostpath-provisioner-admin
  namespace: kube-system
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: kubevirt-hostpath-provisioner
  labels:
    k8s-app: kubevirt-hostpath-provisioner
  namespace: kube-system
spec:
  selector:
    matchLabels:
      k8s-app: kubevirt-hostpath-provisioner
  template:
    metadata:
      labels:
        k8s-app: kubevirt-hostpath-provisioner
    spec:
      serviceAccountName: kubevirt-hostpath-provisioner-admin
      containers:
        - name: kubevirt-hostpath-provisioner
          image: quay.io/kubevirt/hostpath-provisioner
          imagePullPolicy: Always
          env:
            - name: USE_NAMING_PREFIX
              value: "false" # change to true, to have the name of the pvc be part of the directory
            - name: NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: PV_DIR
              value: /tmp/hostpath-provisioner
          volumeMounts:
            - name: pv-volume # root dir where your bind mounts will be on the node
              mountPath: /tmp/hostpath-provisioner/
              #nodeSelector:
              #- name: xxxxxx
      volumes:
        - name: pv-volume
          hostPath:
            path: /tmp/hostpath-provisioner/


text:
Q: About deep packet inspection I need to clarify,Is there any way or tool to capture customized packets and protocols,like whatsapp,skype etc,.I want know is it possible to combine nDPI with libpcap.
Thank you,

A: DPI Devices from PacketLogic from procera networks have created different kind of signatures based on the different packet captures at different time-stamps used to identify the services like whatsapp, skype. In that device we can distinguish the traffics based on the services and capture the packets based on the services


text:
Q: In what circumstances would using threads benefit a sequential program? The title pretty well sums up my question. "In what circumstances would using threads benefit a sequential program"?

A: there are many reasons and its a bit complicated. So I try to be as precious as possible.
Every programm can be parallelized, but sometimes its not worth.
The Big benefit of multithreading is the usage of all cores. This can lead to an improvement of the performance. In the optimal case, having 2 cores working on a problem will double the execution-speed. But in reality this speed-up will be reduzed by the amount of overhead from the threads:
general overhead:

*

*thread start/stop

*communication/synchronization

To ignore the start-stop overhead, the life-time of the threads should be as large as possible.
The communication/synchronisation part is the main-problem. There is an an awful lot of complexity here. In short: avoid/reduce the communication between threads. Each thread should work as isolated as possible.
basically its a trade-off between the overhead and parallelism.
so the key-questions are:

*

*Do you have performance-problems?

*Do you have access to a multicore?

*Do you need the ease of stack-management (->each TCP-connection on
different thread)

*Are you willing to test multiple solutions
(sequential vs. parallel)?

for more information: https://en.wikipedia.org/wiki/Gustafson%27s_law


text:
Q: Не происходит переход в другой хэндлер после нажатия inline клавиатуры aiogram После нажатия на одну из кнопок инлайн клавиатуры никакого действия не происходит, на этой кнопке внизу справа появляются часики, которые стоят секунд 5, потом исчезают и все.
Вот мой код:
@dp.message_handler(state=FindBook.book)
async def looking_book(message: types.Message, state: FSMContext):
    answer = message.text
    if len(answer) > 200:
        await message.answer('Максимально допустимое количество символов - 200. Попробуйте снова')
        await FindBook.book.set()
    else:
        await state.update_data(book=answer)
        await message.answer('Приступаю к поиску')
        data = await state.get_data()
        result = await find_book(answer=data["book"], message=message, bot=bot)
        if result:
            await state.update_data(next_page_url=result)
            await message.answer('Какое действие совершим?', reply_markup=choice)
        else:
            await message.answer('Книг больше нет')
            await state.reset_state()

@dp.callback_query_handler(text="next_page", state=FindBook.next_page)
async def new_page(message: types.Message, state: FSMContext):
    await message.answer('Приступаю к поиску')
    data = await state.get_data()
    result = await next_page(url=data["next_page_url"], message=message, bot=bot)
    if result:
        await state.update_data(next_page_url=result)
        await message.answer('Какое действие совершим?', reply_markup=choice)
    else:
        await message.answer('Книг больше нет')
        await state.reset_state()

@dp.callback_query_handler(text="cancel", state=FindBook.cancel)
async def cancel(call: CallbackQuery, message: types.Message, state: FSMContext):
    await call.answer("Вы отменили текущую комманду")
    await call.message.edit_reply_markup()
    await state.reset_state()
    await message.answer('Для просмотра всего функционала, воспользуйтесь коммандой /help')

Клавиатура:
choice = InlineKeyboardMarkup(
                              inline_keyboard=[
                                  [
                                      InlineKeyboardButton(
                                          text="Следующая страница",
                                          callback_data="next_page"
                                      )
                                  ],
                                  [
                                      InlineKeyboardButton(
                                          text="Отмена",
                                          callback_data="cancel"
                                      )
                                  ]
                              ])

В чем может быть проблема?

A: Судя по коду, ни разу не увидел чтобы было изменение текущего стейта на FindBook.cancel или FindBook.next_page.
Получается вы на кнопку жмёте а Стейт все ещё остаётся на FindBook.book.
Чтобы ваш код заработал просто в колбеках хендлеров оставьте state=FindBook без уточнения какое именно состояние.


text:
Q: Twitter bootstrap : button with only icon inside input-append overflows past the input I couldnt make up the title clear (feel free to edit it).
So, I have included an image to show the problem.
See the Google button is at same level as input but search button is overflowing.

Error occurs only when I place just the icon-search inside button. If I replace icon with text, it fixes the problem. It has something to do with font-size : 17.5px  of .btn-large when I change it to font-size:16.5px , it works. I can hack it but I want a valid method.
Demo
Markup:

<form class="input-prepend input-append">

 Google

a

b

    <input type="text" class="input-xlarge" placeholder="Search">
    <button class="btn btn-large" type="submit">

    </button>
</form>

CSS

form .input-xlarge {
    padding: 11px 19px;
    /* equal to btn-large */
}

Edit:
Experiencing problem in,
Chrome Version 24.0.1312.57
Firefox 18.0.1
Opera 12.14
(all running in Ubuntu 12.04)

A: Bootstrap icons are more commonly used with the  tag.

I'm not saying this will fix the problem, however. This could be a browser-specific issue. I know I had issues with IE using input-append, but this is nothing a browser-specific stylesheet can't fix.
.input-append { height:19px; }
.input-append i { margin:0; padding:0; }

Edit: This doesn't appear to be an issue on Chrome. At least not for the examples given on the Bootstrap site.

A: http://jsfiddle.net/chne9/1/
.btn-large [class^="icon-"], .btn-large [class*=" icon-"] {
    vertical-align:top;
}

By default this is set to text-top - try settings just to top (edit the selector to fit just the problematic button - just to make sure you don't break any other bootstrap functionality).


text:
Q: Removing whitespace in MSSQL and trailing spaces I'm trying to remove whitespace and trailing white space from right and left side of my string in DB.
Note how the current results looklike:

Note the string named:
*excellent-purchase*

When I fetch it in my C# application like this:
ctx.Users.ToList();

The output for this string that I get is:
\t*excellent-purchase*

I need to remove this "\t" sign from my C# application either on DB level or inside the C# application.
The way I've tried it is like doing it is like this:
UPDATE
    TableName
SET
    ColumnName = LTRIM(RTRIM(ColumnName))

But I still get this \t sign in my C# app...
How can I fix this?
Edit:
guys I still have a weird characther like this:
"nl_holyland*555*

And in the C# App it looks like:
\"nl_holyland*555*

Theres an extra \ with this solution like

A: You can try it:
string value=  Regex.Replace(value, @"\t|\n|\r", "");

A: You might want to try the following:
UPDATE
    TableName
SET
    ColumnName = LTRIM(RTRIM(REPLACE(ColumnName,char(9),'')))

A: You can use the Replace also:
UPDATE
    TableName
SET
    ColumnName =  REPLACE(ColumnName, ' ', '')


text:
Q: Declarative Jenkinsfile CIFS share i have another question about the jenkins pipeline.
How can i publish the build artifacts to a windows share? In normal build jobs there is a "CIFS Publisher" post build action. But how can i use it in
post{
    success {
       //publish build artifacts
    }
}

Is there any example?

A: I've succesfully managed it in this way:
cifsPublisher alwaysPublishFromMaster: false, continueOnError: false, failOnError: false, publishers: [[
  configName: 'NAME_OF_THE_CIFS_CONFIG', transfers: [[
    cleanRemote: false,
    excludes: '',
    flatten: false,
    makeEmptyDirs: false,
    noDefaultExcludes: false,
    patternSeparator: '[, ]+',
    remoteDirectory: '$BUILD_NUMBER',
    remoteDirectorySDF: false,
    removePrefix: '',
    sourceFiles: 'myfile']],
  usePromotionTimestamp: false,
  useWorkspaceInPromotion: false,
  verbose: true
]]

A: Please use the auto generate tool in Jenkins to help you.

As you can see the highlight link. Click it.

Fill all the required value that you expected.
After scroll down and click Generate pipeline script, you will see the syntax that you need.

Last step, copy the generated script into success clause.


text:
Q: Configuring Azure Diagnostics for Azure Application Service (PaaS) My setup: Existing WCF service project modified to run as Azure Application Service (PaaS).
Originally I used log4net for my info/error logging, but it is rather cumbersome to look at those logs via FTP or SCM console. After some research I came to a conclusion that Microsoft.WindowsAzure.Diagnostics is the recommended way to handle logging in Azure apps.
Question/problem: I can't find a guide, for my scenario, on how to enable WindowsAzure Diagnostics for Application Service that is NOT created as Web/Worker Role.
The closest I got is Set-AzureServiceDiagnosticsExtension cmdlet, but it requires Role as parameter...

A:
Question/problem: I can't find a guide, for my scenario, on how to
  enable WindowsAzure Diagnostics for Application Service that is NOT
  created as Web/Worker Role.

You can't use Azure Diagnostics for your Azure Application Service. It is meant for Azure Cloud Service (Web/Worker Role) and Azure Virtual Machines.
For App Services diagnostics, please see this link: https://azure.microsoft.com/en-in/documentation/articles/web-sites-enable-diagnostic-log/.


text:
Q: basic C++ (cout buffer or overflow i think?!) ok, so im kinda new to C++ and im trying to build a basic login program. iv got it to work except for one problem... this is what iv got
void InitialLogin()
{
        cout << "\t\t   ===========LOGIN==========" << endl;
        cout << "\t\n\n\n\tUsername/>> " ;
        getline(cin, sUsername);

        cout << "\t\n\tPassword/>> ";
        getline(cin, sPassword);

    if (sUsername == "myname" && sPassword == "mypass")
     {
        cout << "\n\t\t\t--ACCESS GRANTED--";
        system("CLS");
     }
        else if (sUsername != "myname" && sPassword != "mypass")
        {
            SetConsoleTextAttribute(h, FOREGROUND_RED);
            cout << "\n\t\t\t--ACCESS DENIED--\n\n\n";
            SetConsoleTextAttribute(h, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
            main();
        }

}

after i run this, if the login was successfull i have the following run after the screen is cleard...
void Initialization()
{
    cout << "/>> Aquireing file list......" << endl;
    cout << "/>> file list aquired........" << endl;
    cout << "/>> determing file location.." << endl;

}

now my problem is, if i get the username or password wrong say once i get the initialization output twice, if i get it wrong twice, the output is three times.
i need to know how to clear the overflow or buffer or something...
please help :)

A: Your function is attempting to call main().  This is not legal C++.
You should return a status to see if the login worked or not.  Then just loop until the status either becomes "true", or the user has run out of chances.  Here is a small example:
bool InitialLogin();

int main()
{
   int numChances = 3;
   int numCount = 0;
   bool loginOk = false;
   while (numCount < numChances && !loginOk )
   {
      loginOk = InitialiLogin();
      ++numCount;
   }
   if ( !loginOk )
   {
      // number of chances ran out
      return 0;
   }
   else
   {
      // proceed.  Login was successful
   }
}

bool InitialLogin()
{
    //...
    if (sUsername == "myname" && sPassword == "mypass")
    {
        //...
        return true;
    }
    // anything here means that the login failed.  There is no need for an if()
    //...
    return false;
}

A: I feel you are getting this because you are calling the main() function when both the password and username are incorrect (As a side note you might want to change the && in this check to || as you want access to be denied if either the password or username are incorrect).
You might want to consider getting the InitialLogin() function to return a bool to show weather the login was successful or not. If not the get it to run InitialLogin() again if successful then get it to proceed with the code.
In the place where you call InitialLogin() you can use a while loop to get it to repeat.

while(!InitialLogin()){}

So when InitialLogin() is not false (bad login) it will try again and when it is not true (good login) it will continue onto next section of code.


text:
Q: Finding a subset in java I am kind of familiar with what subsets are but I am having a hard time understanding how the below got two subset? Can someone point out how we got only two subsets. I just thought it would have more subsets.
A number, m, is defined as the size of some subsets S of A where each element covers an unbroken range of integers; that is to say, if you were to sort the elements in S, the difference between any elements j and j+1 is either 0 or 1. For example A = {5, 4, 4, 8, 8} gives us a subset {4, 4, 5} and {8,8}; these subsets have m values of 3 and 2 respectively.

A: The key statement is:

the difference between any elements j and j+1 is either 0 or 1

So, for

A={5,4,4,8,8}

A is sorted and as you traverse the elements, if the current element and next element (j and j+1) are within a difference of 0 or 1 of each other, they belong to the subset.
Hence, as you traverse:
A[0]=5 and A[1] = 4 : difference 1 - add to subset {5,4}
A[1]=4 and A[2]= 4 : difference 0 - add to subset {5,4,4}

A[2]=4 and A[3] = 8: difference is 4 - Start new subset {8}
A[3] = 8 and A[4] = 8] : difference is 0 - Add to subset {8,8}


text:
Q: How do I reuse Facebook's Movie Autocomplete in my own Facebook App? On Facebook, when you go to, Edit My Profile > Arts and Entertainment, there is a "Movies" autocomplete widget that suggests movies as you type them in.
So if you type in "Jones", it will start to suggest:

*

*Indiana Jones

*Bridget Jones' Diary

*Indiana Jones and the Kingdom of the Crystal Skull

Can I reuse this widget (or its data) in my own Facebook app?
I would like to give my users the ability to create lists of movies, and I think this feature would be a lot better than having them manually type out the full names of each movie on their list.
I found one potentially relevant answer on stackoverflow ( How to consume Facebook's "autocomplete anything" suggest-style dropdown ) but the answer is 2 years old, and seems to reference an FBML tag called "typeahead" which is no longer in use.
Most searches for "Facebook autocomplete" talk about replicating the autocomplete feature for Facebook's messages, such as what is described here.  But obviously this isn't what I'm looking for, so I'm not finding any help.
If I can't reuse the exact widget that Facebook uses for this feature, is there a way I can feed the data that it draws upon into jQuery UI's autocomplete?
So far I can't find anything like this in Facebook's API, but I'd be surprised if there wasn't as I think a lot of people could use Facebook's autocomplete data in their own Facebook apps.

A: Here is the closest thing to a solution I was able to write, using jQuery UI's autocomplete widget.  This solution doesn't act as a true autocomplete, because although typing in "Indiana" will suggest "Indiana Jones", typing in "Indiana Jo" will not suggest anything.  Perhaps someone else has a better solution?
    $( "#autocomplete" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "https://graph.facebook.com/search",
            dataType: "jsonp",
            data: {
                type: "page",
                q: request.term
            },
            success: function( data ) {
                response( $.map( data.data, function( item ) {
                    if (item.category=="Movie") {
                        return {
                            value: item.name
                        }
                    }
                }));
            }
        });
    },
    minLength: 2
    });


text:
Q: WaitForMultipleObjects - how to properly handle stdin and sockets (FTP client) I am writing a simple C FTP client. I have some problems with receiving data from both FTP (21) and FTP-DATA (passive) sockets. That's my main program loop:
    input_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
    input_handles[1] = WSACreateEvent();
    input_handles[2] = INVALID_HANDLE_VALUE;
    WSAEventSelect(connection->socket, input_handles[1], FD_READ);

    while (1) {
        wait_result = WaitForMultipleObjectsEx(num_in_handles, input_handles, FALSE, INFINITE, FALSE);

        if (wait_result == WAIT_OBJECT_0) {
            fgets(input_line, input_len, stdin);
            ftp_cmd(connection, input_line);

            if (_strnicmp(input_line, "QUIT", 4) == 0) {
                WSACloseEvent(input_handles[1]);
                break;
            }
        }

        if(wait_result == WAIT_OBJECT_0 + 1 || wait_result == WAIT_OBJECT_0 + 2) {
            if (WaitForSingleObject(input_handles[1], 0) == WAIT_OBJECT_0) {
                ftp_recv(connection, &cmd_output);

                if (cmd_output != NULL) {
                    printf(cmd_output);

                    if (strncmp(cmd_output, "227", 3) == 0) { // 227 - enter passive mode
                        CHECK_ERROR(ftp_passive(connection, cmd_output, &input_handles[2]));
                        num_in_handles = 3;
                    }

                    if(strncmp(cmd_output, "226", 3) == 0) { // 226 - exit passive mode
                        ftp_passive_close(connection, &input_handles[2]);
                        num_in_handles = 2;
                    }

                    SAFE_FREE(cmd_output);
                }
            }

            if(num_in_handles == 3 && WaitForSingleObject(input_handles[2], 0) == WAIT_OBJECT_0) {
                ftp_recv_pasv(connection, &cmd_output);

                if (cmd_output != NULL)
                    printf(cmd_output);
                SAFE_FREE(cmd_output);

                // WORKS GOOD WITH THIS UNCOMMENTED
                //ftp_passive_close(connection, &input_handles[2]);
                //num_in_handles = 2;
            }
        }
    }

ftp_passive() opens a socket to the address given by server and creates WSA event (input_handles[2]). ftp_passive_close() closes this socket and event.
I have no idea why it works with the commented fragment. When it's commented, my client doesn't receive any more data from any socket.
What's wrong with my code?


text:
Q: React context is not working in typescript I have written context file AuthContext.ts.
Here is the code
/*-- imports, interfaces and defaults --*/

const AuthContext = createContext<AuthContextType>(contextDefaults);

export const useAuth = () => useContext(AuthContext);

const AuthProvider = ({ children }: AuthProviderProps) => {
  const [user, setUser] = useState<User | null>(null);

  const isLoggedIn = !!user;

  const login = (data: User) => {
    setUser(data);
  };

  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, isLoggedIn, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;

When I write return script in above code Visual Studio Code doesn't provide AuthContext in suggestions But when I use AuthProvider then it shows errors:

Thanks

A: You should declare children of type ReactNode:
import { ReactNode } from 'react';

const AuthProvider = ({ children }: ReactNode) => { ... }


text:
Q: CSS Margin trouble with Chrome? Following is the css code for body element. The problem is that if i set width to 100% then there is no margin on right side, only margin comes on left side. i tested on chrome.Also if i
do anything like 1000px the problem occurs
body {
        background:#ff00ff ;
        margin: 50px;
        width:100%;
        border:5px ;
        border : dotted;
}

A: Just remove the width: 100%; and it should be fine.
DEMO


text:
Q: Css style for  in a table doesn't work Hi i have this piece of CSS:
tbody:hover td {
   color: transparent;
   text-shadow: 0 0 3px #aaa;
}

tbody:hover tr:hover td {
   color: #444;
   text-shadow: 0 1px 0 #fff;
}

When i hover a row of a table i want that the other rows of that table become transparent. This CSS work for the normal td filled with text, but for the td filled with link(a tag) it doesn't work. I can't find why.
This is a part of the HTML code

        Untitled.txt
        File di prova
        Leggi i commenti
        Download

A: I'm not sure if it's possible to make others transparent using CSS only (CSS can not effect on previous siblings). however, you can't use :hover twice, unless you do something like this:
tbody tr:hover > td, tbody tr:hover > td a {
    color: #444;
    text-shadow: 0 1px 0 #fff;
}

In order to find a solution for the transparency issue, you may try to use nth-child() to decide which child will be changed on hover. for example:
tbody tr:nth-child(1):hover {
    color: transparent;
    text-shadow: 0 0 3px #aaa;
}

You can also decide what to do when the element is not hovered, example:
tbody tr:nth-child(1):not(:hover) {
    // If element is not hovered
    color: transparent;
    text-shadow: 0 0 3px #aaa;
}

A: This is simple. Your a tags have inline styles. Those have a high ranking in css hierarchy. So the reason why this doesn't work is this piece of code:
style='color: black;'

Remove the inline style and apply it via class instead.

A: Try using inherit property:
a {
    color: inherit !important; //important just for extra measure
}

A: I think you should put the a tag in your CSS too  .
tbody:hover td, tbody:hover td a {
  color: transparent;
  text-shadow: 0 0 3px #aaa;
}