text:
Q: how to calculate the electric power required to rotate an object from 500 gram I want pull an object (like a rabbit) over grass for teaching my dessert buzzard to catch the object. I made a machine to pull the object about a 50 meters. I can control machine with a remote controller. The machine works perfectly on a flat surface like a road with concrete.
Now I want to use the machine in the field (grass.) But the object doesn't move because the motor is too weak.
I want a speed of 8m/s.  What motor do I need?
Specifications of the object:

*

*leather

*rough surface

*oval

*30 10 10 -> lxwxh

*500 gram

Specifications of the surface:

*

*grass

*dry

*grass length = +- 5 cm

Specifications of the current motor:

*

*30 watt

*12 V DC

*3000 rpm

Can someone help me please?

A: Moving itself on grass and dragging something on grass are two different things. For moving itself you can use bigger wheels to deal with the rougher surface, but need gear down for to compensate for the increased torque requirement to maintain the same speed. But dragging something...you need a new motor. No way around that.
Coefficient for rolling friction of 0.3 is already very high and is for something like for soft wheels on a dirt road where it is light enough it won't sink in. For small wheels in tall grass it will be much higher. Larger wheels reduce the effect of roughness a bit. 5cm grass would need like...>20cm wheels
0.3 means rolling on wheels takes 30% of the pushing/pulling force of just lifting it up. Ideally you want it to be zero. At >1 it is easier to just pick the thing up rather than roll.
I laid everything out so you should only need to read it from top to bottom and look backwards for variables, never forward. I also tried to lay it out so hopefully you know where everything is coming from (as long as you have a basic understanding of power, torque, force, and friction...maybe even if you don't).
\$ m_{robot} = \$ mass of robot (kg)
\$ m_{bait} = \$ mass of bait (kg)
\$ g = \$ acceleration of gravity \$ =9.81m/s^2\$
\$ W_{robot} = \$ weight of robot (N) \$ =m_{robot}\times g\$
\$ W_{bait} = \$ weight of bait (N) \$ =m_{bait}\times g\$
\$v=\$ speed (m/s)
\$\mu_{roll}\$ = coefficient of rolling friction for wheels
\$\mu_{drag}\$ = coefficient of friction for dragged bait
\$\theta=\$ angle of incline
\$ \eta = \$ drive efficiency (between 0 and 1 for 0% to 100%). Use 1 if you need output power (or in calculations of required output like torque). Use actual efficiency if you need input power

\$ F_{roll} =\$ force of rolling friction for robot only \$=W_{\perp robot} \times \mu_{roll}=W_{robot}cos(\theta)\times \mu_{roll}\$
\$ F_{drag} =\$ force of friction dragging bait only \$=W_{\perp drag}\times \mu_{drag}=W_{bait}cos(\theta)\times \mu_{drag}\$
\$ a = \$ desired acceleration \$(m/s^2)\$
\$F_{robot.accelerate} = \$ EXTRA force required to accelerate robot \$ =m_{robot} \times [a +gsin(\theta)]\$
\$F_{bait.accelerate} = \$ EXTRA force required to accelerate bait \$ =m_{bait} \times [a +gsin(\theta)]\$

\$ r_{wheel} \$ = radius of driven wheel (m)
\$ \tau_{roll} \$ = torque required to maintain speed of just the robot \$ = F_{roll} \times r_{wheel}\$
\$ \tau_{drag} \$ = torque required to maintain speed of just the bait \$ = F_{drag} \times r_{wheel}\$
\$ \tau_{friction} = \$ torque required to overcome friction losses and keep everything moving at constant speed = \$\tau_{roll} +\tau_{drag}\$
\$ \tau_{robot.accelerate} = \$ EXTRA torque required to accelerate just the robot \$ = F_{robot.accelerate} \times r_{wheel}\$
\$ \tau_{bait.accelerate} = \$ EXTRA torque required to accelerate just the bait \$ = F_{bait.accelerate} \times r_{wheel}\$
\$ \tau_{accelerate}= \$ total EXTRA torque required to accelerate everything\$=\tau_{robot.accelerate}+\tau_{bait.accelerate}\$
\$ \tau_{total}= \$ total torque required to accelerate everything\$=\tau_{friction}+\tau_{accelerate}\$

\$ P_{robot.continuous} = \$ Continuous power to maintain speed of robot \$= F_{roll} \times v \times \frac{1}{\eta}\$
\$ P_{bait.continuous} = \$ Continuous power to maintain speed of bait \$= F_{drag}\times v \times \frac{1}{\eta}\$
\$ P_{robot.peak} = \$ Peak power to accelerate just robot \$= [F_{roll} + F_{robot.accelerate}] \times v \times \frac{1}{\eta}\$
\$ P_{bait.peak} = \$ Peak power to accelerate just bait \$= [F_{drag} + F_{bait.accelerate}] \times v \times \frac{1}{\eta}\$
\$ P_{total.continuous} = \$ Total continuous motor power required \$= P_{robot.continuous} + P_{bait.continuous}\$
\$ P_{total.peak} = \$ Total peak motor power required \$= P_{robot.peak} + P_{bait.peak}\$

Speed-dependent losses such as aerodynamic resistance or speed-dependent drive-train losses have been neglected.
You can measure the dragging force and rolling force with a pull scale and use the equations above to calculate the coefficient of friction. Accelerate slowly and smoothly when you pull or else the friction force measured will include acceleration forces. Then you can use that in other equations to figure out the power at various speeds and required torque.
All that should get you pretty close as long as you can make good friction force measurements to get good coefficients of friction. Worst case, you can assume a coefficient of 1 for rolling and dragging friction which is normally totally overkill, but with small wheels in tall grass it becomes much more reasonable. The extra power and torque would just go into acceleration.

A: Use a spring scale to measure the drag force of the rabbit on "beton" (concrete?). Do the same thing for the grass.
The ratio of these two numbers is the same as the power ratio you'll need for the motor, all other things (speed, slope, flatness, etc.) being equal.


text:
Q: How to make 3D models for Silverlight 5? I'am a .NET web developer, I really do not know anything about 3D yet. In Silverlight 5 3D API you draw stuff on the screen by code, no XAML for the 3D Objects/Models, I am wondering how 3D developers can make that cool sophisticated animated 3D games and scenes like the SL5 3D 'Windows Cafe' demo? which software is used to draw the model and make that light effects.. etc? how to import the models? how to animate them? I just want to know headlines/basics.
Now in Silverlight 2D the practices are clear, we draw everything with Expression Blend/Design or import graphics from Adobe Illustrator as XAML, then we use code and/or SL built-in animations to animate the XAML elements. What are the equivalents to make 3D with Silverlight 5?
Thank you.

A: Most 3D modeling applications support a huge number of export formats. XNA uses the .X format which is supported by most modeling tools.
Have a look at this tutorial

A: for .OBJ import from Silverlight read this article: http://silverlight.bayprince.com/tutorials.php?tutorial=11
at part 2 of that article they also show how to load textures: http://silverlight.bayprince.com/tutorials.php?tutorial=13
at the sidebar on the left, they seem to have more articles on Silverlight 3D that may be interesting

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to put a image as a background in wxpython How to add background image to panel1? Which command is there?
Code:
import wx
import wx
appy=wx.App()

class cg(wx.Frame) :
     def __init__(self,parent,id) :
         wx.Frame.__init__(self,parent,id,'GPA',pos=(1000,600),size=(600,400))
         #splitter = wx.SplitterWindow(self, -1)
         panel1 = wx.Panel(self)
         panel2 = wx.Panel(panel1, -1,size=(600,200),style=wx.BORDER_SUNKEN)
         panel3 = wx.Panel(panel1, -1,pos=(0,200),size=(600,200),style=wx.BORDER_SUNKEN)
         #panel3=wx.panel(panel1,-1,pos=(300,200),size=(600,200),style=wx.BORDER_SUNKEN)
         #panel13 = wx.Panel(panel1, -1, style=wx.BORDER_SUNKEN)
         #panel13 = wx.Panel(panel1, -1, style=wx.BORDER_SUNKEN)
         #panel13 = wx.Panel(panel1, -1, style=wx.BORDER_SUNKEN)

         #button1=wx.Button(panel1,label='exit',pos=(10,10),size=(10,10))
         #self.cnt1=wx.TextCtrl(panel1,pos=(40,60),size=(120,30))

if __name__=='__main__' :

     app=wx.PySimpleApp()
     frame=cg(parent=None,id=-1)
     frame.Show()
     app.MainLoop()

A: The corrected example from The Mouse vs. The Python.
import wx

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Was wx.BG_STYLE_CUSTOM)
        self.frame = parent

        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        for num in range(4):
            label = "Button %s" % num
            btn = wx.Button(self, label=label)
            sizer.Add(btn, 0, wx.ALL, 5)
        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)
        self.SetSizer(hSizer)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    #----------------------------------------------------------------------
    def OnEraseBackground(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()

        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("butterfly.jpg")
        dc.DrawBitmap(bmp, 0, 0)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, size=(600,450))
        panel = MainPanel(self)
        self.Center()

########################################################################
class Main(wx.App):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, redirect=False, filename=None):
        """Constructor"""
        wx.App.__init__(self, redirect, filename)
        dlg = MainFrame()
        dlg.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = Main()
    app.MainLoop()

A: A simple search would have brought you to this answer from The Mouse vs. The Python.
# create a background image on a wxPython panel
# and show a button on top of the image

import wx

