text:
Q: How does changing DAY_OF_WEEK in java.util.Calendar work? I am trying to change DayofWeek in Calendar but doesnt appear to be working as I expect. Here is an example. I set calendar time to a Friday time, but when I set Calendar.DAY_OF_WEEK to Calendar.SUNDAY, it is moving forward to next week. Since Calendar.SUNDAY is first day of week by default, shouldn't it move the time back to beginning of current week?
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class GenericWeekdayOpenFunction implements TimePeriodFunction {

    public static void main(String[] args) {
        // Nov 8 is Friday
        long time = DateUtilities.newDateTimeAsMillis(2013, 11, 8, 10, 00, 00);
        System.out.println(DateUtilities.formatGmtDatetime(time));

        Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        calendar.setTimeInMillis(time);

        // move day of week to Sunday, expect date to be Nov 3
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println(DateUtilities.formatGmtDatetime(calendar.getTimeInMillis()));    // wrong

        // move day of week to Friday, expect date to be Nov 8
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        System.out.println(DateUtilities.formatGmtDatetime(calendar.getTimeInMillis()));
    }

}

Output:
08-11-2013 10:00:00.000
10-11-2013 10:00:00.000
08-11-2013 10:00:00.000

A: Your scenario working fine with basic Calendar class usage:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date d = new Date(113, 10, 8, 10, 0, 0);
c.setTimeInMillis(d.getTime());
System.out.println(c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println(c.getTime());

Output:

Fri Nov 08 10:00:00 IST 2013
Sun Nov 03 10:00:00 IST 2013
Fri Nov 08 10:00:00 IST 2013

Note that Date(113, 10, 8, 10, 0, 0); is used only for quick check, it is deprecated though. Trying for any other combination also works fine. Can you just try using basic Calendar API and print dates ie
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
System.out.println(c.getTime());//current day
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(c.getTime());

second date should go back to previous sunday not upcoming one. If it's working for you then  DateUtilities implementation may be doubtful.

A: I think that the method set(int field, int value)
Works approaching to the nearest day (not to the DAY_OF_WEEK of the same week).
But you can use the function add(int field, int amount) in this case add(Calendar.DATE, -5) to do that.


text:
Q: Telerik Dropdowns lists selected value I am using Radcombo box . I want to pass get the selected value of the drop down list in a page , and pass it to different page  and get the same value selected for the drop dwon in the 2nd page.
But I am unable to capture the value.Only getting the index here.
I tried
           ddl2.SelectedIndex
           ddl2.SelectedItem.Text
           ddl2.SelectedValue

for sending the value. But it is passing the index of the value only.
Also , in the 2nd page I need to assign this value to drop dwon list .
So,  I used
           ddl2.SelectedIndex = Convert.ToInt32((Request.QueryString["No2"]));
           ddl3.SelectedIndex = Convert.ToInt32((Request.QueryString["No3"]));

But this are also not able to select the proper value. Any suggestions?
Now I can pass values successfully to the 2nd page using query string ..But while assigning the value from quer string to ddl  list I am getting null value each time..
Here is the piece of code that I tried.I tried both of the below lines.but with each case value is coming to the RHS..but on the LHS its coming as Null.
          ddl2.SelectedItem.Value Request.QueryString["No2"].ToString();
          ddl2.FindItemByValue(Request.QueryString["No2"].ToString()).Selected = true;

A: Here is an example of a way to do this:
Page1.aspx:
<telerik:RadComboBox ID="RadComboBox1" runat="server">
    <Items>
        <telerik:RadComboBoxItem Value="A" Text="A" />
        <telerik:RadComboBoxItem Value="B" Text="B" />
    </Items>
</telerik:RadComboBox>
<asp:Button ID="btnNextPage" runat="server" Text="Next Page" OnClick="btnNextPage_Click" />

Page1.aspx.cs:
protected void btnNextPage_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Page2.aspx?value=" + RadComboBox1.SelectedValue);
}

Page2.aspx:
<telerik:RadComboBox ID="RadComboBox2" runat="server">
    <Items>
        <telerik:RadComboBoxItem Value="A" Text="A" />
        <telerik:RadComboBoxItem Value="B" Text="B" />
    </Items>
</telerik:RadComboBox>

Page2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        RadComboBox2.SelectedValue = Request.QueryString["value"];
    }
}

Other ways to achieve this include using a multiview control instead of separate pages, or using the postbackurl property to postback to a different page (instead of using the query string)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability of splitting nucleus I'm sorry if this is a dumb question, but I was just wondering.
Say we have a 20 x 20 cm sheet of sulphur, and we have a knife made of iron. If I take the knife, and repeatedly cut the sulphur for an n number of times, what is the probability that I will once hit the sulphur at such a point where an atom had a nucleus, and the nucleus was cut? Is this physically possible? If not, and if atoms do physically exist, why isn't it possible?

A: So no it is not possible to cut a nucleus or an atom in two, it is not even possible for two atoms to even touch because of electrostatic forces between the atoms. The electrons of both atoms will make two atoms strongly repel at some distance. At normal or usual distances, I should say, two atoms will barely have an effect on one another because the distance between those two atmos will be way larger than the distance between the positive nucleus and the negative electrons which are usually of the same number, so the electrostatic forces are basically the same.

A: Compared to other answers, I would say that two atoms can definitely touch each other - this is why solid matter is "stiff" (minimum of van der Waals interaction is of the order of radius of an atomic cloud). The atoms can even overlap and they often do, say excited to a Rydberg state. In the latter case, the cloud of electrons encompasses other neutral atoms with no problem.
The problem is however, that both knife and the sulphur are made of atoms. So the knife is by no means "sharp" at the length scale of an atom. The cloud of electron gas of a first atom can encompass the second atom, but the attractive interaction between electrons of a first atom and a nucleus of a second atom will not cause the split of the nucleus - it is attractive and much weaker than strong interaction holding the nucleus together.
Two nuclei won't hit each other as they are both strongly positively charged and they repel each other.  It is possible to hit two nuclei together but this is done in the accelerator (then they indeed split forming new particles).


text:
Q: Vector Iterators Casting Hey, In C++, I have a vector of type:
vector<BaseClass*> myVector;

In which, I insert (push_back) pointers of derived classes into it.
Now, I want to pop back its elements so I do this:
vector<ADlgcDev*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
 // but before I pop it, I need to shutdown it down
 // so I cast this
 // but this way, I'm unable to call the function
 (DerivedClass*(*iter))->Shutdown();

 myVector.pop_back();
}

but as mention in the comments before I pop it, I need to call its Shutdown() method and the cast is not working properly too. Any resolutions? or is impossible?

A: Could you make Shutdown a virtual function in BaseClass?  Then you wouldn't need a cast.
Also you'll probably have trouble removing items from a vector while iterating.  I'd do it like this:
vector<BaseClass*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
    (*iter)->Shutdown();
}
myVector.clear();

Edit: and another thing, ++iter is generally preferred over iter++.

A: while (!myVector.empty())
{
  ((DerivedClass*)(myVector.back()))->Shutdown();
  myVector.pop_back();
}

Notes:

*

*You should probably use dynamic_cast instead of the hard cast. (If it's sure that there are only DerivedClass objects in the vector, why isn't it std::vector<DerivedClass>?)

*You should probably not have to cast at all, since Shutdown() should be declared in the base class.

*You should probably delete the objects, too, before you pop them off the vector. (But that might not be so.)

*You should probably use a smart pointer which calls Shutdown() (and delete, probably).

Edit: Using std::vector<T>::clear(), as shown by markh44 is probably better than the pop_back().

A: The constructor casting doesn't work for pointers.  Use static_cast if you're sure or dynamic_cast and check.

A: If Shutdown() is a virtual method of the Base class i.e. BaseClass::ShutDown() you should directly call iter->ShutDown();
Otherwise if the method isn't virtual you should use dynamic_cast.
vector<ADlgcDev*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.end(); iter++)
{
 DerivedClassA* a = dynamic_cast<DerivedClassA*>( *iter ) ;
 if ( a ) a->ShutDownA();
 else
 {
 DerivedClassB* b = dynamic_cast<DerivedClassB*>(*iter);
 if ( b ) b->ShutDownB();
 // ... repeat for every class in hierarchy that might be in the vector.
 }
 myVector.pop_back();
}

Anyway you're probably leaking memory, unless ShutDown() deletes the object from itself (which is generally a bad idea ) or you're keeping duplicated pointers and deleting them elsewhere, which is another risky idea.


text:
Q: cont=getActivity() cannot be resolved to a variable I want use in Fragment a AsyncTask and use in AsyncTask findViewById.
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.category,
            container, false);

    View myFragmentView = inflater.inflate(R.layout.category, container, false);
    cont=getActivity();

    new ProgressTask(cont, myFragmentView).execute();
}

private class ProgressTask extends AsyncTask <Void,Void,Void>{
    private Context mContext;
    private View rootView;

    public void RecuperarComentarisFoto(Context context, View rootView){
        this.mContext=context;
        this.rootView=rootView;
    }

    LinearLayout barLayout = (LinearLayout) rootView.findViewById(R.id.barLayout);
    [...]

He say to me that  cont=getActivity(); cannot be resolved to a variable.
What should I setfor cont?
Thanks


text:
Q: PHP: Use preg_match_all to create objects and call object functions I'm trying to use preg_match_all to find instances of a pattern in text, then use that pattern to instantiate a class and finally call a class function to print replacement text for the matching pattern. I don't know if I'm going about it the right way.
I can find and replace this pattern [bandcamp=http://bandcamp-page.com]1[/bandcamp] with this preg_replace function
$text = preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "replacement text here", $text);

But I want to use the matches to create a BandcampAlbum object and call it's player() function which prints out html. This is what I'm trying but to no avail so far.
if (preg_match_all ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", $text, $matches)) {

    foreach ($matches[0] as $match) {
        preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "", $text);
        $bc = new BandcampAlbum($match[0], $match[1]);
        $bc->player();
    }

}

The preg_replace in the foreach loop is intended to just get rid of the matching text. The matching seems to work so I'm guessing I'm doing it the wrong way rather than making a regular expression error.  Any suggestions welcome.

A: As stated in the comments; what you are probably after is preg_replace_callback. Here is an example of its usage with your problem:
function getBandCampMarkup($matches){
    $bc = new BandcampAction($matches[1], $matches[2]);
    return $bc->player();
}

$data = preg_replace_callback("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "getBandCampMarkup", $data);
echo $data;

This is of course assuming the $bc->player() returns a string of the output. If this function just echos the data then you can can use ob_start and ob_get_clean to capture the output as a string as so:
ob_start();
$bc->player();
return ob_get_clean();


text:
Q: What default CSS is preventing me from fully overlapping two elements with relative positioning? Why don't #img1 and #canvas1 fully overlap in the below code? I want them in exactly the same place. I'm layering images with JavaScript animation on canvas. Initial thoughts were that the padding or margin default settings were interfering somewhere. I've tried setting to zero for all elements - it doesn't work. I understand that position:relative positions an element relative to it's normal position. Clearly missing a default setting or something obvious.

<!DOCTYPE html>

Why can't I overlap the below elements?

      <canvas id="canvas1"></canvas>

A: Two things to do:
1.) Don't leave a linebreak or space between the two elements in the HTML code (see below)
2.) Set the left setting for canvas to -52px - you have to consider the 2 x 1px border of the image.