class Panel1(wx.Panel):
    """class Panel1 creates a panel with an image on it, inherits wx.Panel"""
    def __init__(self, parent, id):
        # create the panel
        wx.Panel.__init__(self, parent, id)
        try:
            # pick an image file you have in the working folder
            # you can load .jpg  .png  .bmp  or .gif files
            image_file = 'roses.jpg'
            bmp1 = wx.Image(image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
            # image's upper left corner anchors at panel coordinates (0, 0)
            self.bitmap1 = wx.StaticBitmap(self, -1, bmp1, (0, 0))
            # show some image details
            str1 = "%s  %dx%d" % (image_file, bmp1.GetWidth(), bmp1.GetHeight())
            parent.SetTitle(str1)
        except IOError:
            print "Image file %s not found" % imageFile
            raise SystemExit

        # button goes on the image --> self.bitmap1 is the parent
        self.button1 = wx.Button(self.bitmap1, id=-1, label='Button1', pos=(8, 8))

app = wx.PySimpleApp()
# create a window/frame, no parent, -1 is default ID
# change the size of the frame to fit the backgound images
frame1 = wx.Frame(None, -1, "An image on a panel", size=(350, 400))
# create the class instance
panel1 = Panel1(frame1, -1)
frame1.Show(True)
app.MainLoop()


text:
Q: Chrome browser - "Only local connections are allowed" - browser launches properly but test cases stops and URL is empty When the tests starts and I run Chrome browser using WebDriver version 85. I get the following message in console.
Starting ChromeDriver 85.0.4183.83 (94abc3121ae0c9a4cb5f035431c8adfb13245875-refs/branch-heads/3142@{#2321}) on port 46427
Only local connections are allowed.

Chrome does launch but when this is triggered in console, the test fails and stops and URL in browser is set to "data:,"
This is my dependency in pom file, and I am using Chrome version 85
<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.141.59</version>
    </dependency>


text:
Q: Check whether for a set of $n$ lines in 3D space, no two lines intersect – without testing each pair of lines Given a set of lines in 3D space I want to determine whether no pair of lines intersect. Trivially, this can be done by checking each pair of lines. My question is if there is a way to avoid having to check each pair.
Or, in other words: Does there exist an algorithm that tests a set of $n$ lines in 3D space for intersections in time less than $O(n^2)$?

For Context: This is motivated by line segment intersection in 2D-space, where we naively can check all pairs of line segments, but in fact, there exists an output-sensitive algorithm that exploits the property that intersections can only occur between segments that are at some point sufficiently close to each other.
Therefore, I wonder if for a set of lines in 3D space there is no way to exploit locality in a similar way resulting in only having to test lines that are sufficiently close to each other at some point? I spent the whole day researching this topic but could not find much on it - neither any hints on possible solutions nor explanations why this is impossible. I would be happy to receive either of both.


text:
Q: Can't insert null The problem is that I have a form where I insert services into each record by entering service code. Services exist in a table called t_services. When I insert a service and save it, it is inserted in another table called s_services(my block).
If I'm inserting a service that doesn't exist an exception will be thrown.
Then I try to save after I've undone the service that doesn't exist but a message shows telling me that I can't insert a null value.
I know that because the service is a primary key, but why can't I save even if the record is null while the cursor is still on the record that I don't want to add a value to it?
Thanks


text:
Q: abstract api call and try catch block into one common method in JavaScript to make it more reusable export const getDatilsCall = async (testId) => {
  try {
    const resp = await axiosInstance.get(
      getUrl(DETAILS, { urlParams: { testId } })
    );
    return resp.data;
  } catch (err) {
    throw handleExceptions(err);
  }
};

export const getDefaultCall = async (productId) => {
  try {
    const resp = await axiosInstance.get(
      getUrl(DEFAULT, { queryParams: { productId } })
    );
    return resp.data;
  } catch (err) {
    throw handleExceptions(err);
  }
};

Let's say there is one api.js file which includes above methods, "getUrl" and "handleExceptions" have been abstracted already and I can use them directly. But it seems like for each api call, we need to duplicate try catch block includes "await axiosInstance.get" "return resp.data" and etc...
Do you guys think whether we need to abstract try catch block for above methods or the current way is good enough. Thanks.
update my question based on the comments. What about I remove the try/catch and use try/catch on top level but how I can handle error part? Do I need to  throw handleExceptions(err) on top level?
    export const getDefaultCall = async (productId) => {

        const resp = await axiosInstance.get(
          getUrl(DEFAULT, { queryParams: { productId } })
        );
        return resp.data;

    };

A: I reviewed your post updated and I think that there is two alternatives

*

*If you want manage particular error, about call axios or other code in your function, you can have "try catch" in your function getDefaultCall, for example:

 export const getDefaultCall = async (productId) => {
  try {

    const resp = await axiosInstance.get(
      getUrl(DEFAULT, { queryParams: { productId } })
    );

    // await anythings

    // await anythings

    return resp.data;
  } catch (err) {
    // manage special error, like custom message, or response structure json for other error manager
  }
};

but,

*If you only want manage error, you can remove "try catch" in getDefaultCall and control your errors in top level

export const getDefaultCall = async (productId) => {
  const resp = await axiosInstance.get(
    getUrl(DEFAULT, { queryParams: { productId } })
  );
  return resp.data;
};

// use

something() {
  try {
    // if getDefault Call fail, jump auto to catch
    const data = await getDefaultCall();

  } catch (err) {

  }
}


text:
Q: "scoring must return a number" cross_val_score error in scikit-learn Maybe it is a dumb question, but I don't understand the error that the function cross_val_score in the code below give me. Perhaps the answer is in the format of X sample, seeing that this is exactly what was shown in the crash message, but I don't know how to fix.  This is a piece of code from my project with some random values.
import numpy as np
from sklearn import mixture,cross_validation

np.random.seed(0)
n_samples = 300
C = np.array([[0., -0.7], [3.5, .7]])
X = np.r_[np.dot(np.random.randn(n_samples, 2), C),
          np.random.randn(n_samples, 2) + np.array([20, 20])]

clf = mixture.GMM(n_components=2, covariance_type='full')
score = cross_validation.cross_val_score(clf, X)

Gives me the error:
ValueError: scoring must return a number, got (<type 'numpy.ndarray'>) instead

A: I think this may be an issue in scikit. cross_val_score ultimately makes a call to the score function for whatever estimator is passed to it. Typically, score (e.g. in KMeans) returns a float. And when a KMeans estimator is passed to cross_val_score, all is well:
>>> clf = cluster.KMeans()
>>> score = cross_validation.cross_val_score(clf, X)
# (no error)

Note the return type of score:
>>> clf = cluster.KMeans()
>>> clf.fit(X)
>>> type(clf.score(X))
numpy.float64

When score is called on a GMM an array is returned.
>>> clf = mixture.GMM()
>>> clf.fit(X)
>>> type(clf.score(X))
numpy.ndarray

Because cross_val_score is relying on clf.score() returning a float, the error message you see would make sense.
A workaround is to supply cross_val_score with your own scorer. For example, to take the average of the scores returned by GMM.score(), create this scoring function:
>>> scorer = lambda est, data: np.mean(est.score(data))

Then you can pass this scorer as an argument to cross_val_score:
>>> score = cross_validation.cross_val_score(clf, X, scoring=scorer)

This avoids the error, and I think should more or less do what you're looking for. I'm not sure if the mean is necessarily the best way to summarize the scores, though it seems reasonable enough. But from here you can define your own method.


text:
Q: Global variables joke
What's the best naming prefix for a global variable?
//

I saw this joke on the wall in my CS lab and, being fairly inexperienced in C++, didn't get it.
Could someone explain it to me?

A: // means that the rest of the line is a comment. Global variables are generally seen as poor design, so the joke is that the best thing to do with global variables is to get rid of them.


text:
Q: RAID level 0 benifits
Possible Duplicate:
RAID 0 performance gains?

What exactly is the (hypothetical) performance gain with RAID level 0? Does it essentially double all the specs of the single hard drive or is does it work differently?

A: It doubles the sequential read and write speeds. Latency for small reads or writes is generally unaffected.

A: Theoretically it would double speeds but in practice it generally falls somewhere short of that. As with other similar RAID levels, RAID0 benefits from the multiple-spindle effect where reads/write speeds are increased purely based on the fact that the additional spindles give additional simultaneous sector access.


text:
Q: Variable values set inside getJSON or ajax are not synchronous outside the function It seems to be the same issue posted in these threads jQuery getJSON save result into variable and Variables set during $.getJSON function only accessible within function. However, it didn't work after applying the solutions to them.
That is,
var a = "";
$.getJSON(url, callbackFuncWithData);

function callbackFuncWithData(data) {
  a = "something";
}

console.log(a); // the output is ""

and
var a = "";
$.ajax({
  Type: "GET",
  url: url,
  async: false,
  dataType: "json",
  success: function(data) {
    a = "something";
  }
});

console.log(a);  // output ""

It's a chanllenge from FreeCodeCamp, here is my pen if you wish to view the code https://codepen.io/MonikaDiao/pen/xjYwJV. I managed to make it work by doing all the operations inside the getJSON function. But the function is called inside a forEach loop. It would be better to set the final html outside the loop. I simply could figure out why it doesn't work as expected. Does the loop also introduce synchronous problem?


text:
Q: css3 slideup slide down How do I style an element with css transitions so that it would slide up / down / left / right when hidden?
.hideUp {
  transition: .5s;
  display:none;
}
.hideLeft {
  transition: .5s;
  display:none;
}

I want to add the class to an element and have it slide left and disappear. Thanks!

A: You may wanna check the following article which contains content sliding demos:
Using CSS3 Transitions, Transforms and Animation

A: You'll have to use multiple browser specific property (moz-transition, webkit-transition...)
A good explanation of how to use them is there: https://developer.mozilla.org/en/CSS/CSS_transitions
for your case that'll be something like
.showUp {
  transition:height .5s;
  height:50px;
  overflow:hidden;
}
.showLeft {
   transition:width .5s;
   width:0px
   overflow:hidden;
}
.showUp.hideUp {
  height:0px
}
.showLeft.hideLeft {
   width:50px
}

And toggling hideUp and hideLeft classes to do a transition.

A: You can't use display:none with transitions. It will cause the transition to just jump from one state to the other without animating it.
This fiddle uses top to move the element. It animates.
http://jsfiddle.net/R8zca/4/
This fiddle uses display:none. It doesn't animate.
http://jsfiddle.net/R8zca/5/
If you want to animate an element hiding you can use z-index, opacity, position or visibilty. Here's the list of animatable properties: http://www.w3.org/TR/css3-transitions/#animatable-properties-


text:
Q: Copy files limited to 50GB or so? Several times I have tried to copy a vhd file from one HDD to another one colocated in the same physical box and connected to the same motherboard.
GUI drag and drop, Powershell, copy and paste - all of these methods stop copying after about 50GB of transferred data.
Are there any data transfer limits?

A: The file size limit for NTFS5 is about 16 ExaBytes, your files are not that big, because you couldn't store them in the first place.
There is no limit on the copy operation itself and I often copy files bigger than 500GB.
Sounds like a hardware problem to me. Test copying the file within the same HDD or to a different one to find out which drive has the problem.


text:
Q: Is there a v-cloak inverse? According to VueJS documentation, v-cloak "directive can be used to hide un-compiled mustache bindings until the Vue instance is ready.". In other word, I can hide a div or something like that, and it will be displayed when vue is ready.
Does VueJS provides its inverse? Something that hides until VueJS is ready?

A: There plenty of solutions, I think another one will be to use v-if with a false property in data like:

Loading Vue....

vue loaded

A: As simple as:

Will be visible until vue is mounted/ready...

Work for all versions.
The element has to be inside your container... if you use to hide your master container, change it that way:

Visible while loading...

Visible when ready...


text:
Q: How Django set path to files In a django project, I want to open a file "file.png" (from images folder) in "worker.py".

*

*worker.py

*images

*
*

*file.png

*
*

*otherfile.png

It works well using the terminal, but when the server call this function I get this error:
[Errno 2] No such file or directory: "images/file.png"
So my question is, where django set relative path?
Where should I put file.png to get it in worker.py using open() function?
Thanks

A: You can use absolute path, in work.py you can define current path by
current_path = os.path.dirname(__file__)
image_folder = os.path.join(current_path, images)

and then you can access the file with file name,
os.path.join(image_folder, xxxx.png)

A: The following works for me. Add this in the python.py file to perform this task with files:
os.path.join(settings.BASE_DIR,'File_Name.csv')


text:
Q: How can I use bind9 to use my own custom domain in my LAN? I'm new to DNS and making a DNS server. I've read through the bind9 server how to (at https://help.ubuntu.com/community/BIND9ServerHowto) and several tutorials online on setting up a bind9 server in ubuntu. I haven't gotten any of them to work yet.
I'm trying to get fivestones.desonia to resolve to my computers LAN ip address of 192.168.1.139.
My named.conf.options file:
options {
    directory "/var/cache/bind";

    // If there is a firewall between you and nameservers you want
    // to talk to, you may need to fix the firewall to allow multiple
    // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

    // If your ISP provided one or more IP addresses for stable
    // nameservers, you probably want to use them as forwarders.
    // Uncomment the following block, and insert the addresses replacing
    // the all-0's placeholder.

    forwarders {
            8.8.8.8;
            8.8.4.4;
    };

    //========================================================================
    // If BIND logs error messages about the root key being expired,
    // you will need to update your keys.  See https://www.isc.org/bind-keys
    //========================================================================
    dnssec-validation auto;

    auth-nxdomain no;    # conform to RFC1035
    listen-on-v6 { any; };
};

My named.conf.local file:
#//
#// Do any local configuration here
#//

#// Consider adding the 1918 zones here, if they are not used in your
#// organization
#//include "/etc/bind/zones.rfc1918";
zone "fivestones.desonia" {
  type master;
  file "/etc/bind/zones/db.fivestones.desonia";
};

zone "1.168.192.in-addr.arpa" {
    type master;
    notify no;
    file "/etc/bind/zones/db.192";
};

my /etc/bind/zones/db.192 file:
;
; BIND reverse data file for local loopback interface
;
$TTL    604800
@       IN      SOA     ns.fivestones.desonia. root.fivestones.desonia. (
                 2013012113         ; Serial
                     604800         ; Refresh
                      86400         ; Retry
                    2419200         ; Expire
                     604800 )       ; Negative Cache TTL
;
@       IN      NS      ns.
10      IN      PTR     ns.fivestones.desonia.

my /etc/bind/zones/db.fivestones.desonia file
;
; BIND data file for local loopback interface
;
$TTL    604800
@       IN      SOA     ns.fivestones.desonia. root.fivestones.desonia. (
                 2013012110         ; Serial
                     604800         ; Refresh
                      86400         ; Retry
                    2419200         ; Expire
                     604800 )       ; Negative Cache TTL
;
@       IN      NS      ns.fivestones.desonia.
ns      IN      A       192.168.1.139
server  IN      A       192.168.1.139
www     IN      A       192.168.1.139

I sudo service bind9 restart and then this is my tail -f /var/log/syslog:
Jan 21 23:47:25 media-server named[16726]: command channel listening on 127.0.0.1#953
Jan 21 23:47:25 media-server named[16726]: command channel listening on ::1#953
Jan 21 23:47:25 media-server named[16726]: zone 0.in-addr.arpa/IN: loaded serial 1
Jan 21 23:47:25 media-server named[16726]: zone 127.in-addr.arpa/IN: loaded serial 1
Jan 21 23:47:25 media-server named[16726]: zone 1.168.192.in-addr.arpa/IN: loaded serial 2013012113
Jan 21 23:47:25 media-server named[16726]: zone 255.in-addr.arpa/IN: loaded serial 1
Jan 21 23:47:25 media-server named[16726]: zone fivestones.desonia/IN: loaded serial 2013012110
Jan 21 23:47:25 media-server named[16726]: zone localhost/IN: loaded serial 2
Jan 21 23:47:25 media-server named[16726]: managed-keys-zone ./IN: loaded serial 2
Jan 21 23:47:25 media-server named[16726]: running

But when I try to host -l fivestones.desonia I get
; Transfer failed.
Host fivestones.desonia not found: 9(NOTAUTH)
; Transfer failed.

And if I try to ping fivestones.desonia I get ping: unknown host fivestones.desonia.
If I host google.com I get
google.com has address 74.125.227.96
google.com has address 74.125.227.97
google.com has address 74.125.227.98
google.com has address 74.125.227.99
google.com has address 74.125.227.100
google.com has address 74.125.227.101
google.com has address 74.125.227.102
google.com has address 74.125.227.103
google.com has address 74.125.227.104
google.com has address 74.125.227.105
google.com has address 74.125.227.110
google.com has IPv6 address 2607:f8b0:4000:800::1004
google.com mail is handled by 20 alt1.aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.

so at least that's working. But host fivestones.desonia does nothing.
If I dig fivestones.desonia I get
; <<>> DiG 9.8.1-P1 <<>> fivestones.desonia
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57727
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;fivestones.desonia.        IN  A

;; AUTHORITY SECTION:
fivestones.desonia. 604800  IN  SOA ns.fivestones.desonia. root.fivestones.desonia. 2013012110 604800 86400 2419200 604800

;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jan 21 23:51:40 2013
;; MSG SIZE  rcvd: 80

...which seems like it's working. But it doesn't work.
And finally if I wget fivestones.desonia (the computer is running apache) I get
Resolving fivestones.desonia (fivestones.desonia)... failed: Name or service not known.
wget: unable to resolve host address `fivestones.desonia'

What am I doing wrong? Or what other info would you need to help me figure this out?
Thanks so much!

A: 'fivestones.desonia' is not a host name in your setup.  Try the following instead.
ping www.fivestones.desonia

A: Has been followed your guide completely and get everything working :)
command host -l fivestones.desonia
should return you all host in your dns zone.
check your config with sudo tail -f /var/log/syslog
to see if no any errors
most possible error you make have with your config is no "zones" subfolder in your bind config, you need to create one or remove it from your paths.
Everything else is correct and working!

A: ns      IN      A       192.168.1.139
server  IN      A       192.168.1.139
www     IN      A       192.168.1.139

Multiple A records for the same IP address is not generally good practice.
Choose one name for the host, the "canonical" name" and then create CNAME "alias" records for the alternative "service" names (eg ns, ftp, www) to that canonical name, as in
server      IN      A       192.168.1.139

and
ns      CNAME   server
ftp     CNAME   server
www     CNAME   server

Then when you move a service to a second server, you add an A record for that server2 and just change to the CNAME entry to point to the second host name, eg
ftp     CNAME  server2

Similarly one should just have a single PTR record in the reverse zone file pointing to the canonical name.
$ORIGIN     1.168.192.in-addr.arpa.

139         PTR    server.fivestones.desonia.

(Note the essential trailing period on the PTR entry.)
Good DNS practice means being able to do reverse lookups as well!


text:
Q: Positive Pay Service option is not available Positive pay service option is not available in my AX environment. It is mention in the tech-net site that you can set outbound port for Positive pay from System administration > Setup > Services and Application Integration Framework > Positive pay service > Outbound ports for positive pay.
But it is not listed in my environment. From where i can get this option.

A: It is there in AX 2012 R2 CU7. You need to check the version of your AX, it shouldn't be lower than AX 2012 R2 CU6.


text:
Q: How to launch .bat file after Gradle build. Sign and reinstall app from .bat I was struggling with a problem where I wanted to use Gradle to execute .bat script after .apk build that signed the application with platform key, and reinstalled it on the device.

A: Folder structure

*

*File instruction.bat content

java -jar "..\app\build\outputs\apk\signapk.jar"
  "..\app\build\outputs\apk\platform.x509.pem"
  "..\app\build\outputs\apk\platform.pk8"
  "..\app\build\outputs\apk\app-debug.apk"
  "..\app\build\outputs\apk\signed.apk"
adb install -r "..\app\build\outputs\apk\signed.apk"
adb shell am start -n
  com.your.package/com.your.package.MainActivity

*Add this to your build.gradle -

task signAndInstall(type: Exec) {
      def finalPath = projectDir.toString() + '\build\outputs\apk\instruction.bat'
      commandLine = [finalPath] }
android {
      applicationVariants.all { variant ->
          variant.assemble.doLast {
              signAndInstall.execute()
          }
      } }


text:
Q: How can I share a link to facebook using native app on browser I want to make a button sharing a link to facebook on android mobile web site via native facebook app.
I found "fb://publish" url can open native app.
but I couldn't find How to send image, title, description like meta tag information to native app.
If anyone know how to do this, please let me know
thanks.


text:
Q: CSS to apply if 2 elements exist Given the following HTML markup, I want to apply (S)CSS only when 2 of the same elements exist (not when 1 exists).
I don't want to use JavaScript to count the number of elements and apply another class, however, I feel this is the only approach.
div {
  a + a {
    // I want to apply styles to both a tags, not just the second one
    // WHEN 2 a tags exists
  }
}

  Home
  About

A: You can use "quantity queries". For exactly TWO...
a:nth-last-child(n+2):nth-last-child(-n+2):first-child,
a:nth-last-child(n+2):nth-last-child(-n+2):first-child ~ a {

}

Source: https://quantityqueries.com/

a:nth-last-child(n+2):nth-last-child(-n+2):first-child,
a:nth-last-child(n+2):nth-last-child(-n+2):first-child~a {
  color: red
}

  Home
  About

  Home

  Home
  About
  More

A: UPDATE: the initial question stated "2 or more of the same elements exist" but was updated later ...
You can do it like below:

a:first-child:nth-last-child(n + 2),
a ~ *{
  color:red;
}

  Home About

  Home About Home About

  Home

Or like below too:

a:not(:only-child){
  color:red;
}

  Home About

  Home About Home About

  Home

A: are you using pre-compilor?
then

div a:nth-child(n+2) {
  background: red
}

  Home
  About

For Scss, following code should work
div {
   & a:nth-child(n+2) {
    // css instruction
  }
}


text:
Q: Center text with higher z-index than image below (CSS) I have several divs with imgs embedded. I want to put text in these divs but the text shall be above the images. So I wrote the following code:
#headline-div {
z-index:100;
position:absolute;
text-align: center;
}
#divbgs1 {
z-index:1;
position:relative;
}

Willkommen auf den Rook Islands...

but now the text is left to the image and i am unable to center it.
Link to the page: http://bit.ly/1i7j47A
Kind regards

A: First of all you have class="divbgs1" in your html, but in your css you put #divbgs1 instead of .divbgs1. I'm going to assume you meant for it to be a class.
.divbgs1 {
    text-align: center;  //add this
    z-index: 1;          //remove this
    position: relative;
    padding: 10px;       // you might want to add a padding, adjust accordingly
}

.divbgs1 img {
     position: absolute;
     top: 10px; //adjust these accordingly
     left: 10px; //adjust these accordingly
}

A: You can put the #headline-div inside the div with the image, like so

        Willkommen auf den Rook Islands...

then absolutely position the #headline-div like this
#headline-div {
  z-index: 100;
  position: absolute;
  text-align: center;
  width: 100%;
  margin-top: 50%;
}

or
you could just add
#headline-div {
   width: 100%;
}

to center the text horizontally, vertical centring requires some more effort though.


text:
Q: Return of a func Consider this code:
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    Rectangle() {}
    Rectangle (int x, int y) : width(x), height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);
};

Rectangle duplicate (const Rectangle& param)
{
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;
}

int main () {
  Rectangle foo;
  Rectangle bar (2,3);
  foo = duplicate (bar);
  cout << foo.area() << '\n';
  return 0;
}

There is a friend function in line 14. this function declares an object inside its body. and at the the end returns that object. Now I wonder if the return of this function is an rvalue or lvalue?

A:
I wonder if the return of this function is an rvalue or lvalue?

It is an rvalue. From value category:

The following expressions are prvalue expressions:

*

*a function call or an overloaded operator expression, whose return type is non-reference...

This means that the call expression duplicate (bar) is an rvalue.

Also note that res itself is an lvalue expression.

A: Please keep it in mind that value category is a property of an expression, not "a value".
res, as an id-expr, is lvalue. However, the duplicate (bar) function call expression is a rvalue, for all the functions calls returning non-reference are prvalues.


text:
Q: Error in as.Date.default(e2) : do not know how to convert 'e2' to class "Date" I am trying to get a new month's start date with mutate from dplyr. The function worked perfectly last night and now out of the blue I get the following error:
Error in as.Date.default(e2) :
  do not know how to convert 'e2' to class "Date"

I never heard or read anything about "e2". Below my code and the head of my data:
CT_inact_months <- CT_inact_months %>%
  mutate(new_start_date = if_else(forced_start == newmonth, as.Date(start), as.Date(paste0(newmonth, "-01"))))

> head(CT_inact_months)
# A tibble: 6 × 8

 camera start               end                 forced_start forced_end name   newmonth  Year
  <chr>  <dttm>              <dttm>              <date>       <date>     <chr>  <I<chr>> <dbl>
1 K_A03  2019-02-19 22:43:00 2019-02-20 08:12:00 2019-02-01   2019-02-01 Month1 2019-02   2019
2 K_A03  2019-05-01 21:07:00 2019-05-02 23:44:00 2019-05-01   2019-05-01 Month1 2019-05   2019
3 K_A03  2019-08-07 02:58:00 2019-08-08 12:53:00 2019-08-01   2019-08-01 Month1 2019-08   2019
4 K_A03  2019-09-17 02:16:00 2019-11-11 06:56:00 2019-09-01   2019-11-01 Month1 2019-09   2019
5 K_A03  2019-09-17 02:16:00 2019-11-11 06:56:00 2019-09-01   2019-11-01 Month2 2019-10   2019
6 K_A03  2019-09-17 02:16:00 2019-11-11 06:56:00 2019-09-01   2019-11-01 Month3 2019-11   2019

I tried to supply as.Date with the "origin" as I thought that might be the issue.
Also the as.Date parts of the code work on their own as I tried them separately.


text:
Q: 230 and 240 transformer leads So I have a transformer that is like 230 || 30 V.
One thing I don't get that on primary side it has the following leads:
0 --- 230V --- 240V
When it can be useful? I mean I can't think of situation when somebody would say "We should wire it to 240V, 230V will be a bad choice".
Isn't it hard to know what exact value particular wall outlet will be outputing? I always though that in one house it can be 230, then you go to the different city and it's 240, not to mention it is never precise, so you can get like 235.  Moreover regular customer doesn't know what he has in the outlet.
What is the reason that manufacturer decided to have two options?
I've never seen a 230/240 switch on any device either. And bonus question - if you already decided to make such a primary side - why not make 220V also?
I tried google this and all the answers were like "there is no difference, don't bother", but I suppose manufacturer would not make it such a way if it wouldn't have an application.

A: This type of multi-tap transformer primary was common before the days of regulated DC power supplies. The user was supposed to select the appropriate tap according to local mains voltage. Variations from 210V to 250V were common, in European radios, TVs, tape recorders and the like. Old test equipment like scopes also had this type of voltage selection.
I've seen a 1957 valve radio with such a tapped primary, and it was set to the wrong one. The secondary AC voltage was low, and that meant that the rectified DC was low, too. We changed to the correct tap, and the voltages came up to levels much closer to the nominal voltages in the schematic. The radio worked a lot better like that!

A: It's precisely because of that inaccuracy in the supply voltage that you may want such a transformer.
By itself it's pretty useless, but with active voltage monitoring, and a method for switching automatically from the 240V to the 230V tap a power supply is able to compensate for brownouts, etc.
The same technique is used in many UPS systems for compensating for brownouts, though they often have more than just one extra tap.

A: This kind of transformer would normally be permanently wired to the correct voltage tap for the target market (country) and the unused tap left open. Adding a tap only costs pennies,and it provides a bit of optimization (especially for something like an audio amplifier that may not be able to meet the advertised performance without the proper tap connection). It could thus run afoul of truth-in-advertising laws in a market with a lower nominal mains voltage, or run a bit hot in a market with a higher nominal mains voltage.
It was not unusual to have mains transformers with taps for 100/120/200/230/240 VAC before switching supplies became common.

A: You may have a transformer that was built for use during the time when Europe was standardizing the line voltage.
Up until 1995, various countries in Europe used different line voltages for the outlets.  For example, in Germany it was 220V, but in the UK it was 240V.
In 1995 (Mains voltage wikipedia ), they all began switching to 230V ,and were supposed to have completed the switchover by 2008.  So, you may have a transformer that was built to be installed into a device and used when the line voltage was 240V, but could then be switched (switch or jumper) to use the lower voltage after the changeover.
Here in Germany in the early 1990's I used a big test rig for two way radios that had a switchable supply voltage - it was adjustable from like 210V up to 250V.  I also own an oscilloscope that was built in 1967 that has a jumper on the back to switch between 110V and 220V - with various jumper positions for voltages from 220V up to 250V (or something like that I don't have it memorized.)


text:
Q: Retaining and identifying elements in an array which satisfy a threshold in MATLAB I have a matrix (about 342 by 342) denoted by C_{ij} and I want to identify all indices i,j which satisfy the condition C_{ij} > rho where rho is some fixed value. I am using MATLAB
For example, if I have the matrix C_{ij} as:
C = 1     0.7    0.8
    0.7   1      0.5
    0.8   0.5    1

And rho = 0.6 then the indices which satisfy the condition C_{ij} > 0.6 are i,j = 1,2 as C_{11}=C_{22}=1 and C_{12}=C_{21}=0.7
But note that i,j=3 does not satisfy this condition since although C_{13}=C_{31}=0.8, C_{23}=C_{32}=0.5
I am not sure how/the best way to do this is in MATLAB?

A: C = rand(342,342);
rho = 0.6;
res = C(C>rho); %// contains all values that are above the threshold
[row,col,val] = find(res); %// returns the indices.

row would contain your i, col your j, but I'd caution against using i or j as a variable. val contains the corresponding value, but you can omit that for freeing RAM, as you can use C(row,col) as well to get the values.
If your matrix is symmetric you can use that:
[rowt,colt,val] = find(triu(C)>rho); %// find only in the upper triangle
row = [rowt;colt]; %// flip rows and columns to obtain all results
col = [colt;rowt]; %// flip rows and columns to obtain all results

For your edit:
IdxR = find(diff(unique(rows))==1,1,'first');
IdxC = find(diff(unique(columns))==1,1,'first');
Result = C(1:IdxR,1:IdxC);


text:
Q: How do I make one service dependent on another in Windows 7? If I view properties for a service, I can see the "Dependencies" tab, but I can't assign other services to this tab.
I have two services that start on startup, a server and a database. The server depends on the database - if the db hasn't started, the server doesn't work. (However, it does actually fail as a service, so I can't use the Recovery tab.)
How do I make the second service dependent on the first service, so that they always start up in the correct order?

A: Following the steps here worked perfectly for me:
Boyce.us
Long story short:
regedit.exe, HKLM/System/CurrentControlSet/Services/(your service)
Add a multi value key named DependOnService
Add the dependency service name

A: From a command prompt running with admin credentials:
sc config <server_service_name> depend= <database_service_name>
Read more at this sc.exe documentation.


text:
Q: I am not able to click on checkbox as there is no tag present for that checkbox Checkbox is present inside label with link of terms of use

I agree to the
Terms of Use.

previously i was able to click on checkbox but now its clicking on link of terms of use
I have used following xpath to locate checkbox
I_AGREE_CHECKBOX = By.xpath("//div[@class='account-information']/fieldset[2]/ul/li[2]/span[1]/label");

and
I_AGREE_CHECKBOX = By.xpath("//*[contains(text(), 'I agree to the')]");

Please give me some idea so that i can click on checkbox only not on Terms of use
Thanks in advance

A: Try using the following expression:
//*[text()[contains(.,'I agree to the'))]]


text:
Q: Screen sharing without waking up screen (Macbook connects to iMac) Basically I need this but for 2022:
How to Screen Sharing / VNC to an iMac without waking the display?
I connect from my Macbook Pro to my iMac in the office. I need to have the iMac screen off because I work with confidential data and I don't want people in the office see what I am doing from home with my Macbook pro. I have MacOS Monterrey in both endpoints.


text:
Q: Integrating with repsect to x Given the function
\begin{equation}
f(x)=\left(\int_{0}^{x} e^{-u^2} du\right)^2
\end{equation}
Differentiating with respect to $x$ gives:
\begin{equation}
f'(x)=2\left(\int_{0}^{x} e^{-u^2} du\right)e^{-x^2}
\end{equation}
I understand the first part $2\left(\int_{0}^{x} e^{-u^2} du\right)$ but I cannot understand why we added the second term $e^{-x^2}$. Can anyone explain?

A: Hint
Let $$G(x)=\int_0^x e^{-u^2}\mathrm dx=\int_0^x g(u)\mathrm du.$$
You have that $$f(x)=G^2(x).$$
Therefore $f'(x)=2G(x)G'(x)$ and by definition, $G'(x)=g(x)$. I let you conclude.


text:
Q: Deploy WSO2 API Manager in existing tomcat I already have tomcat running, can I only have war file of WSO2 API Manager to deploy on the server?

A: No. This is not possible as we have many config files and dependencies with api-manager which are required at runtime.
API manager is a server and it is not a webapp.


text:
Q: C++ - Enumeration range? Bjarne Stroustrup book I am reading C++ programing language - of Bjarne S.
On page 77, section 4.8 I find this:
"An enumerator can be initialized by a constantexpression
(§C.5) of integral type (§4.1.1). The
range of an enumeration holds all the enumeration's enumerator values rounded up to the nearest
larger binary power minus 1 . The range goes down to 0 if the smallest enumerator is nonnegative
and to the nearest lesser negative binary power if the smallest enumerator is negative. This defines
the smallest bitfield
capable of holding the enumerator values. For example:
enum  e1 { d a r k , l i g h t }; // range 0:1

enum  e2 { a = 3 , b = 9 }; // range 0:15

enum  e3 { m i n = 10 , m a x = 1 0 0 0 0 0 0 }; // range -1048576:1048575

I do not understand why enum3 has that range

(1048576:1048575)?  - (- 2^20 : 2^20 - 1)

A: It's should be a typo in your edition.  In my edition (The C++ programming langage - special edition, 12th printing, May 2005) of the same book, I read
enum e3 { min = -10, max = 1000000 };

which is in line with the text.
Additional explanation:
Stroustrup explains that the range is based on the smallest bitfield capable of holding the enumerator values. With 20 bits you can represent 2^20=1048576 different values. As you start your count from 0 and not from 1, you can go to max 2^20-1.  This explains the highest range.
Now he explains that the range goes down to 0 if the smallest enumerator is nonnegative.  This means that if min = 10,  the range would be from 0 to 1048575.
He also explains that the min range shall be rounded to the nearest lesser negative binary power if the smallest enumerator is negative which applies for min = -10.  This sentence alone would be ambiguous : you could think that le smallest power of two below -10 would be -16.  But the sentence has to be connected with the fact that the range is defined by the smallest bitfield capable of holding the values.  Hence, you need 20 bits+ the sign bit, and according to the conventions you can represent with this the values from -2^20 to +2^20-1.


text:
Q: parsing json from url to swift 2.0 I've been trying to retreive my json data for my iOS App. I tried many different sollutions but none of these worked properly for me. So this was the code I was using to read the json from the url and convert it.
let url = NSURL(string: "http://www.blind3d.byethost7.com/service.php")!

func load() {
        do {
            let request = NSURLRequest(URL: url)
            let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
            self.handleData(data)
        }
        catch let error as NSError {
            print("wieso dont you do siss : \(NSURLRequest(URL: url))")
            self.handleError(error)
        }
    }

func handleError(error : NSError?) {
    print("wieso dont you do siss : \(NSURLRequest(URL: url))")
    NSLog("%@", "Error with loading from \(url): \(error)")
}

func handleData(data : NSData) {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
        handleJSON(json)
    }
    catch let error as NSError {
        handleError(error)
    }
}

but somehow this isn't running properly. I am always getting this error when I am executing this method: NSJSONSerialization
Error with loading from http://www.blind3d.byethost7.com/service.php: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})

The json data I wanted to use for my app is here
Thank you for your help guys

A: The problem occurs because there it no actual JSON in the data variable. I tried your web service, and this is what you get returned in the data, along with all the other error html tags:
"This site requires Javascript to work, please enable Javascript in your
browser or use a browser with Javascript support"

The full response:

This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support

This seems to happen, because there is some Javascript injected in the webpage you are trying to parse from, probably for statistics, or some other unknown reasons.
For checking by yourself, print your data - print(data), before calling self.handleData(data)

A: Try removing \r\n or escape them with '\' like
\\r\\n

and you are good to go. BTW, using json is painful in swift like this, SwiftyJSON is a necessary library if you deal with json frequently.

A: This is the result of installed "testCookie-nginx-module"
It's supposed to prevent DDOS attacks on your hosting
When you visit your site for the first time, it sends you this JS code, which your browser is supposed to process and set a special cookie (its name it _test)
Only with this cookie attached to your IP your browser can see the original content (your content: html php json etc.)
Seems the only way for you - is to process this JS (with AES, HEX and other JS functions, get the right _test cookie and send another request with this cookie)


text:
Q: "Unexpected Error interacting with provider: 403 FORBIDDEN" error when trying to bootstrap in the maas portal :ht   tp://192.168.101.148/MAAS,i can see 6 nodes,and the status are all:ready.
and my environments.yaml file is :
environments:
  maas:
    type: maas
    maas-server: ht    tp://192.168.101.148:80/MAAS
    maas-oauth: "the key i get from the portal"
    admin-secret: super-secret-made-up-admin-key
    default-series: precise

and the error is below:
root@ubuntu:~# juju bootstrap
2013-09-11 15:55:31,557 INFO Bootstrapping environment 'maas' (origin: distro type: maas)...
2013-09-11 15:55:32,222 ERROR Failed to launch machine /MAAS/api/1.0/nodes/node-e097fab8-1a11-11e3-a94b-0800270f346d/; attempting to release.
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/juju/providers/maas/launch.py", line 48, in start_machine
    instance_uri, cloud_init.render())
ProviderInteractionError: Unexpected Error interacting with provider: 403 FORBIDDEN
Unexpected Error interacting with provider: 403 FORBIDDEN
2013-09-11 15:55:32,404 ERROR Unexpected Error interacting with provider: 403 FORBIDDEN

A: There is a fix in precise-proposed, enable this in your /etc/apt/sources.list:

*

*How do I add the "proposed" repository?
And then:
sudo apt-get update
sudo apt-get upgrade

and then restart MAAS with
sudo /etc/init.d/maas restart

this will solve your issue.

A: I had the same problem, had better luck by using juju from the PPA instead of the default precise apt repository.
Install add-apt-repository tool:
sudo apt-get install python-software-properties

Add Juju PPA:
sudo add-apt-repository ppa:juju/stable

Install Juju core:
sudo apt-get update
sudo apt-get install juju-core


text:
Q: How to convert an integer that was the end result of a bitwise OR to a table of the individual integers that the bitwise OR was applied against? How can I convert the final integer of a bitwise OR back to it's original set of integers that the bitwise OR operation was applied to?
For example if I have the following set of bit values: {0, 1, 2, 4, 8, 16} and if I have the bitwise OR generated value of 11 then I would like to convert that value of 11 back to 1, 2, and 8 (the only possible combinations of values).

A: The answer provided by J.D. works, except in the example the value 1 is not included in the results, even though for 11 the correct bits are 1, 2, 8.
The below example extends the logic from that answer, but uses a recursive CTE instead of a loop to generate the bit values and wraps it in a function that can be called easily to return a table of bits for a given mask. It also doesn't use a table to store the bit values and generates them on the fly.
Code:
CREATE FUNCTION fnGetBitsForMask (@Mask INT)
RETURNS TABLE
AS
RETURN
    WITH BitwiseValues AS
    (
        SELECT CAST(1 AS INT) AS RowNumber, CAST(0 AS INT)  AS BitValue
        UNION ALL
        SELECT b1.RowNumber+1 AS RowNumber, POWER(2, b1.RowNumber-1) AS BitValue
        FROM BitwiseValues b1
        WHERE b1.RowNumber < 30
    )
    SELECT b.BitValue
    FROM BitwiseValues b
    CROSS JOIN (SELECT @Mask AS Mask) m
    WHERE b.BitValue & m.Mask > 0

In use:
SELECT * FROM dbo.fnGetBitsForMask(11)

Result:
BitValue
1
2
8

As a Table-Valued Function, you can use this in SELECT statements and other queries without having to maintain tables or use loops.

A: I believe I figured out the answer. The quick version is, to convert from a bitwise OR generated value, I would need to apply a bitwise AND to between each individual bit value and the bitwise OR generated value.
The way I did this was I generated a table of all possible bitwise values in my set (I actually just made a table with the first 30 bitwise values using the SQL POWER() function, because after 30 you run into arithmetic overflow) and then cross joined that table to my bitwise OR generated value and selected the bitwise AND operation between the bitwise values and my bitwise OR generated value, then filtered out where the result is 0.
SQL to create bitwise values table:
DECLARE @LoopCounter AS INT = 0

WHILE (@LoopCounter < 30)
BEGIN

    SET @LoopCounter = @LoopCounter + 1

    INSERT INTO BitmaskValues
    SELECT @LoopCounter AS RowNumber, POWER(2, @LoopCounter) AS BitValue

END

SQL to join to my bitwise OR generated value and get my results after:
SELECT 11 AS BValue
INTO #Mask;

WITH BitwiseOperation AS
(
    SELECT BV.BitValue, M.BValue, BV.BitValue & M.BValue AS BitwiseAnd
    FROM BitmaskValue AS BV
    CROSS JOIN #Mask AS M
)

SELECT BitValue, BValue, BitwiseAnd
FROM BitwiseOperation
WHERE BitwiseAnd <> 0


text:
Q: Discord.py get server name or id by server link So i want a bot that can return the server name/id by the join link.
Like:
https://discord.gg/WxwgCQzW
Will return:  cryptoTribe

A: Update
Better way
After some more digging, there's a better way to do this, using discord.Client.fetch_invite(), which returns a discord.Invite:
async def get_invite_name(link: str):
    # Assuming bot or client is a global variable
    invite = await bot.fetch_invite(link)
    return invite.guild.name

Old way
You can perform a GET request to the invite endpoint:
GET https://discordapp.com/api/invite/WxwgCQzW

Then, with the JSON data:
guild_name = data["guild"]["name"]

Code
Using aiohttp:
import aiohttp
import json

DISCORD_API_LINK = "https://discordapp.com/api/invite/"

async def get_invite_name(link: str) -> str:
    # Get the invite code of the link by splitting the link and getting the last element
    invite_code = link.split("/")[-1]
    async with aiohttp.ClientSession() as session:
        async with session.get(DISCORD_API_LINK + invite_code) as response:
            data = await response.text()
            json_data = json.loads(data)
            return json_data["guild"]["name"]


text:
Q: Migrations Failing - "No superclass method 'version' for #" The Problem
I am attempting to update a production database with a series of migrations without losing its current data. In starting from scratch, I've had no problems running all of the migrations on an empty database, or working forward with my development and test databases. However, in trying to run the migrations on a backup of our production database I am receiving a strange error, which in turn prevents all migrations from running.
The Error Message:
This is the result of running rake db:migrate RAILS_ENV=production
rake aborted!
NoMethodError: super: no superclass method `version' for #<ActiveRecord::SchemaMigration >
C:in `map'
C:in `map'
Tasks: TOP => db:migrate

The Error Message - Expanded:
This is the result of running rake db:migrate RAILS_ENV=production --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
rake aborted!
NoMethodError: super: no superclass method `version' for #<ActiveRecord::SchemaMigration >
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activemodel-4.2.0/lib/active_model/attribute_methods.rb:430:in `method_missing'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/schema_migration.rb:53:in `version'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:844:in `block in get_all_versions'
C:in `map'
C:in `map'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:844:in `get_all_versions'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:985:in `migrated'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:990:in `ran?'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:967:in `block in runnable'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:967:in `reject'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:967:in `runnable'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:952:in `migrate'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:820:in `up'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/migration.rb:798:in `migrate'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/tasks/database_tasks.rb:137:in `migrate'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.2.0/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:240:in `call'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:240:in `block in execute'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:235:in `each'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:235:in `execute'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:179:in `block in invoke_with_call_chain'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:172:in `invoke_with_call_chain'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/task.rb:165:in `invoke'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:150:in `invoke_task'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:106:in `block (2 levels) in top_level'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:106:in `each'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:106:in `block in top_level'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:115:in `run_with_threads'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:100:in `top_level'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:78:in `block in run'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:176:in `standard_exception_handling'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:75:in `run'
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rake-10.4.2/bin/rake:33:in `<top (required)>'
C:/RailsInstaller/Ruby2.0.0/bin/rake:23:in `load'
C:/RailsInstaller/Ruby2.0.0/bin/rake:23:in `<main>'
Tasks: TOP => db:migrate

Additional Info:

*

*Database: sqlserver

*Ruby: 1.9.3

*Rails: 4.2.0

*Environment: Windows 7

Actions Taken:
A cursory check of my database proves that the schema_migrations table exists, and that it does contain a "version" column. Everything appears to be in proper order. For good measure I've tried dropping and (re-)restoring the database backup multiple times, deleting and regenerating the schema.rb, and running all of my migrations again from scratch. I can't seem to figure out what is causing this to fail.
Research:
I can only find one example of someone experiencing a similar problem (here), and no clear resolution.
I Need to Know:

*

*What's causing this

*How to fix it

*OR an alternative way to update my database without losing its records

A: I've had the same issue today. Turns out it was because in my database.yml I had other schemas in my search_path, and those schemas had tables named schema_migrations without the field version.
So if you're having this issue, make sure that there are no tables with the name schema_migrations except for the one you need in the search path.


text:
Q: Menus in game: Is Screenmanager the way to do it? I'd like to create a menu in my game coded thanks to Kivy, where the player can choose different options and launch the game.
I've learned about the ScreenManager module but I don't know whether it's taylored for this:
from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition

class MenuScreen(Screen):
    pass

class GameScreen(Screen):
    gameloop.main()

class MyGameApp(App):
    def build(self):
       sm = ScreenManager(transition=NoTransition())
       sm.add_widget(MenuScreen(name='menu'))
       sm.add_widget(GameScreen(name='game'))
          return sm

if __name__ == '__main__':
    MyGameApp().run()

If I do this, isn't the app launching simultaneously the Menu AND the Game screen at the same time (one in the background and the other shown to the user)? (which is not what is intended of course).
What is the proper way to do a menu in games with kivy?

A: You can put a game's logic in screen widgets.
If your game has some kind of count down, or moving enemies, you can bind its start to on_pre_enter or on_enter events.


text:
Q: How can we retrieve existing subscriptions in Microsoft Graph? This is the call I'm trying:
https://graph.microsoft.com/v1.0/subscriptions

This results in the following error:
{
    "error": {
        "code": "QueryNotSupported",
        "message": "The query is not supported.",
        "innerError": {
            "request-id": "8b2f2137-51ed-498d-9fbb-bc0a29c509da",
            "date": "2018-01-27T14:56:01"
        }
    }
}

I am using the Microsoft Graph .NET SDK to make the actual call:
var subscriptions = await graphServiceClient.Subscriptions.Request().GetAsync();

A: It isn't possible to retrieve a list of all existing subscriptions. You need to know the subscriptionId for a given subscription before you can GET, PATCH, or DELETE a subscription.
Keep in mind that subscriptions are by nature temporary resources. Unless that application that requested the subscription renews it, a given subscription will generally automatically expire within 3 days.


text:
Q: SASS Concatenate class name? I got a LESS file from this a Date-picker plugin and want to convert it to SASS.
But in the LESS, it concates a class name like this:
//LESS
.dropdown{
    &-inline{
    }
}

Result:
.dropdown-inline ...

I tried many things in SASS like #{-inline} or #{"-inline"} but it doesn't work.
I tried googling and found a year-old article saying it's impossible in SASS. I can't found recent post about this issue. Is it possible now? How?
Thanks

A: This is not possible before version 3.2 but will be eventually. Just like LESS, the syntax will use &.
With updated scss, you can now use the interpolation syntax &-- to DRY up your style files.

A: Just moved from css to scss I ran in to this question and was disappointed until I found out it is not up-to-date.
Found the correct answer here:
https://css-tricks.com/the-sass-ampersand/#article-header-id-12.
It is now possible with the following syntax:
.add-some {
    &-red {
        color: red;
    }
}

Results, as expected, to:
.add-some-red {
    color: red;
}


text:
Q: Where or how should I declare the global variable "dtjava"? I'm attempting to following this example from the JavaFX documentation to deploy a JavaFX app in HTML: http://docs.oracle.com/javafx/2/deployment/deployment_toolkit.htm#FBJHIEAG.  The problem I'm having is that NetBeans highlights the dtjava elements, and displays the error message 'The global variable "dtjava" is not declared.'.  The page itself loads, but I get "JavaFX application could not launch due to system configuration", which I'm assuming relates back to the "dtjava" issue.
Where or how should I declare the global variable "dtjava", to resolve the error?


text:
Q: Help to understand Noether Normalization Theorem I'm trying to understand the statement of the Noether Normalization Theorem:

How can $k[x_1,\ldots,x_n]$ be equal to $k[x]$? a typical element of $k[x]$ is for example $ax^2+bx$ with $a,b\in k$, while an element of $k[x_1,\ldots,x_n]$ is for example $cx_1^3x_2x_3^2+x_1^2+d$ with $c,d\in k$.
Thanks in advance.

A: Here $x$ is just a (relatively common) shorthand for the entire list of variables $x_1, \ldots, x_n$. Typically this is denoted $x_1, \ldots, x_n = \underline{x}$, but for whatever reason the author chose not to denote it this way.


text:
Q: How to interact with a Binance Smart Chain contract using Python I've first tried sending a transaction with python:
from web3 import Web3

transaction = {
        'chainId': 97,  # 97: Testnet. 56: main.
        'to': '0xmyaddress',
        'value': 1,
        'gas': 2000000,
        'gasPrice': 13,
        'nonce': 0,
    }

infura_url = "https://mainnet.infura.io/v3/my-api-key"
w3 = Web3(Web3.HTTPProvider(infura_url))

key = '0xmykey'
signed = w3.eth.account.signTransaction(transaction, key)

w3.eth.sendRawTransaction(signed.rawTransaction)

Giving me the following error: ValueError: {'code': -32000, 'message': 'invalid sender'}

Now, I am trying to interact with a contract - calling methods and giving inputs, but I am unsure how to accomplish this.


text:
Q: Flutter Bloc test "bloc.add" null safety issue I have a flutter bloc_test which is failing due to recent upgrades in Flutter involving null safety.
I have the following code
blocTest('get the usecase name',
        build: () {
          when(() => mockGetUseCaseName(any()))
              .thenAnswer((_) async => Right(name));
          return bloc;
        },
        act: (bloc) => bloc.add(GetUseCaseName(name)),
        verify: (_) => verify(
            () => mockGetUseCaseName(Params(string: name))));

And I get the error on the line "bloc.add"
"The method 'add' can't be unconditionally invoked because the receiver can be 'null'"
Any ideas?

A: the most correct solution would be to make the data type explicit
Before:
blocTest('get the usecase name',
    build: () {
      when(() => mockGetUseCaseName(any()))
          .thenAnswer((_) async => Right(name));
      return bloc;
    },
    act: (bloc) => bloc.add(GetUseCaseName(name)),
    verify: (_) => verify(
        () => mockGetUseCaseName(Params(string: name))));

after:
blocTest<ClassBloc, ClassState>('get the usecase name',
    build: () {
      when(() => mockGetUseCaseName(any()))
          .thenAnswer((_) async => Right(name));
      return bloc;
    },
    act: (bloc) => bloc.add(GetUseCaseName(name)),
    verify: (_) => verify(
        () => mockGetUseCaseName(Params(string: name))));

A: I found the answer - for any others out there with the same issue. I fixed it by casting the bloc type (because act/bloc is of Object? type)
act: (bloc) => cast<UseCaseBloc>(bloc).add(GetUseCaseName(name))

Have a good day.
Kia Kaha,
Mike Smith


text:
Q: How to take 1000 lines of codes in muliple cells in Jupyter to Paragraphs Zeppelin Notebook? I want to copy-paste the code from Jupyter to zeppelin notebook.
I have multiple cells in jupyter notebook and I want to copy it to Zeppelin notebook without doing manually for each cell to paragraph.
Is there a way to do this in quicker way.


text:
Q: Why bigger stream of water in a metal sink is more silent than a smaller one? I have a metal sink. I don't want to waste much water so I prefer smaller streams of water. But when the stream is small it makes a big noise. However, when I increase the flow, the tapping sound becomes absent and I can only hear the sound of the water flow.
My question is - why does the additional water reduce the noise of flowing water? I believe it has something to do with damping but I can't imagine the process. Probably the water particles in the middle don't make much noise because they are surrounded by other particles and sound waves are trapped inside. But what about the water around the stream? The stream's diameter is big and therefore there are more water particles on the borders than there are in the smaller stream. And more particles should make more noise.
I can make a video of the process I've described if I didn't myself clear enough. Tell me in the comment if you need it.

A: I tried this on my kitchen sink and it's true.  A narrow stream almost separated into many dollops makes a loud resounding thudding, but a thick fast column of water is almost silent on the metal.
The reason is that the narrow, weaker, less continuous stream allows the metal to vibrate.
The thick, weighty, continuous stream deforms the metal and keeps it that way, doesn't allow the metal to spring back into shape, and there is no vibration.  The greater weight and pressure of the thick stream damps the resonance of the metal.
If you pressed a drumstick into a drumhead continuously, there would be no vibration.  But when  you allow the drumstick to bounce on the drumhead, there's vibration and sound.


text:
Q: How do I find diamonds? The durability of iron tools is really starting to annoy me, but in all my hours of playing I've only stumbled across one deposit of diamond ore that provided around 7 Diamonds.
What's the best way to locate more in Survival mode? Where is it most commonly found?

A: One way I find lots of diamond is by making something I called Mining rooms. How you do this is dig a staircase type thing down until you're a couple blocks above bedrock. When you get there dig as far as you can right without moving and do the same thing to the left (your tunnel should look sorta like a "T" by now). Go into the right tunnel and dig a tunnel to the left(as long as you want). You then dig 9 blocks to the left. when you do that turn to the left once more and dig until you find your tunnel. Then dig up all the area in between the tunnels. Using this strategy I found 30 diamonds, 75 redstone, 36 iron, and loads of coal within an hour. Hope this helps

A: When in doubt, Find a Cave.
If you don't see anything on the surface, Dig Deeper.
Really, that's all there is to it. In general, you won't find Diamond much past 10 levels or so above Bedrock.
The graph below (taken from TR's interactive MC Block Distribution Chart) shows the density of Diamond in one generated world. 0 on the X axis represents bedrock. 255 is the top of the sky.

A: Follow a path that's been previously mined out by water. All you have to do is replace the source block (the block from which water appears to be flowing), and the water will cease to flow, allowing you easy passage through the cave.
After you've stopped the flow of water, follow its former path. Not only will your path be carved out for you, but you'll be much more likely to find coal, gold, red ore and diamond.

A: For hunting diamond, dig down to bedrock. Diamonds only occur in the bottommost 10 levels of minecraft. Once you are at the proper depth, start digging exploratory branches until you find what you are after.
For more information on most efficent mining and efficent travel to the bedrock layer, see What's the most efficient Minecraft mining strategy?

A: I've tried two or three different methods, and a single one stands out for its output.You'll need nothing more than what you would typically take on a mining expedition, apart from the addition of a bucket of water. Firstly, mine (or explore) to the general level of lave generation within the bottommost stretch of the Overworld, just before hitting bedrock. Once you've located a large pool of lava, get above it and place the water from your bucket on an adjacent or overhead block. Recollect the water, and repeat. Once all of the lava has been exhausted and you're left with a floor of obsidian, use this as your canvas to mine the area.
As this level is fairly easily accessed and close to the bedrock level, diamonds are sure to be found. Oftentimes, the removal of lava exposes diamonds above the pool or to the side that normally wouldn't have been seen.

A: Method only works for versions 1.16+
All you have to do is:

*

*Find a swamp

*Find a clay patch (underwater)

*Mark the middle

*Go out 6 blocks from the middle south or positive Z axis

*Dig down on the 7th block

*You will have a 88% chance of finding diamonds!

Source
Note:

Before trying it, players must note that this method has been tested in Minecraft version 1.16 Java Edition and works only in 87.5% of seeds. In the other 12.5% seeds, the probability of finding diamonds is 50%.

SWAMP_CLAY DIAMOND will work reliably on 87.5% of seeds.
Z offset 8 occurs with probability 0.500088
Z offset 6 occurs with probability 0.3749
Z offset 15 occurs with probability 0.062528
Z offset 12 occurs with probability 0.046895
Z offset 10 occurs with probability 0.011681
Source


text:
Q: Garbarge collector order I know the .Net garbage collector cannot guarantee any order when destroying objects but I am really suprised of the following behaviour:
using System;
using System.Collections.Generic;

namespace ConsoleApplication2 {
class Program {

    class A {
        public A() { i = 1; }
        private int i;

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~A() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Console.WriteLine("Disposed A");
        }
    }

    class B {
        static int p = 0;
        public B(A a) {
            this.a = a;
            j = p++;
        }

        ~B() {
            Console.WriteLine("Disposed " + j.ToString());
        }

        private int j;
        private A a;
    }

    static void Main(string[] args) {
        A a_obj = new A();
        List<B> bs = new List<B>();
        for (int i = 0; i < 10; i++) {
            B b = new B(a_obj);
            bs.Add(b);
        }
    }
}
}

This execution has the following (possible) output:
Disposed 9
Disposed 2
Disposed 1
Disposed 0
Disposed A
Disposed 8
Disposed 7
Disposed 6
Disposed 5
Disposed 4
Disposed 3
I can understand that the order of B objects is not deterministic but
how is possible that the garbage collector destroys a_obj, if there are still some B objects that have a reference to a_obj and has not been destroyed still?

A: .NET garbage collector does not use reference counting, so it doesn't matter how many references to a_obj there is. What matters is what objects are reachable from roots (like static variables). In your case, all objects (A and all Bs) become unreachable from root at the same time and so are all eligible to garbage collection, their mutual references do not matter. If A and B are both unreachable and will be collected in the same cycle, why bother about order in which this will happen? Also if order was dependent on which object references which - think about how it would then collect objects that have mutual references to each other?
Here is also a quote from documentation which fits your situation exactly:

The finalizers of two objects are not guaranteed to run in any
  specific order, even if one object refers to the other. That is, if
  Object A has a reference to Object B and both have finalizers, Object
  B might have already been finalized when the finalizer of Object A
  starts.

Also note that first all finalizers will run and only then objects will be really dead and memory taken by them might be reused (you can even ressurect object in finalizer via GC.ReRegisterForFinalize). So you can access A from B's finalizer, even though A's finalizer might have already been run at this point. Obviously you should avoid doing this anyway.

A: If none of the elements that reference a_obj are referenced, the GC can collect it, because the application root has no way of obtaining a reference to it again.
Here is the relevant part of a good tutorial on C# object lifecycle
During a garbage collection process, the runtime will investigate objects on the managed heap to determine whether they are still reachable (rooted) by the application. To do so, the CLR will build an object graph, which represents each reachable object on the heap. Object graphs are used to document all reachable objects.
[...]
Once the graph has been constructed, unreachable objects are marked as garbage.

A: The output is produced when process is being shut down, at this point GC is cleaning whole memory allocated during process, references between objects do not affect the order of cleaning.


text:
Q: Read Bits for definded length at defined position I have a bitstring.Bitarray and want to read from a certain position to another position.
I have the int variable length in a for loop, so for example I have:
length = 2
and my Bitarray looks something like:
msgstr = bitstring.BitArray(0b11110011001111110)

id = bitstring.BitArray()
m = 0
while 5 != m:
   /////////////
   Length changes in value part of Code
   /////////////
   x = 0
   if m == 0:
       while length != x:
           id.append = msgstr[x] #msgstr is the BitArray that needs to be read
           x = x + 1
   m = m + 1

I then want to read the first two bits and convert them into an int, so that I have:
id == 3
And for the next round when length has changed in value it should start from the third bit etc.

A: The code inside your loop only does anything if m == 0, but then you increment m, so m is only 0 the first time through the loop. The rest of the times you go through your loop, it doesn't seem to actually be doing anything.
Also, where you say
id.append =  msgstr[x]

you probably actually want
id.append(msgstr[x])

It also seems like you might benefit from using Python's slice notation.

A: I do not understand exactly what you goal is but do you had a look at https://wiki.python.org/moin/BitManipulation ?


text:
Q: removing gap between div border and font Here's my CSS:
div {
  border: 1px solid
  font-size: 30px
  color: red
  width: fit-content
  height: fit-content
}

Here's my HTML:

⮝

Here's how it shows up in the browser:

Here it is on JS Fiddle:
https://jsfiddle.net/f9wkb4qp/
I'd like to remove the gap between the div border and the font. eg. I'd like to make the result look more like this:

Any ideas as to how I might achieve this effect? Or is this even possible? Like if the white space is actually part of the character then I guess it might not be possible?

A: Try to use line-height.

div {
    border: 1px solid;
    font-size: 30px;
    color: red;
    width: fit-content;
    line-height: 0.9;
}

⮝


text:
Q: Django REST Framework Browsable API JWT Auth I am trying to integrate the django-rest-framework-simplejwt package for jwt auth.
Everything works as expected, the only issues is that I don't know how to make it work with the Django Rest Framework Interface.
When I try to access a "protected" view I get the expected Not Authorized response, but there is no way for me to add the token when making the request.
And when I try to Login I get redirected to the django login, which doesn't help.
How can I add the Bearer token to the Django Rest Framework Interface?
To circumvent this, I've installed the drf_spectacular package that does its job very well, I am just curios if I can make the Django Rest Framework Interface work with the jwt token so that I don't need the drf_spectacular package.
Some of my configs:
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",
    "rest_framework",
    "rest_framework_simplejwt",
    "drf_spectacular",
    "todo_api",
]

REST_FRAMEWORK = {
        "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
        "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
        "DEFAULT_AUTHENTICATION_CLASSES": (
            "rest_framework_simplejwt.authentication.JWTAuthentication",
        ),
    }

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

#TODOListApiView.py
    from .serializers import TodoSerializer
    from drf_spectacular.utils import extend_schema
    from rest_framework_simplejwt.authentication import JWTAuthentication

    class TodoListApiView(APIView):
        # add permission to check if user is authenticated
        authentication_classes = [JWTAuthentication]
        permission_classes = [permissions.IsAuthenticated]
        ...

A: Aparently its not possible and you need to use a chrome extension such as "ModHeader" to add the jwt token to the header in the browser.
A shame, you would expect these libraries to make compatible implementations with each other.


text:
Q: Solr Request Handlers and Query Parsers I am new to Solr. Please help me with following queries:

*

*What is the difference between a request handler and a query parser?
I'm thinking it's that when a query is sent through URL in solr, at first the query is parsed using the Query parser. Request handler then takes the parsed query and searches and presents the response according to request handler parameters. Is this Correct?

*What is the default query parser and default request handler in Solr?

*Parameter deftype is used to specify parser and qt for request handlers right?
I wrote this query
select?q=features:power%20features:latency&deftype=dismax
which works, but select?q=features:power%20features:latency&qt=dismax does not.
Here is my requestHandler
<requestHandler name="dismax" class="solr.SearchHandler">
 <lst name="defaults">
  <str name="defType">dismax< /str>
  <str name="echoParams">explicit< /str>
  <float name="tie">0.01< /float>
  <str name="qf">text^0.5 features^1.0 name^1.2 sku^1.5 id^10.0 manu^1.1 cat^1.4< /str>
  <str name="pf">text^0.2 features^1.1 name^1.5 manu^1.4 manu_exact^1.9< /str>
  <str name="bf">popularity^0.5 recip(price,1,1000,1000)^0.3< /str>
  <str name="fl">id,name,price,score< /str>
  <str name="mm">2<-1 5<-2 6<90%< /str>
  <int name="ps">100< /int>
  <str name="q.alt">*:*< /str>
 <!--  example highlighter config, enable per-query with hl=true
  -- >
  < str name="hl.fl">text features name</str>
 <!--  for this field, we want no fragmenting, just highlighting
  -- >
  < str name="f.name.hl.fragsize">0< /str>
 <!--  instructs Solr to return the field itself if no query terms are
          found
  -- >
  <str name="f.name.hl.alternateField">name< /str>
  <str name="f.text.hl.fragmenter">regex< /str>
 <!--  defined below
  -->
  < /lst>
</requestHandler>

A: Default request handler is the one with default="true" parameter in SolrConfig.xml (SearchHandler, if you haven't changed that).
Request handler handles requests, so it is a starting point for every request, which means that request handler uses/calls query parser (either the one specified by the url or default one) as its first step.
You want to get:
 1. Documents with "power latency" as the phrase?
 2. Or docs with both terms anywhere in a doc?
 3. Or docs with either of those terms?
Try like this:
 1. select?q=features:"power latency"&qt=dismax
 2. select?q=features:power+features:latency&qt=dismax&mm=2
 3. select?q=features:power+features:latency&qt=dismax&mm=1
More info on DisMaxQParserPlugin.


text:
Q: Why do gradient boosting algorithms mostly use trees? Why do gradient boosting algorithms mostly use trees? Is there any logic in this? (in XGBoost and in boosting which in sklearn library uses trees, not other algorithms).

A: Mostly because they are very good base learner. In few words, I woud say because it is easy to boost trees, and the performance (in terms of predictive power) is very good.
Usually, data mining procedures are well suited for particular applications. For instance, LASSO is a good choice if we believe that the true Data Generating Process (DGP) is sparse, while we do not expect a great perfomance when the DGP is dense. However, there exist several Off-the-shelf procedures, which tend to have discrete to good perfomances in several and various applications, and do not need a lot of data pre-processing. Such procedures satisfy few desiderata: among others, low computational burden, ability to handle mixed data (continuous, binary, categorical, ...) and missing values. Moreover, interpretability is often desired. Black-box models can achieve superior perfomances, but sometimes we do wish understanding what is happening inside.
Decision trees are probably the best off-the-shelf procedure we have so far. However, they have a clear drawback: volatility, which probably is the only thing preventing trees to be the ideal algorithm.
So, boosting trees is considered optimal for two reasons: it is easy, and it solves the problem of high variance (sacrifying interpretability), thus improving accuracy.
This is what comes to my mind. I remember a short discussion about this point in Elements of Statistical Learning (Hastie et al., 2009). Looking at the table of contents, you can probably find more details in chapter 10. I am curious if somebody has other explanations for this.


text:
Q: Can i get lead gen data at linked in using webhooks URL and C# likd facebook? i have an application in linked in and have page on it and Campaign manager, i want to send leads data automatically to Microsoft Dynamics CRM without downloading the leads,i want to make this cycle dynamics.
i do not know where can i add My Webhooks URL to can send leads information to it.

A: If I understand your req, you have an external system (non crm) and from this system you wish to get information from crm and perform some operation in crm.
I would suggest you go with Dynamics 365 webpi.
Create Application user in Azure AD and give proper rights, Then create this user in CRM and you are good to go.
You have an user dedicated to perform Interface tasks. You do not need unnecessary webhooks or other technologies.
https://www.dynamicsforcrm.com/using-postman-with-dyanmics-365-web-api/
https://community.dynamics.com/crm/b/crminthefield/posts/setup-postman-to-use-web-api-for-dynamics-365-ce-online-#:~:text=Postman%20is%20a%20popular%20tool,to%20be%20permitted%20by%20AAD.
https://carldesouza.com/calling-the-power-apps-and-dynamics-365-web-api-from-the-postman-windows-client/
https://medium.com/capgemini-microsoft-team/dynamics-365-application-users-no-additional-license-required-and-no-limit-on-quantity-4bdc49f8ce2d


text:
Q: Custom Dialog Alert I am trying to make a custom dialog alert as shown in the picture; I tried and looked everywhere to make it look like the photo but nothing seems to work. Any help would be appreciated; First picture shows what I want to make and the second what it looks like currently:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val alert = AlertDialog.Builder(this@MainActivity)

        alert.setTitle("Confirm delete")
        alert.setMessage("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.")

        alert.setPositiveButton("DELETE"){dialog, which ->
            Toast.makeText(applicationContext,"Ok, we change the app background.",Toast.LENGTH_SHORT).show()

        }

            alert.setNegativeButton("CANCEL"){dialog,which ->
            Toast.makeText(applicationContext,"You are not agree.",Toast.LENGTH_SHORT).show()
        }

        val dialog: AlertDialog = alert.create()

        dialog.show()
    }
}

A: Alert.Dialog theme depends on your device API levels.  In the first picture look like Android KitKat (API 19 - 20) ,in the second picture follows material design pattern (API >20).
If want to dialog like the first picture you may need make custom layout
happy_coding

A: 1.Create Kotlin class for Dialog
class CustomDialog(
    context: Context,val mCallBack: CallBack
) : Dialog(context, R.style.full_screen_dialog) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_custom)
        // YOUR COMPONENT HANDLE HERE
    // FOR EXAMPLE
        btn_yes.setOnClickListener {
              mCallBack.onDone()
              dismiss()
        }
        btn_cancel.setOnClickListener {
            dismiss()
        }
    }

    interface CallBack {
        //YOU CAN HANDLE THIS METHOD IN YOUR CALLING ACTIVITY
        fun onDone(rating: Float, comments: String)
    }

}

2.How to call
 var mDialog: CustomDialog = CustomDialog(
            this,
            object : CustomDialog.CallBack {
                override fun onDone() {

                }
            })
        mDialog.show()

3.styles.xml
<style name="full_screen_dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">false</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="colorAccent">@color/transparent</item>
    </style>

Create your own custom layout file and set it on setContentView(R.layout.dialog_custom) as I didn't mentioned here

A: This is because your dialog is displaying using material theme.
You can use below code to get required result by applying style to AlertDialog.
val alert = AlertDialog.Builder(this@MainActivity,AlertDialog.THEME_HOLO_LIGHT)

Note: this style is deprecated.


text:
Q: Erro no cálculo de valores de um vetor Estou parado nessa parte do meu trabalho no case 2 da faculdade, a saida fica toda embaralhada, por exemplo:

O lucro sera de -1,#$%#!@

#define vetor 40

struct Produto{
    char codigo[10];
    char descricao[100];
    float precoCompra;
    float precoVenda;
    int quantEstoque;
};

int main(){

    // Declaração das variaveis
    struct Produto estoque[vetor];

    float lucro;
    float lucro2;

    int opcao;
    int opcao2;
    int count;
    int i;

   // Inicios do menu do programa
   system("cls");  // Limpa a tela

    puts( "Escolha uma opção:" );
    puts( "1 - Cadastrar produto." );
    puts( "2 - Lucro da venda de todos os produtos." );
    scanf( "%d", &opcao );  // Lê a entrada do usuário

    fflush(stdin);  // Limpa o lixo da memoria
    system("cls");  // Limpa a tela

    // Inicios do switch case
    switch( opcao ){

        case 1:

            count = 1;

            system("cls");

            printf( "Deseja cadastrar um produto?\n1 - SIM\n2 - NAO\n" );
            scanf( "%d", &opcao2 );

            system("cls");

            while( opcao2 != 2 ){

                fflush(stdin);

                printf( "Entre com o codigo do produto: " );
                scanf( "%s", &estoque[count].codigo );

                printf( "Entre com a descricao do produto: " );
                scanf( "%s", &estoque[count].descricao );

               printf( "Entre com o preco da compra: " );
               scanf( "%f", &estoque[count].precoCompra );

                printf( "Entre com o preco da venda: " );
                scanf( "%f", &estoque[count].precoVenda );

                printf( "Entre com a quantidade em estoque:" );
                scanf( "%d", &estoque[count].quantEstoque );

                count++;

                system("cls");

                printf( "Deseja cadastrar outro produto?\n1 - SIM\n2 - NAO\n" );
                scanf( "%d", &opcao2 );

            }
            return main();

        case 2:

            lucro = 0;

            printf( "Lucro total com a venda de cada produto.\n" );

            for( i = 1; i <= vetor; i++ ){

                    fflush(stdin);

                    lucro = lucro + ( estoque[i].precoVenda * estoque[i].quantEstoque      );
                }

            fflush(stdin);

            printf( "O lucro sera de: %.2f", lucro );

            getch();
            return main();

    }

    return 0;
}

Como posso resolver isso?

A: Problema 1
Você esta calculando valores com lixo de memória.
Em C, todos os vetores são indexados partindo da posição 0 até a N-1, sendo N a quantidade de elementos do vetor.
No seu caso, o vetor estoque possui vetor posições. No seu looping, você esta inicializando i com 1 e caminhando até i <= vetor. Logo, quando i == vetor, você fará referência a posições de memória não inicializadas, podendo causar desde resultados aleatórios (aka undefined behavior) até falhas de segmentação (access vilation se você usa Windows, segmentation fault se usa praticamente qualquer outra coisa hehehe).
Solução
Altere para o seu looping ir de i = 0 enquanto i < vetor.
No case 1 também será necessário corrigir, uma vez que a você utiliza a variável count para acessar os elementos do estoque e esta esta sendo inicializada com o valor 1.
Problema 2
Caso você não possua todos os elementos do vetor inicializados (por exemplo se a constante (estou inferindo já que você não postou a declaração) vetor valer 5 mas inserir apenas 3 itens na variável estoque), você também irá ler lixo de memória no looping do case 2.
Solução
Mantenha uma variável de controle (pode ser a própria variável count, porém em escopo global) com a quantidade de elementos no vetor estoque, e ao invés de percorrer o vetor estoque inteiro no case 2, percorra apenas os count primeiro elementos. Seria algo mais ou menos assim:
for ( i = 0; i < count; i++ ) {
    // faça o cálculo aqui.
}

Há alguns outros problemas no código, mas a princípio, são estes os problemas que estão causando os erros encontrados.
Além disso, estou assumindo primeiro semestre do curso de computação, logo não vou ser chato e criticar todos os problemas de uma única vez...
Espero ter ajudado,
Boa sorte!