.chapter {
  width: 90%;
  margin: 0 auto;
  max-width: 1000px;
  border: 1px solid red;
}

#img1 {
  border: 1px solid green;
  position: relative;
  left: 50px;
  height: 100px;
  width: 100px;
  margin: 0px;
  padding: 0px;
}

#canvas1 {
  border: 1px solid blue;
  position: relative;
  left: -52px;
  height: 100px;
  width: 100px;
  margin: 0px;
  padding: 0px;
}

Why can't I overlap the below elements?

    <canvas id="canvas1"></canvas>

A: A couple of remarks:

*

*use box-sizing: border-box for 'easier' sizing. With border-box the border width and padding are substracted from the elemenent istead of added on to it. An element with width: 100px, a border-width of 1px and a padding of 10px will be 100 + (2 * 1) + (2 * 10) = 122px wide without box-sizing: border-box but the element will be 100px wide even with the border-width and padding when the box-sizing is set to border-box. See here for a (better) more detailed explanation: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

*When trying to overlap element I find it easiest to keep the surrounding container element as empty as possible. Taking out the h1 element makes overlapping a lot more manageable.

*Change the position of the canvas element to absolute. This way it no longer takes up place in the DOM and it is positioned in the upper left container of its positioning parent (in your example the div.chapter in my answer the div.container). This also helps when trying to have elements line up.

* {
  box-sizing: border-box;
}

.container {
  position: relative;
}

.chapter {
  width: 90%;
  margin: 0 auto;
  max-width: 1000px;
  border: 1px solid red;
}

#img1 {
  border: 1px solid green;
  position: relative;
  left: 50px;
  height: 100px;
  width: 100px;
  margin: 0px;
  padding: 0px;
}

#canvas1 {
  border: 1px solid blue;
  position: absolute;
  left: 50px;
  height: 100px;
  width: 100px;
  margin: 0px;
  padding: 0px;
}

Why can't I overlap the below elements?

      <canvas id="canvas1"></canvas>

A: #img1 {
border: 1px solid green;
position: relative;
left: 56px;
height: 100px;
width: 100px;
margin: 0px;
padding: 0px;
}

this worked...

A: There are certainly better ways to achieve the effect you're going for but to answer your question, I believe the spacing is being caused by the default font size on the parent element. Set the font size to 0px on the chapter div and you can see the elements now overlap each other.


text:
Q: Flutter: about overflow behavior when hiragana and alphabet are mixed in the string of the text widget I'm not particularly troubled by this problem right now, but I don't know the reason for the phenomenon I happened to find, so let me ask you a question.
When the code below is executed on iPhoneSE2, if the second argument of the substring method is 56, only "ああああいいい" will be displayed,
and if the second argument is set to 57, the following alphabet will also be displayed.
I have no idea why. If anyone knows anything, please let me know.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final String str1 = 'ああああいいいaaa,aaaaaaaaaa,aaaaabbbbb,bbbbbbbbbc,cccccccccc,wwwwwwwwww,mmmmmmmmmm,';
    return Scaffold(
      body: Center(
        child: Container(
          //width: 500,
          child:Text(
            str1.substring(0,56),//←here!
            maxLines: 1,
            //overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    );
  }
}


text:
Q: Java WebService adding CDATA field in response I'm working on a webservice where, i created the wsdl and generated the java classes using apache axis2.
The problem I'm trying to solve is, while creating web service response I have to set text with special characters like Books & Pens Or Value is <10>  in some of the fields. I am looking for ways to just put these field content in CDATA sections.
Example response my WebService has to send:
<BOOKSHOP>
  <ITEM><![CDATA[BOOKS & PENS]]></ITEM>
</BOOKSHOP>

I'm not able to find a way to do this. I have googled but found no solution.
Any help would be really appreciated.
I'm aware of converting these special characters explicitly into  & amp ; or & lt;  but that does not work for us.
Also, We want to put just the required fields in CDATA and not entire XML response.
I tried @XmlCDATA but it works only if my text is XML structured.


text:
Q: Did Early AI Researchers Understand Why the Perceptron "Worked"? I was reading about the development of the original Perceptron Algorithm (i.e. the First Neural Network) - if I understand this correctly, a Perceptron is a One Layer and One Neuron "Neural Network". The first perceptron was able to successfully classify pictures of shapes and letters (around 1958).
I am interested in learning about to what extent did Early AI Researchers understand the mathematical limits and abilities of the Perceptron. For instance, I know that many years later, an important theorem in AI called the "Universal Approximation Theorem" was established, that showed a Neural Network in "theory" could perfectly learn any function - but the earliest version of this theorem was established in 1989 (https://en.wikipedia.org/wiki/Universal_approximation_theorem) - 30 years prior to the successful implementation of the first Perceptron.
While doing some reading online, the only theoretical results I came across that suggest early AI Researchers understood the "mathematical abilities" of the Perceptron were:

*

*"X-OR" Problem: It was theoretically demonstrated that a simple Perceptron can not perfectly separate data that is non-linearly separable.

*Perceptron Convergence Theorem: A theoretical result was found that suggests "a finite number of iterations are required to update the weights of the perceptron such that all data  points (provided they are linearly separable) will be perfectly classified" (https://web.mit.edu/course/other/i2course/www/vision_and_learning/perceptron_notes.pdf).
I have the following question : Did the early AI Researchers have "confidence in the mathematical abilities" of the first Perceptron? Or was this more of a trial-and-error experiment which had no mathematical justifications as to if such an experiment was even theoretically possible - let alone in practice?
Thanks!


text:
Q: mathematical biology (steady-states) non-dimensionalisation equation:
\begin{equation} \frac {du}{d\tau}=\frac{\overline{\lambda}_{1} u}{u+1} -\overline{r}_{ab}uv -\overline{d}u
\end{equation}
where $\overline{\lambda}_{1}= \frac {\lambda_{1}}{\lambda_{2} K_{1}}$
Another non-dimensionalisation equations
\begin{equation} \frac {dv}{d\tau}=v(1-v) -\overline{r}_{ba}uv
\end{equation}
THE REAL QUESTION IS: calculate the steady state $(u_4,v_4)$ and $(u_5,v_5)$? Discuss the occurrence of these steady-states in respect of any relationships between the non-dimensional. Note you are not required to determine the stability of these two states.
=>
I have already calculated the steady-states of $(u_4,v_4)$ and $(u_5,v_5)$ which are
$(u_4,v_4)$ =($ \frac{\overline{\lambda}_{1} - \overline{d} -\overline{r}_{ab}}{\overline{r}_{ab} + \overline{d}} ,1)$
$(u_5,v_5)$ =($ \frac{\overline{\lambda}_{1} - \overline{d} -\overline{r}_{ab}}{\overline{r}_{ab} + \overline{d}}$ ,$ 1 - \overline{r}_{ba} \frac{\overline{\lambda}_{1} - \overline{d} -\overline{r}_{ab}}{\overline{r}_{ab} + \overline{d}}$ )
I HAVE ALREADY CALCULATED $(u_1,v_1)$ and $(u_2,v_2)$ and $(u_3,v_3)$ but i an not interested to talk about their steady-state with respect to non-dimensional parameters.
here are the non-dimensional parameters which I have also determined:
$\overline{\lambda}_{1}= \frac {\lambda_{1}}{\lambda_{2} K_{1}}$
$\overline{d}= \frac{d}{\lambda_{2}}$
$\overline{r}_{ab} = \frac{\overline{r}_{ab} K_{2}} {\lambda_{2}}$
$\overline{r}_{ba} = \frac{\overline{r}_{ab} K_{1}} {\lambda_{2}}$
can anyone please please help me in discussion of these steady states $(u_4,v_4)$ and $(u_5,v_5)$ with the above non-dimensional parameters .

A: Shouldn't it be? in which case your steady states are mostly wrong, unless im going blind...
\begin{equation} \frac {dv}{d\tau}=v(1-v) -\overline{r}_{ba}uv
\end{equation}

A: Hint:  In a steady state, all derivatives are zero.  That is the definition of a steady state, and it simplifies the equations considerably.


text:
Q: How to replace a value in pandas? Trying to group 23 different labels in second last column of "KDDTest+.csv"  into four groups. Please note, I have deleted the last column of the csv prior to doing this.
I have read the .csv file using
df = pd.read_csv('KDDTrain+.csv', header=None, names = col_names)

where
col_names = ["duration","protocol_type","service","flag","src_bytes",
    "dst_bytes","land","wrong_fragment","urgent","hot","num_failed_logins",
    "logged_in","num_compromised","root_shell","su_attempted","num_root",
    "num_file_creations","num_shells","num_access_files","num_outbound_cmds",
    "is_host_login","is_guest_login","count","srv_count","serror_rate",
    "srv_serror_rate","rerror_rate","srv_rerror_rate","same_srv_rate",
    "diff_srv_rate","srv_diff_host_rate","dst_host_count","dst_host_srv_count",
    "dst_host_same_srv_rate","dst_host_diff_srv_rate","dst_host_same_src_port_rate",
    "dst_host_srv_diff_host_rate","dst_host_serror_rate","dst_host_srv_serror_rate",
    "dst_host_rerror_rate","dst_host_srv_rerror_rate","label"]

If I print out the first 5 rows of the dataframe, this is the output (please note the 'label' column):
using print(df.head(5))
   duration protocol_type  ... dst_host_srv_rerror_rate    label
0         0           tcp  ...                     0.00   normal
1         0           udp  ...                     0.00   normal
2         0           tcp  ...                     0.00  neptune
3         0           tcp  ...                     0.01   normal
4         0           tcp  ...                     0.00   normal

I've tried both these methods for grouping based on what I found online:
Method 1:
df.replace(to_replace = ['ipsweep.', 'portsweep.', 'nmap.', 'satan.'], value = 'probe', inplace = True)
df.replace(to_replace = ['ftp_write.', 'guess_passwd.', 'imap.', 'multihop.', 'phf.', 'spy.', 'warezclient.', 'warezmaster.'], value = 'r2l', inplace = True)
df.replace(to_replace = ['buffer_overflow.', 'loadmodule.', 'perl.', 'rootkit.'], value = 'u2r', inplace = True)
df.replace(to_replace = ['back.', 'land.' , 'neptune.', 'pod.', 'smurf.', 'teardrop.'], value = 'dos', inplace = True)

Method 2:
df['label'] = df['label'].replace(['ipsweep.', 'portsweep.', 'nmap.', 'satan.'], 'probe',regex=True)
df['label'] = df['label'].replace(['ftp_write.', 'guess_passwd.', 'imap.', 'multihop.', 'phf.', 'spy.', 'warezclient.', 'warezmaster.'], 'r2l',regex=True)
df['label'] = df['label'].replace(['buffer_overflow.', 'loadmodule.', 'perl.', 'rootkit.'], 'u2r',regex=True)
df['label'] = df['label'].replace(['back.', 'land.' , 'neptune.', 'pod.', 'smurf.', 'teardrop.'], 'dos',regex=True)

However, this is still the output of printing the first 5 rows of the dataframe:
After replacing, first 5 rows of df:

   duration protocol_type  ... dst_host_srv_rerror_rate    label
0         0           tcp  ...                     0.00   normal
1         0           udp  ...                     0.00   normal
2         0           tcp  ...                     0.00  neptune
3         0           tcp  ...                     0.01   normal
4         0           tcp  ...                     0.00   normal

I'm expecting the label column in row 2 to read 'dos' instead of 'neptune', but it's not happening.
What am I doing wrong? Any help is appreciated.

A: Maybe you are using "neptune." instead of "neptune"
My tests seem to work with "neptune"
>>> df
     label
0  neptune
>>> df["label"].replace(["neptune."], "normal", regex=True)
0    neptune
Name: label, dtype: object
>>> df["label"].replace(["neptune"], "normal", regex=True)
0    normal
Name: label, dtype: object
>>> df["label"].replace(["neptune"], "normal")
0    normal
Name: label, dtype: object

A: By using "neptune." as the to_replace value with regex = True, you are telling Pandas to look for "neptune" and any single additional character (e.g., "neptuneX" or "neptune!"). Since that extra character is not present, the whole phrase does not get replaced. Instead you could use just "neptune", or "neptune.?" for 0 or 1 extra characters, or "neptune.*" for 0 or any greater number of extra characters.
Without regex = True, you are telling Pandas to look for literal "neptune." phrase.


text:
Q: Line up data spread across multiple Excel columns I have scoured the Internet and tried a billion different VLOOKUP formulas and Visual Basic marcos to no avail on this one.
I have 4 columns of letters and numbers (identifiers).  Some of the identifiers are duplicated in the 4 columns.  I need to line up the data in the columns so that I can see which identifiers are in multiple columns.  There are some identifiers in each column that are not in any other columns (each column had a different number of entries, so the identifiers do not currently line up).
I want it to look something like this (minus the ...s):
Column A..............Column B...........Column C..............Column D
R101...............................................R101........................
R102.........................R102................................
R103.................................................................................R103
R104........................R104.................R104.........................
.................................R105.........................
There are a couple of additional columns of data associated with Column A that need to remain tied to the identifier they correspond to in Column A (so the data in Column E and F should stay tied to the item the correspond to in column A).  The identifiers in Columns B, C, and D can move about however they need to to line up with their matches in A.  Honestly, all I really care about is whether values in B, C, and D are also in A.  I'm happy to use a macro.  The identifiers in Columns B, C, and D are also avaialble in other sheets of the same workbook -- I moved them into the same sheet as Column A because I thought it would be easier to make this work... but I could be wrong!
Can someone help me with this?  Very explicit copy-paste type instructions are appreciated!  I currently have the data organized into adjacent columns A, B, C, and D.

A: I am not very sure I have understood your question , but suppose your data in column A ranges from say A2 through A10.
In column B , starting from cell B2 , put in the formula :
=IF(ISNA(MATCH($A2,B$2:B$10,0)),"",$A2)
Copy this down till B10 ; copy the formulae in B2:B10 to columns C and D.
What this does is where there are matches in columns B , C and D for data in column A , the entries will be displayed , otherwise the cells in columns B , C and D will be blank.


text:
Q: Rails - Factorygirl - Skip after_create Calls I have a factory for a model that I'd like to skip the after_create call backs when I create it. I've tried a few variations of the following (from another stackoverflow question), ...
before_create { |page| Page.skip_callback(:create, :after_create, :retrieve_stream_profile, :update_stream_profile) }

Basically, I'd like the model to be saved in the database when in an rspec test I do something like ...
  @page = FactoryGirl.create :page

but, I don't want any of the after_create callbacks to happen.

A: It looks like you need to have multiple lines for each callback you'd like to skip. In my case, it'd look something like ...
after_build { |page| page.class.skip_callback(:create, :after, :add_page_for_superadmins) }
after_build { |page| page.class.skip_callback(:create, :after, :update_stream_profile) }
after_build { |page| page.class.skip_callback(:create, :after, :grab_stream) }
after_build { |page| page.class.skip_callback(:create, :after, :retrieve_past_insights) }

So, after building this page, skip all the callbacks. There may be a more elegant way to do this ... thinking about it, I don't think I tried an array as the last parameter for each of the four methods to skip.


text:
Q: Index 1 Fano threefolds and Serre's construction Let $X$ be a Fano threefold of index $1$ and genus $8$ (i.e. degree $14$). In this (top of page 5) paper, the authors state that the rank $2$ Gieseker stable vector bundle $E_0$ with $c_1=1$ and $c_2 =5$ giving the embedding $X \hookrightarrow \mathrm{Gr}(2, 6)$ is defined by the Serre construction for any elliptic quintic $C$ on $X$. They link this paper as a reference for this, but having looked through I can't seem to find the relevant part of the paper.
Would I be correct in  assuming then, that $E_0$ fits into the short exact sequence
$$ 0 \to \mathcal{O}_X \to E_0(H) \to I_C(2H) \to 0  $$
where $H$ is the choice of polarisation on $X$, and $C \subset X$ is an elliptic quintic. I'm mimicking the Serre construction on cubic threefolds to obtain instanton bundles here, but I'm not sure whether we should use the same short exact sequence or a different one for my Fano threefold case?
Thanks.
Edit: I've had some more thoughts as follows: $X$ is a threefold and $C$ is a codimension $2$ subscheme which is a locally complete intersection, and $C$ can be regarded as the locus of a section $s_0$ of the vector bundle $E_0$. Then we should have a short exact sequence
$$ 0 \to\mathcal{O}_X \xrightarrow{s_0} E_0 \to I_C \otimes \Lambda^2E_0 \to 0 .  $$
I guess my question becomes: what is $\Lambda^2E_0 = \det (E_0)$? My Fano threefold $X$ is anticanonically embedded, and since the embedding is "given" by $E_0$, I guess we should have $\det(E_0) =  - K_X = \mathcal{O}_X(H)$, the second equality because $X$ is index $1$. I don't know if this is actually the correct thinking though.

A: The bundle $E_0$ is defined by the exact sequence
$$
0 \to \mathcal{O}_X \to E_0 \to I_C(H) \to 0,
$$
where $H = -K_X$ is the anticanonical polarization. You can find this sequence on page 14 of the paper.


text:
Q: Kivy Touch - Raspbian Stretch 26.07 after a long time trying it by myself i think it is the right time to ask for help.
my setup:

*

*raspberry pi 3 B+

*official 7' raspberry Touchscreen

*Kivy installed

*Raspbian Stretch 26-07 image
I have problem to activate the touchscreen while using kivy on the newest raspbian strech image.
normally it worked with a clean installed raspbian stretch image, clean installed kivy and after running a kivy demo there is an folder named '.kivy' in /home/pi.
in this folder in need to configure the touchinputs with following commands:
mouse = mouse
mtdev_%(name)s = probesysfs,provider=mtdev
hid_%(name)s = probesysfs,provider=hidinput

but i cant find this folder and cause of that i cant use the touchscreen with kivy.
I followed step 1, 2 and 3:
kivy documentation
when i run whereis kivy:
whereis .kivy :
/usr/bin/. /usr/sbin/. /usr/lib/. /bin/. /sbin/. /etc/.fstab /etc/. /etc/.java /lib/. /usr/games/. /usr/local/bin/. /usr/local/sbin/. /usr/local/etc/. /usr/local/lib/. /usr/local/games/. /usr/include/. /usr/local/. /usr/share/. /opt/sonic-pi/bin/. /opt/vc/bin/. /usr/man/man3/. /usr/man/man1/. /usr/share/man/ko/. /usr/share/man/sv/. /usr/share/man/man2/. /usr/share/man/sl/. /usr/share/man/it/. /usr/share/man/man6/. /usr/share/man/man7/. /usr/share/man/tr/. /usr/share/man/pl/. /usr/share/man/hu/. /usr/share/man/cs/. /usr/share/man/pt_BR/. /usr/share/man/fr.UTF-8/. /usr/share/man/nl/. /usr/share/man/pt/. /usr/share/man/man5/. /usr/share/man/da/. /usr/share/man/man8/. /usr/share/man/de/. /usr/share/man/id/. /usr/share/man/gl/. /usr/share/man/vi/. /usr/share/man/ja/. /usr/share/man/es/. /usr/share/man/man3/. /usr/share/man/fr/. /usr/share/man/zh_CN/. /usr/share/man/man1/. /usr/share/man/fi/. /usr/share/man/fr.ISO8859-1/. /usr/share/man/ru/. /usr/share/man/zh_TW/. /usr/share/man/man4/. /usr/share/info/. /usr/src/sense-hat/.

Do you have some ideas for me how I can fixed that ?

A: after days for searching, I found finally the folder:
/root/.kivy
for the future when the folder change places:
if you start the kivy script from another computer with Putty (ssh), you can see in the first line after starting the script the path to this folder.

[INFO   ] [Logger      ] Record log in /root/.kivy/logs/kivy_18-07-26_59.txt

best regards
Danjin


text:
Q: socket call recvfrom appears to be stuck in infinite loop I've inherited a piece of code from one of my colleagues that I need to tidy up and turn into some in-house IP.
My problem is reading the socket. I have debugged the code and I can see that the socket is opened correctly. Everything runs fine until the interpreter runs the following line of code
    data, addr = any_struct.recv_socket.recvfrom(2048)

The interpreter goes nuts and I have to kill python through the task manager to stop it. I've tried using a debugger to step through the code, but it can't/won't step into the recvform call.
I'm in the early stages of turning this code into something worthwhile. Any suggestions as to how I can debug/fix this problem? I'm sure I'm going to kick myself when I find out what the problem is, but no lightbulbs at the moment.
I have used sockets before, but that was quite some time ago in C, not even C++

A: As @nos has already mentioned in the comments, if there is no data to receive then the call would generally block until there was data to return. However, your application sitting there waiting for input doesn't meet any sensible definition of the interpreter "going nuts" so I'll assume this isn't the case.
Three possibilities spring to mind. One is that the socket is set to non-blocking when it's created - check the socket options that are used. In this case, of course the function won't block - in Python I believe this is communicated via an appropriate error.
The second possibility is that the socket is connection-oriented (e.g. TCP) and the connection has been closed - this would result in any recv()-family call returning empty data as soon as you call it, which typically leads to busy loops if the code hasn't been written with this in mind.
The third possibility is that some other part of your application (perhaps even another thread of execution?) has closed the socket under your feet and you're calling recvfrom() on an invalid socket. I would rather expect this to raise an immediate exception.
I would suggest the following steps:

*

*Confirm the exact type of socket in use - if connection-oriented (e.g. TCP) then I suggest just using recv() instead of recvfrom().

*Put some trace indicating the return code of recvfrom(). If you can't print to standard output then open a file with append mode and write to that. If you have literally no means to get debug trace into your code then debugging any problem is going to be like ice-skating uphill I really suggest you address that. Try looking at the logging module for a convenient way to do this (but for now just dumping in a hard-coded filename might be easier).

*Make sure you wrap the recvfrom() call in a generic try...except which catches all subclasses of Exception and logs some trace. You can always re-raise them if you want to do this without affecting the flow of the code.

Based on the results of the above, you can choose your next steps. If the interpreter is "going nuts" when recvfrom() hasn't returned, then this means either you've hit some odd bug in Python or the libraries it's using (unusual!); or you've got other threads in your application which are causing the issue.
One final thought is that if you're on Windows then I'm not sure whether the firewall might lead to odd behaviour in recvfrom() if your application isn't enabled; but I would still expect this to manifest itself as either an odd return code or exception from recvfrom() within Python.


text:
Q: How are you meant to do this so that it works? SVN tree conflicts, etc We have a trunk that we've branched.
In the branch we moved files using TortoiseSVN into new folders to re-organise the structure.
Those files were also worked on in the trunk.
So let's call the file /trunk/file1.cs
and /branch/folder1/file1.cs
We're now trying to merge the trunk changes into the branch and svn is screaming about tree conflicts?
How are you meant to do this scenario.
btw we're using svn 1.6.6 on both server and client although upgrade was done after the branch was created (not sure if that makes a difference?)

A: Move the file to where it is supposed to be (Subversion complains because it can't figure this out by itself), and then mark the conflict as resolved.


text:
Q: Page numbering and sections Consider this image:

As you can see I am having difficulties with the page numbering. The left page is 15 (section 2) as it should, but the right one is 2 (section 4). What I think that happened:
By inserting a multi-column lay-out at the bottom of the left page, that page is divided into three sections. At the top section 2, then the multi-column (section 3) and at the bottom the section after the columns (section 4).
Because section 2 is force-started at 1 (as it should) and new sections by default link to the previous one, section 3 (the multi-column) 'thinks' it has a page number as well. Because it is linked to the previous section (2) it starts again at page number 1. Then, of course, section 4 follows which I can edit freely. The problem is that I cannot seem to edit the "invisible footer" of section 3 so that it is NOT linked to section 2 anymore and that I can allow it to let it continue its numbering from the previous section.
How can I do this? I've been struggling with this for days but can't get it to work.
I hope that my explanation is clear.

A: Click in Section 3 (the multi-column block) and type Ctrl+Enter, to force a page break.  This will give you a page ("16") that exposes the Section 3 header and footer.  Configure them as needed, then go back and delete the page break.


text:
Q: User able to access SharePoint even without license I have a few users in my tenant for whom I have disabled SharePoint, OneDrive and Office Online. But the users are still able to go to SharePoint sites and upload/download documents, edit lists etc. They can still navigate to OneDrive for Busines but cannot get teh upload/download/sync menu.
I tried revoking licenses from UI and with powershell too I can see they do not have those licenses. Any more steps to take? One user was not assigned these licenses at the time of creating his account but still can access SharePoint.

A: The users are likely members of an AD, from where they get the permissions despite excluding them individually from the Office tools. Have a look at your AD on one of the users part of your description.
Alternatively, on SP, you can check what permissions each user has on a site using the Check Permissions -tool, which should lead to conclusions about the users' group memberships.
When using the built-in Everyone group, the group covers your AD users and external users, so even if you wouldn't have the user in your AD, but your environment would allow external users, they can access the site after receiving an invitation. Also, even if the user only exists in AD, but doesn't belong into any group, the user is by default part of this coverage. Using SharePoint doesn't require an Office license.

A:
Not assigning a license to an individual user will not physically
  prevent them from accessing a SharePoint site

What you have to do is to manage the permissions for the SharePoint Online sites. Managing permissions will work for you.
Additionally, you have to consider the comments from @moe


text:
Q: How to search data using OleDbDataReader in VB.NET? With ms access as the database storage software.
And if you know of other ways on how to read data base on a certain criteria and displaying the results that meets the criteria.

A: The normal way to do this is to create a SQL query that does all the data searching/filtering/ordering on the database so you don't have to do it in code.
Doing it that way, all you have to do is iterate through the results in the DataReader.
If you're unfamiliar with SQL, here is a good place to get started.


text:
Q: selector { text-align: "." right; } I'm extremely new to coding so forgive if this is a basic question; however, I need a little direction and hope someone is able to provide an answer.
I'm reading an article pertaining to the alignment of numerical data to a decimal point within a table https://alistapart.com/article/web-typography-tables/#section6
which uses the below declaration for example:
td { text-align: "." center; }

Below is the basic table code I'm testing the syntax on.

        <!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link rel="stylesheet" href="style.css" type="text/css" />

            October Expenses

          <colgroup>
            <col style="text-align: right" />
          </colgroup>

              Date
              Expense
              Cost
              Payment Method

              01.10.21
              75" Samsung tv.
              $1,995.00
              Zip

              07.10.21
              Netflix
              $15.99
              Debit

              12.10.21
              Paint Supplies
              $102.14
              Debit

              18.10.21
              Pencil
              $0.80
              Debit

              Total
              $2,113.93

/* CSS */
    caption {
      font-size: 1.3rem;
      font-weight: bold;
      padding-bottom: 10px;
    }
    table,
    th,
    td {
      border: 1px solid black;
      border-collapse: collapse;
      padding: 1%;
    }
    thead th:nth-child(n) {
      width: 20%;
    }
    tbody tr:nth-child(even) {
      background-color: #adc2a9;
    }
    tbody tr:nth-child(odd) {
      background-color: #d3e4cd;
    }
    thead th:nth-child(1) {
      text-align: right;
    }
    thead th:nth-child(2) {
      text-align: left;
    }
    thead th:nth-child(3) {
      text-align: center;
    }
    thead th:nth-child(4) {
      text-align: left;
    }
    tbody td:nth-child(1) {
      text-align: right;
    }
    tbody td:nth-child(3) {
      text-align: center;
    }
    caption {
      font-size: 1.3rem;
      font-weight: bold;
      padding-bottom: 10px;
    }
    table,
    th,
    td {
      border: 1px solid black;
      border-collapse: collapse;
      padding: 1%;
    }
    thead th:nth-child(n) {
      width: 20%;
    }
    tbody tr:nth-child(even) {
      background-color: #adc2a9;
    }
    tbody tr:nth-child(odd) {
      background-color: #d3e4cd;
    }
    thead th:nth-child(1) {
      text-align: right;
    }
    thead th:nth-child(2) {
      text-align: left;
    }
    thead th:nth-child(3) {
      text-align: center;
    }
    thead th:nth-child(4) {
      text-align: left;
    }
    tbody td:nth-child(1) {
      text-align: right;
    }
    tbody td:nth-child(3) {
      text-align: "." center;
    }

However, when I employ this code within my  elements located on separate rows and contain various decimal placed numbers, the output doesn't appear to line up the periods directly beneath each other. I have the text-aligned to center to test this . syntax (I understand numbers should be styled to text-align: right;)
Am I misinterpreting the function of this syntax? Am I not doing something correctly? or does this syntax simply not work?


text:
Q: Does innodb use snapshot to help replication of a new secondar like redis cluster? I am reading InnoDB replication and find that it uses binlog for secondaries to replicate primary node. This is strange to me to find that "secondaries download the binlog to replicate". Wouldn't it be more efficient to get a snapshot of the primary node first, and then append binlog for new changes just like what Redis cluster do?
So what is the true process of the replication between a newly added secondary node and a primary node?


text:
Q: How does DocumentDB failover happen if the the reader instance and writer instance have different instance types? I have a DocumentDB cluster with exactly one replica instance ( db.r5.16xlarge ) and a primary instance (   db.r5.24xlarge ).
If something happens to the primary instance and a failover occurs, the replica instance will act as the new primary instance.
Once the previous primary instance becomes ready, will it again failover back to my initial     db.r5.24xlarge primary instance?

A: No, it will not failover again to promote the previous primary instance. You'll have to failover manually to promote the bigger instance.
Better control can be achieved with 3 instance using failover tiers. Each replica instance is associated with a failover tier (0–15), where a lower tier means the instance has higher priority to be chosen for election.
For example, a cluster with two db.r5.24xlarge set on tier-1 and one db.r5.16xlarge set on tier-2. If a primary db.r5.24xlarge becomes unavailable, then the other db.r5.24xlarge will be promoted because it has a higher priority.
Reference.


text:
Q: Cascade on update and delete wih django I cannot find an option to cascade update or delete in the model api. Am wondering if there is a manual out there that can help me pass this db option when sycning the db.
any idea's?

A: Look at the ForeignKey docs. It says:

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument.

So the default behavior is to cascade on delete, but you can change it by specifying something like this:
class Foobar(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET(User.objects.get_or_create(username="foooobarrrr")[0]))


text:
Q: Can't seem to add a new row to a filtered table using my current VBA I've been wracking my brain trying to solve this issue, and I bet it's super simple, but the answer is eluding me!
I'm trying to add a new row to a filtered table in Excel via a macro button. The macro works when the table is unfiltered but, due to client requirements, they want to add rows regardless of how filtered the table is. The user uses the column header dropdowns to filter the table - sometimes three or filters applied at a time.
Here is the current VBA code I'm using;
Public Sub Add_new_row_2()
    Dim tbl As ListObject
    Dim rw As Range

    Set tbl = Sheets("Master Input").ListObjects(1)
    Set rw = tbl.ListRows.Add.Range

    Sheets("Data").Range("CF2:KX2").Copy rw
End Sub

The code copies a fully formatted blank row within a range (CF2:KX2) located on a separate tab and pastes the row to the bottom of the table. It works well whilst the table is unfiltered or sorted, but when the user tries to apply multiple column filters, they get a Runtime error "1004".
Is there a way to add a new row despite any heavy filtering?


text:
Q: Can "rentee" be used to refer to one who rents an item? I am working on a project where I need to be able to distinguish between one who is offering something for rent, and one who is renting from someone. The phrases used need to be short and concise.
The context is not real estate thus commonly suggested alternatives like landlord or tenant do not fit.
I was thinking maybe rentee could work, thinking it followed the same style as employer versus employee, for example.  Some quick googling, however, seems to indicate that rentee is not a valid word, but some people do occasionally use it.

A: I think a reasonable distinction between the two parties involved would be "the owner" and "the renter". See for example https://www.pandadoc.com/free-car-rental-agreement-template.
In a specific agreement, "owner" would probably be replaced by owner's legal name, i.e. "Avis" in
http://www.avis.co.uk/dms/avis/rentalAgreement/UK/en_GB/avis-uk-rental-agreement-terms-conditions.pdf.
I'm not a lawyer, but "lease" and "rental" are not quite the same thing. See http://www.allbusiness.com/whats-the-difference-between-a-rental-agreement-and-a-lease-for-a-rental-property-4099-1.html for example.

A: Rentee is a rare formal term whose more common 'form' is lessee:

*

*One who rents (property, etc.).

(Wiktionary)
Lessee:

*

*n. the person renting property under a written lease from the owner (lessor). He/she/it is the tenant and the lessor is the landlord.

(The Free Dicrionary )
Ngram: rentee vs lessee.
Renter and  tenant are more common terms,

A: I think you do not need it when the dictionary has the word renter.
Oxford Advanced Learner's Dictionary, 8th edition
renter
BrE   / rentə(r) /
NAmE   / rentər /
  noun
1   a person who rents sth
house buyers and renters
© Oxford University Press, 2010
Why doesn't the word tenant match?

A: "er/ee" and used to describe the person or thing doing something, and the person or thing it is done to. So, for example, an "employer" is someone who employs people, and an "employee" is someone who is employed".
This doesn't work the way you want with "rent". A "renter" who would be someone who rents something, and a "rentee" would be someone who is rented. But we don't normally rent people -- unless you're talking about charging for temporary use of a slave. We rent objects. If, say, we have a rental agreement for a car, I'd think the "rentee" is the car, not either party.
As to substance, I believe @alephzero has the best answer: You call the parties the "owner" and the "renter".

A: The pair of words you are looking for are lessor and lessee. The lessee is the one who rents the property. According to Investopedia, the property does not have to be real estate, nor does it even need to be tangible.

DEFINITION of 'Lessor'
  The owner of an asset that is leased under an agreement to the lessee....
  The leased asset can either be tangible property such as a home, office, car or computer, or intangible property like a trademark or brand name.

(From Investopedia)
Lessor and lessee are used in rental contracts, and they are short (albeit formal) terms.

A: Not a term, but possible solution.
If you are doing a document or other project result that would be read from beginning to end (or has otherwise reasonable starting point for all users), it would be possible to define the terms in the beginning of the document. Instead of using renter and rentee, used terms might be for example owner and customer, with the definition in the beginning of the document stating clearly that for the rest of the document, term Owner will be used for people who are renting out stuff and term Customer will be used for persons who rent stuff from Owners.
Obviously there might be business related reasons exact terms Owner and Customer are not usable, but you might find other suitable terms related to the actual business.
(While I do think that from language point of view stating "define a new word" is not optimal solution, I somehow got the impression that this might be needed in info and/or contract papers where unambiguousness if often more important than most elegant use of language.)

A: I found this ambiguous also while preparing advertising projects, so after reading this here went to dictionary.com and realized the fundamental sense, so the renter is bi-directional noun form, as genitive for the provider or accusative case for given/taker determined by role either, but principality renter is the owner with holding rights who uses property by payment of rent, either way.

renter
  [ ren-ter ]
  noun
  "a person or organization that holds, or has the use of, property by payment of rent"

And, so the rentee term should be used more as both business information evolving together with the common culture. Regards


text:
Q: Unit Testing StreamingOuput as Response entity Jersey I am doing something similar to mentioned in
Example of using StreamingOutput as Response entity in Jersey
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response streamExample(@Context UriInfo uriInfo) {
  StreamingOutput stream = new StreamingOutput() {
    @Override
    public void write(OutputStream os) throws IOException,WebApplicationException {
    try{
      Writer writer = new BufferedWriter(new OutputStreamWriter(os));
      //Read resource from jar
      InputStream inputStream = getClass().getClassLoader().getResourceAsStream("public/" + uriInfo.getPath());

      ...//manipulate the inputstream and build string with StringBuilder here//.......
      String inputData = builder.toString();
      Writer writer = new BufferedWriter(new OutputStreamWriter(os));
      writer.write(inputData);
      writer.flush();
    } catch (ExceptionE1) {
        throw new WebApplicationException();
      }
    }
};
  return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
}

I am trying to unit test this by mocking URIInfo like mentioned in How to get instance of javax.ws.rs.core.UriInfo
  public void testStreamExample() throws IOException, URISyntaxException {
        UriInfo mockUriInfo = mock(UriInfo.class);
        Mockito.when(mockUriInfo.getPath()).thenReturn("unusal-path");
        Response response = myresource.streamExample(mockUriInfo);}

I want to be able to check that I get an Exception when I switch the path to jar to something else.But, when I run/debug the test, I never enter the
public void write(OutputStream os) throws IOException,
            WebApplicationException {...}

part and I only always hit the return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
Am I missing something very obvious here??

A: Because the stream is not written to until it hits the MessageBodyWriter (which is the component that ends up calling the StreamingOutput#write).
What you can do, is just get the Response from the return and call Response#getEntity() (which returns an Object) and cast it to StreamingOutput. Then call the write method yourself, passing an OutputStream, maybe a ByteArrayOutputStream so you can get the contents as a byte[] to check it. It all would look something like
UriInfo mockInfo = mockUriInfo();
Response response = resource.streamExample(mockInfo);
StreamingOutput output = (StreamingOutput) response.getEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
output.write(baos);
byte[] data = baos.toByteArray();
String s = new String(data, StandardCharsets.UTF_8);
assertThat(s, is("SomeCharacterData"));


text:
Q: Angular 8 and Kendo DropDownList Component: Why does a click on dropdown cause a "re-computation" of ngStyle inside an  with an *ngFor? I edited this code on Stackblitz (the original link is the first link to Stackblitz here, under the "Primitive Values" section: https://www.telerik.com/kendo-angular-ui/components/dropdowns/dropdownlist/value-binding/) in this way:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `

        Selected Value: {{selectedValue}}

    <kendo-dropdownlist [data]="listItems" [(ngModel)]="selectedValue"></kendo-dropdownlist>
    <ng-container *ngFor="let item of listItems;">
      {{item}}
    </ng-container>
  `
})
export class AppComponent implements OnInit {
    public listItems: Array<string> = [ "Small", "Medium", "Large" ];
    public selectedValue: string = "Medium";

public ngOnInit() {
   console.log('onInit');
}

onChangeStyle(item) {
  console.log(item);
  return {'color': 'red'}
}

}

I cannot understand the reason why clicking the dropdown triggers the onChangeStyle() function for each item in the array; without even selecting it. The same happens when clicking out of the dropdown to close the items list. As demonstrated on the console, every click on the dropdown menù causes three executions of console.log().


text:
Q: Safari Content Blocker Extension Showing Error Domain=SFErrorDomain Code=3 "(null)" I'm using safari content blocker extension in my app, i want to use array for blocking using nsuserdefaults , but extension showing this error on reloadContentBlocker "Error Domain=SFErrorDomain Code=3 "(null)"", and here is my code for extension:
func beginRequest(with context: NSExtensionContext)
{

    let userDefaults = UserDefaults.standard
    let decoded  = userDefaults.object(forKey: "teams") as! Data
    let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! NSArray
    let attachment = NSItemProvider.init(item: decodedTeams, typeIdentifier: kUTTypeJSON as String)

    let item = NSExtensionItem()
    item.attachments = [attachment]

    context.completeRequest(returningItems: [item], completionHandler: nil);

}

Please help me to remove this error.

A: You might have an exception handling issue within the endpoint Swift code. Check the Console for further investigation. For example,
SafariWebExtensionHandler.swift:34: Fatal error: Unexpectedly found nil while unwrapping an Optional value


text:
Q: bsearch() on an array of strings in C I am implementing a code in C so as to copy a string in an array of characters ( string ) and then later do a bsearch on it. But unexpectedly the bsearch returns false for results that should be true.
I am guessing it has something to do with how i am inserting the string in the first place during insert. You could consider this as insertion and search on the leaf node of a btree.
I am coding this in a multi - file framework so cant post all code. posting relevant parts
Structure of the array of strings for easier visualization -
array of strings ( array of array of chars )
                            --
                          0 -- array of characters ( size may be 5 )
                          1 -- array of characters ( size may be 7 )
                          2 -- array of characters ( size may be 10 )

or

keys = [
         [ s t r i n g 1 ]
         [ s t r i n g T w o ]
         [ s t r i n g T H R E E ]
       ]

function to insert -
void insert_in_leaf_node(struct leaf_node * node, u32 len, u8 * key){
    if (node->no_of_keys > 1 ) {
       if (!search_in_fat(node, len, key)) {
            node->keys[node->no_of_keys] = (char *) malloc(sizeof(char) * len);
            strncpy(node->keys[node->no_of_keys], (char *) key, len);                                                              // copy key to array
            node->keys[node->no_of_keys][len] = '\0';
            node->no_of_keys += 1;
            qsort(node->keys, (size_t) node->no_of_keys, sizeof(char *), cstring_cmp);                                          // sort alphabetically to enable bsearch later
        }
    } else {
        node->keys[node->no_of_keys] = (char *) malloc(sizeof(char) * len);
        strncpy(node->keys[node->no_of_keys], (char *) key, len);                                                              // copy key to array
        node->keys[node->no_of_keys][len] = '\0';
        node->no_of_keys += 1;
        qsort(node->keys, (size_t) node->no_of_keys, sizeof(char *), cstring_cmp);                                          // sort alphabetically to enable bsearch later
    }
}

code to search -
bool search_in_fat(struct leaf_node * node, u32 len, u8 * key){
    if(!bsearch(key,node->keys,(size_t)node->no_of_keys, sizeof( char * ),(int(*)(const void*,const void*)) strcmp)) return false;
    return true;
}

cstring_cmp functione used in insert function -
int cstring_cmp(const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
    /* strcmp functions works exactly as expected from
    comparison function */
}

In case anyone is wondering whats in key, here is how a key array is populated earlier and a set / get function is called with indivisual key each time ( the set / get functions call the above functions )
code for trace load from file to generate array of keys -
( __samples holds the keys )
bool
load_trace(const char * const filename)
{
  char * buf = NULL;
  size_t size = 0;
  FILE * fin = fopen(filename, "r");
  if (fin == NULL) return false;
  u64 i = 0;
  // count for lines
  while (getline(&buf, &size, fin) >= 1) {
    i++;
  }
  rewind(fin);
  __samples = malloc(sizeof(char *) * i);
  __sizes = malloc(sizeof(u32) * i);
  __nr_samples = i;
  ssize_t len = 0;
  i = 0;
  while ((len = getline(&buf, &size, fin)) >= 1) {
    if (buf[len-1] == '\n') { // remove trailing '\n'
      len--;
      buf[len] = '\0';
    }
    __samples[i] = strdup(buf);
    __sizes[i] = len;
    i++;
  }
  free(buf);
  fclose(fin);
  return true;
}

P.S : this part was not coded by me, but by my senior when building the framework.
What could be the problem? I have done quite a bit of googling but no positive results yet.
Thank You!

A: You can't pass strcmp() as the comparison function for bsearch(). That function needs to take pointers to the elements to compare (In this case a pointer to a pointer to a string, though the actual type of the functions arguments need to be const void *), while strcmp() expects a pointer to a string. There's an extra layer of indirection that it doesn't handle.
You don't show the function, but the cstring_cmp() function you use with qsort() can probably be used.
The first argument of the bsearch() comparison function is the pointer given as the key, the second argument is a pointer to the current element of the array being compared, where with a qsort() comparison function, both arguments are pointers to elements. So if you make the key argument to bsearch() a pointer to the thing you're looking for, both will work with the same function. In other words, bsearch(&key, ...) is good, bsearch(key, ...) isn't. You can also have a bsearch()-specific comparison function that will work with that second case. See https://stackoverflow.com/a/15824981/9952196 for an example.


text:
Q: How to change the owner of perforce workspace? I cloned a workspace in perforce from other credentials (as i was having some issue with my account back then due to permissions). Now i have the relevant permissions so want to change the owner of that workspace.
In p4v tool, I logged in from the account through which the workspace was created and i tried to change the owner in the advanced options but it gives an error "Client specification failed: You can't create another user's workspace."
Any ideas on how can we change the owner ?

A: I'd recommend using the command line as it's much faster
p4 client <workspace name>

Then change the Owner: to the one you want, save and you're done.


text:
Q: How do i retrieve this information using javascript? I want to retrieve the information between "tmad=" and "&tmpageid" using javascript.
example: www.url.com/tmad1234&tmpageid88

A: Assuming you mean www.url.com/tmad=1234&tmpageid88 the following should do the trick
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

getQueryVariable("tmad");


text:
Q: Files for FTP in cms Drupal How can I find files for FTP in cms Drupal,where I can edit the code? There are a lot of folders and files, how to understand them? How or where can I see the required file pathes?

A: You should put your files in /sites/all dir.
Your theme(s) should be in /sites/all/themes and modules in /sites/all/modules, libraries in /sites/all/libraries. Don't change files out of /sites/all. By "your" I mean also on themes and modules you download/buy.


text:
Q: #memsql lowercase table names we are evaluating memsql to port our mysql Web App to Memsql.
Mainly our software is developed using .net on windows platform.
Last year we ported the Database layer to mysql on a linux server. First we had the problem that a select on a Table was case sensitive, because in .Net and windows it was not a problem to mix cases in Table names. This means if the table is named Test1 in Database, you were able to do: Select * from tesT1 and you received the result.
After running against mysql the Select failed.
Then we set parameter lowercase_table_names = 1 in my.cnf of mysql and the Select worked again.
Is there a similiar setting for memsql?
best regards
Kai

A: Kai,
No, there's no similar setting in MemSQL.
If number of ways you spell your tables is not very large (e.g. it's either table1 or Table1), then you can create views with different spellings you use, as in:
CREATE VIEW Table1 AS SELECT * FROM table1;

Selecting from such view is as fast as selecting from the table itself.


text:
Q: HOW TO FIx code : 'ERR_REQUIRE_ESM' const { nanoid } = require("nanoid"); how to fix it ,
I'm doing App chat .
Sorry if the language is difficult to read, I'm Thai.
PS C:\Users\ADMIN\Desktop\chat\server> node server.js
C:\Users\ADMIN\Desktop\chat\server\server.js:4
const { nanoid } = require("nanoid");
               ^
[ERR_REQUIRE_ESM]: require() of ES Module
C:\Users\ADMIN\Desktop\chat\server\node_modules\nanoid\index.js from
at Object.<anonymous> (C:\Users\ADMIN\Desktop\chat\server\server.js:4:20) {
code: 'ERR_REQUIRE_ESM'

{
"name": "chat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},

"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"nanoid": "^4.0.0",
"socket.io": "^4.5.1"
}
}

A: This means the library you're trying to require cannot be imported using the require syntax.
I think the version of the nanoid you're using needs to be imported using import
You could try downgrading nanoid or switching to the import keyword.

A: The problem is that you are using nanoid Ver.4.0.0 .
It seems that a new feature in V.4 (support for ESM) is a braking change.
The full documentation is in this link to issue#365 in the nanoid GitHub repo.
The comment that helped me and I base my solution on was from @salyndev0
To fix the problem follow these steps:

*

*Uninstall nanoid: npm uninstall nanoid

*Install Version 3 supporting all 3.x.x:  npm install nanoid@^3.0.0


text:
Q: Get IDs of Images from Gallery Block in InnerBlocks of a Custom Gutenberg Block I am basically creating a Custom Carousel Gutenberg Block. It qould be a carousel at the front end and I plan on using a Gallery Block to add images to the carousel.
The carousel would be loaded using bxSlider which requires a certain syntax as you can see here. The gallery renders a different syntax at the front-end (a list based output of Images). I want to modify the syntax of the rendered gallery.
The render_callback argument seems to modify the output but for that to work, I need IDs of all the images in the Gallery.
The closest I have come to a way out is in this thread using data modules and withDispatch component to retrieve data but I have no Idea how to use it in JSX script. This is the script for my custom block-
const { registerBlockType }   =   wp.blocks;

const { InnerBlocks }    =   wp.blockEditor;

const ALLOWED_BLOCKS_GALLERY = ['core/gallery'];

const GALLERY_TEMPLATE = [
    ['core/gallery', {} ]
];

registerBlockType('my-plugin/my-plugin-carousel', {
    title: 'Carousel',
    description: 'Insert a Carousel using Images from Gallery',
    category: 'common',
    icon: {
        src: 'image-flip-horizontal',
        foreground: '#1d7eb6'
    },

    attributes: {},

    edit: (props) => {

        return([

                <InnerBlocks allowedBlocks={ ALLOWED_BLOCKS_GALLERY } template={ GALLERY_TEMPLATE } templateLock="insert"/>

        ])

    },

    save: () => {

        return <InnerBlocks.Content />
    }
});

Any help on how to proceed with this situation will be highly appreciated! I have spent the last two days on this and have nothing to show for it.

A: In the end, I was successful in extracting the IDs of a Gallery Inner Block. It is kind of a work-around and not an exact solution. This article showed me the way. This is the code I ended up with-
attributes: {
        images: {
            type: 'array',
            default: []
        },
        clientId: {
            'type': 'string',
            'default': ''
        }
    },

edit: withSelect(select => {
        return {
            blocks :   select('core/block-editor').getBlocks()
        }
})(Edit);

Here, the withSelect() method is used to get the data of every block using getBlocks(). I made a separate class for the render part of the code as it was getting quite lengthy. Also, I created two attributes clientId and images which are type string and array respectively.
Here is the code for the class-
class Edit extends Component {

    render() {

        const { attributes, setAttributes } = this.props;

        console.log(this.props.blocks);

        this.props.blocks.map((block, index) => {

            if (block.name === "diviner-blocks/diviner-blocks-carousel" && block.innerBlocks.length > 0 && block.clientId == this.props.clientId) {

                let currentClientID =   block.clientId;
                let currentIDs      =   block.innerBlocks[0].attributes.images;

                attributes.images       =   [...currentIDs]
                attributes.clientId =   currentClientID
            }
        });

        return(

                <InnerBlocks allowedBlocks={ ALLOWED_BLOCKS_GALLERY } template={ GALLERY_TEMPLATE } templateLock="all"/>

        )
    }
}

export default Edit;

Here, the blocks data is present in props in the form of an array. I mapped the blocks array, made appropriate checks if the inner block exists, it is the gallery block and the most important of all, we encounter the current block in the loop. For that we matched the client IDs of the blocks. This is especially useful if there are multiple instances of this block on the same post/page.
When all checks are successful, attributes are updated with the appropriate info. In the images attribute, data of all the images in the gallery Inner Block is stored and the clientId attribute stores the client ID of the block.
It is not a full fledged solution right now and there might be bugs in the future but right now it's the best I came up with going through all the documentation and resources available.


text:
Q: Parallax Issue in Javascript I was creating a parallax effect in which the image and the text move in opposite direction to the movement of the mouse. That is happening inside an element called parallax-wrapper. But when I move out of the element I want the image and the text to return back to their original positions. I have tried to detect the mouse position outside the element but for some reason it not firing properly.
The codepen link is - https://codepen.io/rohitgd/pen/gRLNad?editors=1010
HTML

REVERT

CSS
    body {
        background-color:#fff;
        padding: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    }

    .parallax-wrapper {
        width: 500px;
        height: 300px;
        background-color:#0c0c0c;
        position: relative;
        overflow: hidden;

        .layer {
            width: 80%;
            height: 80%;
            position: absolute;
      left: 30px;
            text-align: center;
            line-height: 300px;
            font-size: 38px;
            color:#FFF;
            transition: all 200ms ease-out;
        }

    }

img {
  width: 200px;
  height: 200px;
  position: relative;
  top: 50px;
  right: 70px;
}

Javascript
$(".parallax-wrapper").mousemove(function(e) {
  var x = e.pageX - $(this).offset().left - $(this).width() / 2;
  var y = e.pageY - $(this).offset().top - $(this).height() / 2;

  $("*[data-mouse-parallax]").each(function() {
    var factor = parseFloat($(this).data("mouse-parallax"));
    x = -x * factor;
    y = -y * factor;

    $(this).css({ transform: "translate3d( " + x + "px, " + y + "px, 0 )" });
  });
});

$(document).mouseleave(function(e) {
    var target = $(e.target);

    if( !target.is("div.layer")) {
      alert('out of the element');
      e.stopPropagation();

    }
});

What I want is when the mouse is outside the parallax-wrapper the Image and the text return back to their original positions.

A: You're not resetting the transformations when your mouse leaves.  You need to add this where you have the alert...
$(".parallax-wrapper").mouseleave(function(e) {
  $("*[data-mouse-parallax]").each(function() {
    $(this).css({ transform: "translate3d( 0, 0, 0 )" });
  });
});

Note that the mouseleave event is triggered when the mouse leaves .parallax-wrapper, not document as you previously had it.
Here's a modified codepen...
https://codepen.io/anon/pen/ZyBgYJ

A: I think a selector was wrong. Here's a correct version or see code below.
To show better when you are inside/outside I change the background color, that's better than an alert. When you leave the wrapper (the black background) it flips correctly now.
Where RED is set you can reset the transform to the origin.

// Trying to replicate the effect here - https://tympanus.net/Development/MorphingBackgroundShapes/

$(".parallax-wrapper").mousemove(function(e) {
  var x = e.pageX - $(this).offset().left - $(this).width() / 2;
  var y = e.pageY - $(this).offset().top - $(this).height() / 2;

  $(".parallax-wrapper").css("background-color", "#00ff00"); // <-- EXIT
  // reset transform here

  $("*[data-mouse-parallax]").each(function() {
    var factor = parseFloat($(this).data("mouse-parallax"));
    x = -x * factor;
    y = -y * factor;

    $(this).css({ transform: "translate3d( " + x + "px, " + y + "px, 0 )" });
  });
});

// this is the selector I changed from "document" to ".parallax-wrapper"
$(".parallax-wrapper").mouseleave(function(e) {
    var target = $(e.target);

    if( !target.is("div.layer")) {
      $(".parallax-wrapper").css("background-color", "#ff0000"); // <-- ENTER
      e.stopPropagation();

    }
});
 body {
  background-color:#fff;
  padding: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
 }

 .parallax-wrapper {
  width: 500px;
  height: 300px;
  background-color:#0c0c0c;
  position: relative;
  overflow: hidden;

  .layer {
   width: 80%;
   height: 80%;
   position: absolute;
      left: 30px;
   text-align: center;
   line-height: 300px;
   font-size: 38px;
   color:#FFF;
   transition: all 200ms ease-out;
  }

 }

img {
  width: 200px;
  height: 200px;
  position: relative;
  top: 50px;
  right: 70px;
}

REVERT

A: Replace $(document).mouseleave with $(".parallax-wrapper").mouseleave.

$(".parallax-wrapper").mousemove(function(e) {
  var x = e.pageX - $(this).offset().left - $(this).width() / 2;
  var y = e.pageY - $(this).offset().top - $(this).height() / 2;

  $("*[data-mouse-parallax]").each(function() {
    var factor = parseFloat($(this).data("mouse-parallax"));
    x = -x * factor;
    y = -y * factor;

    $(this).css({ transform: "translate3d( " + x + "px, " + y + "px, 0 )" });
  });
});

$(".parallax-wrapper").mouseleave(function(e) {
      alert('out of the element');
});
body {
  background-color: #fff;
  padding: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parallax-wrapper {
  width: 500px;
  height: 300px;
  background-color: #0c0c0c;
  position: relative;
  overflow: hidden;
}
.parallax-wrapper .layer {
  width: 80%;
  height: 80%;
  position: absolute;
  left: 30px;
  text-align: center;
  line-height: 300px;
  font-size: 38px;
  color: #FFF;
  transition: all 200ms ease-out;
}

img {
  width: 200px;
  height: 200px;
  position: relative;
  top: 50px;
  right: 70px;
}

REVERT


text:
Q: Jquery: why $("#id_pop")[0] is illegal? In my code when I write code like:
$("#id_pop")[0]

there is an error. When I correct it to:
var $d = $("#id_pop");
$d[0]....

it's ok. Why?

A: [0] should work, i.e. get you a DOM object. But you can't continue using jQuery methods once you get back a normal DOM object.
you can also get a DOM object from a jQuery selector like this:
$('#id_pop').get(0);
Also are you sure you only have one element with the id id_pop. If there is then $('#id_pop')[0] should work.
See working example here: http://jsbin.com/udace3

A: You are using an ID selector, you should not be getting an array but the jquery object itself.  In the jQuery documentation of using the #id,
Each id should only be used only once within a document.  If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on...

A: Isn't it better to use .eq() instead of .get()?
$('#id_pop').eq(0);

Or for that matter:
$('#id_pop:eq(0)');


text:
Q: Vue.js not sending Authorization header I have problem with Authorization header in Vue.js 2 using vue-resource and axios(with both is the same problem). Vue not adding header when send request to backend. Below is my code and example request. Server is running on WSGIServer and its Django(is not nginx yet).
When request send:
Access-Control-Request-Headers: "authorization,xxxxx"
Instead of:
Authorization: "JWT "
Backend works fine - I used CURL to check request and response.
Accounts.vue:
<script>
  import Account from './Account.vue';
  import axios from 'axios';

  export default {
    data() {
      return {
        accounts: []
      }
    },
    created: function () {
      this.getAccounts();
    },
    methods: {
      getAccounts() {
        const token = localStorage.getItem('token');

        axios.defaults.baseURL = 'http://localhost:8000';
        axios.defaults.headers.common['Authorization'] = 'JWT <my_token>';

        axios.get('/api/accounts/')
          .then(
            response => {
              this.accounts = response.data;
            }
          )
          .catch(
            error => console.log(error)
          );

      },
    }
  }
</script>

General
Request URL:http://localhost:8000/api/accounts/
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:localhost:8000
Referrer Policy:no-referrer-when-downgrade

Response Headers
Allow:GET, POST, HEAD, OPTIONS
Content-Length:58
Content-Type:application/json
Date:Wed, 21 Jun 2017 06:59:34 GMT
Server:WSGIServer/0.2 CPython/3.5.2
Vary:Accept, Cookie
WWW-Authenticate:JWT realm="api"
X-Frame-Options:SAMEORIGIN

Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:authorization,xxxxxx
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:8080
Referer:http://localhost:8080/accounts
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36


text:
Q: Breezejs: nest zValidate inside a directive So, have created a few angular directives -- picture "user controls" around common data entry elements, like a label-textbox pair, etc
The problem we are having is that the zValidate directive does not seem to work from within the directive.  Is there something we need to do to make nested directives work?
Edit
Here are the relevant code snippets.
So, first, we have a little directive that adds a label-input pair:
app.directive('afLabelInputPair', function ($compile) {

    var directive = {
        restrict: 'A',
        transclude: true,
        replace: true,
        scope: {                    //@textValue    =twoWayBinding      &oneWayBinding
            labelText: '@labelText',
            afModel: '=',
            afId: '@',
            afPlaceholder: '@'
        },
        templateUrl: './app/templates/af-label-input-pair.html',
        link: function (scope, element, attrs) {
            scope.opts = attrs;
            $compile(element.contents())(scope);
        }
    }

    return directive;
});

Next, we have the template html (this is what's returned from templateUrl:

    {{labelText}}
    <input id="{{afId}}" class="form-control" ng-model="afModel" placeholder="{{afPlaceholder}}" data-z-validate />

But, we don't get a display of breeze validation errors when we use this directive.


text:
Q: Code igniter routing for dynamic id How can I route to specific URL for URL having dynamic id. Suppose orginal URL is
 http:localhost/c2c/init/product/5     // here 5 is the id of the product.

In route.php
 $route["product/iphone-on-sale"] = "init/product/5";

But its not routing to http:localhost/c2c/product/iphone-on-sale when when original URL is entered.

A: You can try this
$route["product/iphone-on-sale/(:num)"] = "init/product/$1";

and your url will be
http://localhost/c2c/product/iphone-on-sale/5


text:
Q: How do I return results from a second query if the first query didnt reach its limit? I have this featured listings thing that will grab its information using
mysql_query("SELECT * FROM listings WHERE featured = '1' DESC LIMIT 5")
However, if I didnt have enough results to display, how do I make it so that it would run mysql_query("SELECT * FROM listings ORDER BY date desc") till it reached the 5 limit?

A: Your first query is missing an order by.  But the idea for solving your problem is to sort the data by both conditions, and then choose the first five:
SELECT *
FROM listings
ORDER BY (featured = '1') DESC,
         date
LIMIT 5;


text:
Q: C# event inheritance I have this program:
    class One
    {
        public delegate void del(object o);
        public event del SomethingChanged;

        int x;
        public int X
        {
            get { return x; }
            set { x = value; OnSomethingChanged(this); }
        }

        protected void OnSomethingChanged(object o)
        {
            if (SomethingChanged != null)
                SomethingChanged(o);
        }
    }

    class Two: One
    {
        public void ChangeSomething()
        {
            //if (SomethingChanged != null)
            //    SomethingChanged(this);
            OnSomethingChanged(this);
        }
    }

    static void Main(string[] args)
    {
        One one = new One();
        Console.WriteLine(one.X);
        one.SomethingChanged += new One.del(one_SomethingChanged);
        one.X = 5;
    }

    static void one_SomethingChanged(object o)
    {
        Console.WriteLine(((One)o).X);
    }

There are 2 classes - One and Two, Two is descendant of One. There is event declared in class One(SomethingChanged) and it is triggered by class One and class Two. But take a look at Two.ChangeSomething - it raises event by invoking base class's method. However if I try to invoke event using raw code like

if (SomethingChanged != null)
    SomethingChanged(this);

I'm getting compiler error saying

The event 'One.SomethingChanged' can only appear on the left hand side of += or -= (except when used from within the type 'eventstest.Program.One')

So I'm just curious why I can't use 'raw' code in class Two to raise event but when I invoke a corresponding function event gets raised?
[EDIT]
Found some clarification here:
C#: Raising an inherited event

A: When you declare an event using the "event" keyword in C#, the generated IL actually contains two corresponding elements: a private delegate field and an event accessor with the same visibility as the declared event.  The event accessor cannot be used to fire the event.  It is only used to subscribe and unsubscribe from notifications.  Your SomethingChanged(this) code is using the private field to invoke the delegate, and that private field is not available from outside the class.

A: Have a look at Use event and delegate in subclass.

A: The code
if (SomethingChanged != null)
    SomethingChanged(this);

(which has a race-condition, by the way) implies calling Delegate.GetInvocationList on SomethingChanged. Automatically implemented events don't allow you to do that unless you are in the class the event is defined in.
You would be able to do it if you implemented the event manually and provided protected access to the delegate field backing the event.

A: Use:
this.SomethingChanged += new One.del(one_SomethingChanged);


text:
Q: error: arma::memory::acquire(): out of memory for Armadillo I encounter the error described in the title when I try to multiply a 10516x66 matrix by a 66x10516 (a matrix by its transposed). The result should be a 10516x10516 matrix which of course I never achieve. Maybe my reasoning is flawed but since my matrix is is a Mat<double> and each double is 8 bytes the result should be 10516*10516*8 = 884690048 bytes = 0.88469 Gbytes. My machine is a Windows with 8 Gb of RAM, I am running a 32-bit minGW compiler. Any idea whiy this is happening and how I can overcome the issue?

A: 32bit programs running under 64bit hosts on Windows could use up to 4Gb of memory. To do so, you have to use special option /LARGEADDRESSAWARE during linking.
Link: https://msdn.microsoft.com/en-us/library/wz223b1z(VS.80).aspx
Most likely, your process is limited to 2Gb and at the moment of allocation there is either not enough memory or not enough continuous memory. Moving to 4Gb might quickly solve the problem
UPDATE
Looks like equivalent mingw32 linker option is --large-address-aware


text:
Q: restricting the value of the field based on another referenced field I have a table whose primary key is referenced in several other tables as a foreign key. For example:
CREATE TABLE `user` (
    `user_id` int NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY  (`user_id`)
  )

  CREATE TABLE `customer` (
    `customer_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`customer_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
  )

  CREATE TABLE `product` (
    `product_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `customer_id` int NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`user_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`),
    CONSTRAINT `customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`customer`);
  )

How can I restrict the value of product.user_id based on the value of the product.customer_id. I want the product.user_id value to be always equal to the value of the customer.user_id where customer.customer_id = product.customer_id

A: It sounds like you don't want to store user_id in the product table.  You should always look it up, using the customer_id field.
If for some strange reason you do need to include it, then you can define a second key on customer and another foreign key relationship:
CREATE TABLE `customer` (
    `customer_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`customer_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
    UNIQUE (customer_id, user_id)  -- redundant, because customer_id is already unique
  );

CREATE TABLE `product` (
   . . .,
   FOREIGN KEY (customer_id, user_id) REFERENCES customer(customer_id, user_id)
  );


text:
Q: Custom Deque Class C++ I'm writing a class for a Deque in cpp, and have almost completed it entirely. I am running into a weird bug where I get trash values after the first insert_tail() function call.
Here is the following code I'm referring to.
Header File:
//File: Deque.h

#ifndef DEQUE_H
#define DEQUE_H

#include <iostream>

const int CAPACITY = 5;
const int DEFAULT = -1;

class Deque
{
public:
    Deque()
    {
        front = 1;
        end = 0;
        size = 0;
    }

    int get_size() const;

    int operator[](int) const;

    void insert_head(int);
    int remove_head();

    void insert_tail(int);
    int remove_tail();

    bool is_empty() const;
    bool is_full() const;

private:
    int size;
    int x_[CAPACITY];
    int front;
    int end;
};
std::ostream & operator<<(std::ostream &, const Deque &);

#endif

Implementation File:
//File: Deque.cpp

#include <iostream>
#include "Deque.h"

std::ostream & operator<<(std::ostream & cout, const Deque & dq)
{
  cout << dq.get_size() << " [ ";
  for (int i = 0; i < dq.get_size(); ++i)
  {
    cout << dq[i] << " ";
  }
  cout << "]";
  return cout;
}

int Deque::operator[](int x) const
{
    return x_[x];
}

int Deque::get_size() const
{
    return size;
}

void Deque::insert_head(int element)
{
    if (size != CAPACITY)
    {
        x_[front] = element;
        front = (front+1) % CAPACITY;
        size++;
    }
}

int Deque::remove_head()
{
    if(is_empty())
    {
        return DEFAULT;
    }
    else
    {
        front = (front-1) % CAPACITY;
        size--;
        return x_[front];
    }
}

void Deque::insert_tail(int element)
{
    if (!is_full())
    {
        x_[end] = element;
        end = (end-1) % CAPACITY;
        size++;
    }
}

int Deque::remove_tail()
{
    if(is_empty())
    {
        return DEFAULT;
    }
    else
    {
        end = (end+1) % CAPACITY;
        size--;
        return x_[end];
    }
}

bool Deque::is_empty() const
{
    return (size == 0);
}

bool Deque::is_full() const
{
    return (size == CAPACITY);
}

Test File:
//File: main.cpp

#include <iostream>
#include "Deque.h"

void print(const Deque & deque)
{
  static int i = 1;
  std::cout << i << ". " << deque  << ", empty: " << deque.is_empty()
            << ", full: " << deque.is_full();
  i++;
}

void test_remove_head(Deque & deque)
{
  int x = deque.remove_head();
  print(deque); std::cout << ", x: " << x << "\n";
}

void test_remove_tail(Deque & deque)
{
  int x = deque.remove_tail();
  print(deque); std::cout << ", x: " << x << "\n";
}

void test_insert_tail(Deque & deque, int x)
{
  deque.insert_tail(x);
  print(deque); std::cout << "\n";
}

void test_insert_head(Deque & deque, int x)
{
  deque.insert_head(x);
  print(deque); std::cout << "\n";
}

void test1()
{
  Deque deque; print(deque); std::cout << "\n";
  test_remove_tail(deque);
  test_remove_head(deque);
  test_insert_tail(deque, 2);
  test_insert_tail(deque, 1);
  test_insert_tail(deque, 0);
  test_insert_head(deque, 5);
  test_insert_head(deque, 1);
  test_insert_tail(deque, 0);
  test_insert_head(deque, 2);
  test_remove_head(deque);
  test_remove_tail(deque);
  test_remove_tail(deque);
  test_remove_tail(deque);
  test_remove_head(deque);
  test_remove_head(deque);
  test_remove_head(deque);
}

void test2()
{
  Deque deque;
  for (int i=0; i<15; i++) test_insert_head(deque, i);
  for (int i=0; i<15; i++) test_remove_tail(deque);
}

int main()
{
  test1(); test2();
  return 0;
}

Output:
1. 0 [ ], empty: 1, full: 0
2. 0 [ ], empty: 1, full: 0, x: -1
3. 0 [ ], empty: 1, full: 0, x: -1
4. 1 [ 2 ], empty: 0, full: 0
5. 2 [ 2 0 ], empty: 0, full: 0
6. 3 [ 2 0 0 ], empty: 0, full: 0
7. 4 [ 2 5 0 4198128 ], empty: 0, full: 0
8. 5 [ 2 5 1 4198128 0 ], empty: 0, full: 1
9. 5 [ 2 5 1 4198128 0 ], empty: 0, full: 1
10. 5 [ 2 5 1 4198128 0 ], empty: 0, full: 1
11. 4 [ 2 5 1 4198128 ], empty: 0, full: 0, x: 1
12. 3 [ 2 5 1 ], empty: 0, full: 0, x: 0
13. 2 [ 2 5 ], empty: 0, full: 0, x: 2
14. 1 [ 2 ], empty: 0, full: 0, x: 2
15. 0 [ ], empty: 1, full: 0, x: 5
16. 0 [ ], empty: 1, full: 0, x: -1
17. 0 [ ], empty: 1, full: 0, x: -1
18. 1 [ 32764 ], empty: 0, full: 0
19. 2 [ 32764 0 ], empty: 0, full: 0
20. 3 [ 32764 0 1 ], empty: 0, full: 0
21. 4 [ 32764 0 1 2 ], empty: 0, full: 0
22. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
23. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
24. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
25. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
26. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
27. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
28. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
29. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
30. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
31. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
32. 5 [ 4 0 1 2 3 ], empty: 0, full: 1
33. 4 [ 4 0 1 2 ], empty: 0, full: 0, x: 0
34. 3 [ 4 0 1 ], empty: 0, full: 0, x: 1
35. 2 [ 4 0 ], empty: 0, full: 0, x: 2
36. 1 [ 4 ], empty: 0, full: 0, x: 3
37. 0 [ ], empty: 1, full: 0, x: 4
38. 0 [ ], empty: 1, full: 0, x: -1
39. 0 [ ], empty: 1, full: 0, x: -1
40. 0 [ ], empty: 1, full: 0, x: -1
41. 0 [ ], empty: 1, full: 0, x: -1
42. 0 [ ], empty: 1, full: 0, x: -1
43. 0 [ ], empty: 1, full: 0, x: -1
44. 0 [ ], empty: 1, full: 0, x: -1
45. 0 [ ], empty: 1, full: 0, x: -1
46. 0 [ ], empty: 1, full: 0, x: -1
47. 0 [ ], empty: 1, full: 0, x: -1

As you can see, after line 4. The proper insert statements are not completed, and also the x: from function "remove_head()" and "remove_tail()" are not receiving the correct return values.


text:
Q: Use cached data by FaradayMiddleware::Caching I use Faraday for request api. I want to cache response body and use it instead of request for specifed expired time.
I found FaradayMiddleware::Caching and I can cache response body, but I do not know how use cache instead of request.
API service which I use do not support http cache, so I can not use faraday-http-cache gem.
Below my code
connection = Faraday.new(url: 'http://exapmle.com') do |faraday|
  faraday.request :url_encoded
  cache_dir = File.join('/tmp/cache')
  faraday.response :caching do
    ActiveSupport::Cache::FileStore.new cache_dir, :expires_in => 3600
  end
  faraday.adapter Faraday.default_adapter
end

connection.get '/path/to/api', version: nil

How can I use cached data instead of normal response?
Cache key is request url, but url is dynamically change. So I think I need a way to get url which constructed by Faraday.


text:
Q: First order logic formula R(x) is a red block
B(x) is a blue block
T(x,y) block x is on top of block y
Question:
Write a formula asserting that if no red block is on top of a red block then no red block is on top of itself.
My answer:
(Ax)(Ay)(R(x) and R(y) -> ~T(x,y))->(Ax)(R(x)-> ~T(x,x))
A = For all
~ = Not
-> = implies

A: That is a plausible formulation, though not necessarily the most straight-forward translation of the sentence, which, to my mind, is (Ax)(Ay)(T(x,y) -> R(x) -> ~R(y)) -> ~(3x)(R(x) and T(x,x)). 3, here, being the existential quantifier (i.e. "there exists an").

A: Looks good to me.

A: (Ax)(Ay)(Az) { (((R(x) and R(y)) -> ~T(x,y)) -> ~T(z,z) }


text:
Q: Jquery ajax data I am using the qTip plugin to post a imdb URL to an IMDB grabber script and display movie info on that url.
Everything works until I have more than one qtip on the page.
What i need to do Is only post the data of the image that is being hovered. This is the code should make a bit more sense then me.
Script -
var link = $("#link").val();
var imdbLink =  { "link" : link };  // note change to data...

$('.moviebox').each(function() {
    $(this).qtip({
       style: { name: 'light' },
       content: {
         method: 'GET',
         data: imdbLink,   // you could make this { "link" : link }
         url: '/bin/imdb/imdb.example.php',
         text: ''
       },
       position: {
             corner: {
               target: 'bottomright',
              tooltip: 'bottomleft'
            }
          }
    });
    });

html--

  <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107969"/>
 </form>

   <form method="get" action="">
    <input type="text" name="link" id="link" style="display:none" value="http://us.imdb.com/Title?0107050"/>
 </form>

You will see that both inputs have the same ID which is causing an issue. how would I get around this keeping the IDs the same????

A: Simple solution is to use class instead of id.  Besides that, ID are meant to be unique, shouldn't use them in more than once on the same page anyways.

A: $('.moviebox').each(function() {
   var imdbLink =  { "link" : $(this).find("input.link").val() };
   $(this).qtip({
      // qTip code
   });
});


text:
Q: BitmapUtils throwing FileNotFoundException on foldername having space while getting bitmap from uri Getting FileNotFoundException on folders having space on Android 5.1. Otherwise its working fine.
I tried replacing space with %20 but din't work. Also tried URLEncoder but it's failing.
I'm getting path of image using contentresolver:
absolutePathOfImage=cursor.getString(column_index_data);

which is (/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20181025-WA0001.jpg)
Uri:
file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20181024-WA0022.jpg

I want to get bitmap of image but while getting bitmap from Uri,  BitmapUtils throwing exception: (Note: even Glide,picasso is failing to create thumbnail of image)
        BitmapUtils.decodeSampledBitmap(mContext, mUri, mWidth, mHeight);

java.lang.RuntimeException: Failed to load sampled bitmap: file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20181024-WA0022.jpg
  /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20181024-WA0022.jpg: open failed: ENOENT (No such file or directory)

I'm getting exception on Android 5.1.
Same code working on Android 8.0
Stuck with it since 2 days. Any workaround or solution?

A: the space should not be encoded, alike an URL:
file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20181024-WA0022.jpg

but it should be escaped with \, alike a Linux path:
file:///storage/emulated/0/WhatsApp/Media/WhatsApp\ Images/IMG-20181024-WA0022.jpg

also make sure that the base-path file:///storage/emulated/0 is correct.