text:
Q: Struggling to format variables correctly for constructor I want to pass two values through a constructor, but am struggling to find a way to define my variables so that the constructor will take the values. The constructor itself must stay the same.
The constructor I'm trying to pass into is:
playing_card(card_face const& f, std::optional<card_suit> const& s = std::nullopt) : face_val(f), suit_val(s)
{
  if (!s.has_value() && f != card_face::white_joker && f != card_face::red_joker)
    throw std::domain_error("playing card without suit must be a joker");
};

And the part that is giving me errors that I am trying to pass:
std::optional<playing_card> read_playing_card(std::istream& is)
{
  std::optional<playing_card> retval;

  auto face = read_card_face(is);
  //auto suit;

  if (face.has_value() && face != card_face::white_joker && face != card_face::red_joker)
  {
    auto suit = read_card_suit(is);

    if (suit.has_value())
    {
      retval = playing_card(face, suit);
    }

    retval = playing_card(face);
  }

  if (!retval.has_value())
    is.setstate(std::ios_base::failbit);
}

The error is:
a4-provided.cpp:271:39: error: no matching function for call to 'playing_card::playing_card(std::optional<card_face>&, std::optional<card_suit>&)'

  271 |       retval = playing_card(face, suit);

I understand what the compiler is saying, but I'm not sure how to navigate this error in my code.
The entire clode block is here:
//=============================================================================
#include <array>
#include <istream>
#include <optional>
#include <string>
#include <sstream>

#include "a4-provided.hpp"

//=============================================================================
//
// std::optional<card_suit> read_card_suit(std::istream)
//
// read_card_suit reads a card suit from an input stream returning a
// an optional value. The return value only holds a card_suit if a valid
// card_suit was read in. If an error occurs on the stream while reading in
// the data, then stream is failed. If the character on the stream read in
// is not a valid suit, then the character read in is returned to the stream
// using is.unget().
//
std::optional<card_suit> read_card_suit(std::istream& is)
{
  std::optional<card_suit> retval;
  auto ch = is.get();

  if (!std::istream::traits_type::eq_int_type(ch,std::istream::traits_type::eof()))
  {
    switch (ch)
    {
      case 'c':
        retval = card_suit::clubs;
        break;

      case 'd':
        retval = card_suit::diamonds;
        break;

      case 'h':
        retval = card_suit::hearts;
        break;

      case 's':
        retval = card_suit::spades;
        break;

      default:
        is.unget();                               // return ch to stream
        is.setstate(std::ios_base::failbit);      // fail the stream
    }
  }
  else
    is.setstate(std::ios_base::failbit);          // fail the stream

  return retval;
}

//=============================================================================
//
// Provide a simple way to generate all playing cards without requiring
// card_face, card_suit, playing_card, and all supporting operations to be
// written first.
//
std::string all_playing_cards_as_string()
{
  std::array<char,4> const special_face{ 'A', 'J', 'Q', 'K' };
  std::array<char,4> const suit{ 'c', 'd', 'h', 's' };
  std::ostringstream buf;

  // generate all numeric face cards...
  for (int face=2; face != 11; ++face)
    for (auto const s : suit)
      buf << face << s;

  // generate all special face cards...
  for (auto const f : special_face)
    for (auto const s : suit)
      buf << f << s;

  // generate two jokers (red and white)...
  buf << "RW";

  // return string...
  return buf.str();
}

//=============================================================================
std::optional<card_face> read_card_face(std::istream& is)
{
  std::optional<card_face> retval;

  //retrieve char from input stream
  auto ch = is.get();

  //peek at the next char
  auto ch2 = is.peek();

  //is ch EOF ? if no, continue
  if (!std::istream::traits_type::eq_int_type(ch,std::istream::traits_type::eof()))
  {
    switch (ch)
    {
      case 'A':
        retval = card_face::ace;
        break;

      case '2':
        retval = card_face::two;
        break;

      case '3':
        retval = card_face::three;
        break;

      case '4':
        retval = card_face::four;
        break;

      case '5':
        retval = card_face::five;
        break;

      case '6':
        retval = card_face::six;
        break;

      case '7':
        retval = card_face::seven;
        break;

      case '8':
        retval = card_face::eight;
        break;

      case '9':
        retval = card_face::nine;
        break;

      case 'J':
        retval = card_face::jack;
        break;

      case 'Q':
        retval = card_face::queen;
        break;

      case 'K':
        retval = card_face::king;
        break;

      case 'R':
        retval = card_face::red_joker;
        break;

      case 'W':
        retval = card_face::white_joker;
        break;

      case '1':
        //check if ch2 = 0
        if (ch2 == '0')
        {
          is.ignore();
          retval = card_face::ten;
        }
        else
          is.unget();
        is.setstate(std::ios_base::failbit);
        break;

      default:
        is.unget();
        is.setstate(std::ios_base::failbit);
        break;
    }
  }
  else
    is.setstate(std::ios_base::failbit);

  if (retval.has_value())
    return retval;
}

inline std::istream& operator>>(std::istream& is, card_face& s)
{
  auto face = read_card_face(is);
  if (face)
    s = *face;
   return is;
}

inline std::ostream& operator<<(std::ostream& os, card_face const& s)
{
  switch (s)
  {
    case card_face::ace:           os.put('A'); break;
    case card_face::two:           os.put('2'); break;
    case card_face::three:         os.put('3'); break;
    case card_face::four:          os.put('4'); break;
    case card_face::five:          os.put('5'); break;
    case card_face::six:           os.put('6'); break;
    case card_face::seven:         os.put('7'); break;
    case card_face::eight:         os.put('8'); break;
    case card_face::nine:          os.put('9'); break;
    case card_face::ten:           os.put('1'); os.put('0'); break;
    case card_face::jack:          os.put('J'); break;
    case card_face::queen:         os.put('Q'); break;
    case card_face::king:          os.put('K'); break;
    case card_face::white_joker:   os.put('W'); break;
    case card_face::red_joker:     os.put('R'); break;
    default:
      os.setstate(std::ios_base::failbit);
      break;
  }
  return os;
}

class playing_card
{
  private:
    card_face face_val;
    std::optional<card_suit> suit_val;

  public:
    playing_card() = delete;

    playing_card(card_face const& f, std::optional<card_suit> const& s = std::nullopt) : face_val(f), suit_val(s)
    {
      if (!s.has_value() && f != card_face::white_joker && f != card_face::red_joker)
        throw std::domain_error("playing card without suit must be a joker");
    };

    const std::optional<card_face> face() { return face_val; }

    const bool has_suit() { return suit_val.has_value(); }

    const std::optional<card_suit> suit()
    {
      if (has_suit() == true)
        return suit_val;
    }

    friend bool operator==(playing_card const&, playing_card const&);
    friend std::strong_ordering operator <=> (playing_card const&, playing_card const&);
};

std::optional<playing_card> read_playing_card(std::istream& is)
{
  std::optional<playing_card> retval;

  auto face = read_card_face(is);
  //auto suit;

  if (face.has_value() && face != card_face::white_joker && face != card_face::red_joker)
  {
    auto suit = read_card_suit(is);

    if(suit.has_value())
    {
      retval = playing_card(face, suit);
    }

    retval = playing_card(face);
  }

  if (!retval.has_value())
    is.setstate(std::ios_base::failbit);
}

I have tried using manual definitions for face and suit, and I have tried adding const to the variables, and have tried messing with pointers and references, but I can't seem to understand how to format it the way the compiler wants.

A: The compiler is complaining about you passing 2 std::optional objects to the playing_card constructor when it accepts only 1 std::optional, in the 2nd parameter.
Change this line:
retval = playing_card(face, suit);

To this instead:
retval = playing_card(face.value(), suit);

However, that statement is useless since you are calling retval = playing_card(face) immediately afterwards, thus discarding the object that the previous statement had just created.  I suspect you are missing an else on your if, eg:
if (suit.has_value())
{
  retval = playing_card(face.value(), suit);
}
else // <-- here!
  retval = playing_card(face.value());

In which case, you don't need the if at all, just call retval = playing_card(face.value(), suit); unconditionally.

That being said:
read_playing_card(), read_card_face(), and playing_card::suit() all exhibit undefined behavior, as they are declared as returning a std::optional object, but not all of their code paths actually return such an object. The compiler should be warning you about that mistake.
Also, this kind of code:
auto ch = is.get();

if (!std::istream::traits_type::eq_int_type(ch,std::istream::traits_type::eof()))

Can be greatly simplified to this (same with is.peek()):
auto ch = is.get();

if (ch != std::istream::traits_type::eof())

Or even this:
char ch;

if (is.get(ch))

Also, there is no point in playing_card::face() returning a std::optional since the value being returned can never be empty.  And because of that, it doesn't make sense for read_card_face() to return a std::optional either.  Every card needs a face, if not a suit.  The caller of read_card_face() should be checking for a reading failure by looking at the std::istream's failure state, not whether the function returned an optional (but not really!) face.
Also, playing_card() = delete; is unnecessary since playing_card has a user-defined constructor, so the compiler won't generate its own default constructor to begin with.


text:
Q: document.cookie not working with chrome only I have already read other posts but I'm not working on localhost.
The code below works on safari ie and firefox but chrome fails.
It looks like it is completely ignored. Any suggestion is welcome.
Here is the code.
  document.cookie = "lang="+$('#account_lang').val()+"; path=/; samesite=none;";

A: Seems the newer version of each browser does not support this technique.
you should split this string into parts.

   var x = "lang='1'; path='/'; samesite='none';";

 $.each(x.split(";"), function(i,obj)
    {  if(obj !== "")
        document.cookie = obj;
    });

if you are using jquery then below is the code

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use multidimensional checkbox v-model in vuejs Suppose i have some subjects which has conditions and groups.
How can i load those first time and checked in update mood in vuejs?

  {{ sub }}

                                        <input type="checkbox"
                                        :value="subconlist.id"
                                         :key="subconlist.id"
                                       >
                                        {{subconlist.name}}

                                        <input type="checkbox">
                                        {{clsgrlist.academic_group_name}}

     <button @click="saveOrUpdate()" >Save   </button>

fiddle here
the table where i will save it : sub_id,condition_ids,group_ids
I have to save data based on checked value in the table with comma separated.
How can i get checkbox checked if it already found in the table, i mean when update?
I need to get subjectconditon or group ids basis on each subject when click on save button.


text:
Q: Frequency dependence of electrolytic capacitors It's said that electrolytic capacitors behave as inductors at high frequencies, which is why we put small ceramic caps in parallel with them:

Electrolytic, paper, or plastic film
  capacitors are a poor choice for
  decoupling at high frequencies; they
  basically consist of two sheets of
  metal foil separated by sheets of
  plastic or paper dielectric and formed
  into a roll. This kind of structure
  has considerable self inductance and
  acts more like an inductor than a
  capacitor at frequencies exceeding
  just a few MHz.

Capacitor impedance vs. frequency.
Yet I also see a few things like this:

The "inductance problem" associated with electros is another idiotic myth
  - they have no more inductance than a length of wire the same as the length
  of the cap.

or

A popular myth is that electros have considerable inductance because
  of the way the foil is wound inside the can. This is nonsense - the
  foils are usually joined at the ends in the much the same way as with
  film caps. High frequency performance usually extends to several MHz,
  even with standard off-the-shelf electros and bipolar
  (non-polarised electrolytic) caps.

What is the exact nature of this effect and in what applications and frequencies do we need to worry about it?  What are the practical implications?

A: This effect is due to the effects of parasitic characteristics of the device.  A capacitor has four basic parasitics:
Equivalent Series Resistance - ESR:
A capacitor is really a capacitor in series with the resistances of its leads, the foil in the dielectric, and other small resistances. This means that the capacitor cannot truly discharge instantly, and also that it will heat up when repeatedly charged and discharged.  This is an important parameter when designing power systems.
Leakage current:
The dielectric is not ideal, so you can add a resistance in parallel with your capacitor.  This is important in backup systems, and the leakage current of an electrolytic can be much greater than the current required to maintain RAM on a microcontroller.
Dielectric Absorption - CDA:
This is usually of less interest than the other parameters, especially for electrolytics, for which leakage current overwhelms the effect.  For large ceramics, you can imagine that there is an RC circuit in parallel with the capacitor.  When the capacitor is charged for a long period of time, the imagined capacitor acquires a charge. If the capacitor is rapidly discharged for a brief period and subsequently returned to an open circuit, the parasitic capacitor begins to recharge the main capacitor.
Equivalent Series Inductance - ESL:
By now, you shouldn't be too surprised that, if everything has capacitance as well as nonzero and non-infinite resistance, everything also has parasitic inductance.  Whether these are significant is a function of frequency, which leads us to the topic of impedance.
We represent impedance by the letter Z.  Impedance can be thought of like resistance, just in the frequency domain.  In the same way that a resistance resists the flow of DC current, so does an impedance impede the flow of AC current.  Just as resistance is V/R, if we integrate into the time domain, impedance is V(t)/ I(t).
You'll either have to do some calculus, or buy the following assertions about the impedance of a component with an applied sinusoidal voltage with a frequency of w:
\$
\begin{align}
Z_{resistor} &= R\\
Z_{capacitor} &= \frac{1}{j \omega C} = \frac{1}{sC}\\
Z_{inductor} &= j\omega L = sL
\end{align}
\$
Yes, \$j\$ is the same as \$i\$ (the imaginary number, \$\sqrt{-1}\$), but in electronics, \$i\$ usually represents current, so we use \$j\$.  Also, \$\omega\$ is traditionally the Greek letter omega (which looks like w.)  The letter 's' refers to a complex frequency (not sinusoidal).
Yuck, right?  But you get the idea - A resistor doesn't change its impedance when you apply an AC signal.  A capacitor has reduced impedance with higher frequency, and it's nearly infinite at DC, which we expect.  An inductor has increased impedance with higher frequency - think of an RF choke that's designed to remove spikes.
We can calculate the impedance of two components in series by adding the impedances.  If we have a capacitor in series with an inductor, we have:
\$
\begin{align}
Z &= Z_C + Z_L\\
 &= \frac{1}{j\omega C + j\omega L}
\end{align}
\$
What happens when we increase the frequency?  A long time ago, our component was an electrolytic capacitor, so we'll assume that \$C\$ is very much greater than \$L\$. At first glance, we'd imagine that the ratios wouldn't change.  But, some trivial (Note: This is a relative term) complex algebra shows a different outcome:
\$
\begin{align*}
Z &= \frac{1}{j \omega C} + j \omega L\\
 &= \frac{1}{j \omega C} + \frac{j \omega L \times j \omega C}{j \omega C}\\
 &= \frac{1 + j \omega L \times j \omega C)}{j \omega C}\\
 &= \frac{1 - \omega^2 LC}{j \omega C}\\
 &= \frac{-j \times (1 - \omega^2 LC)}{j \omega C}\\
 &= \frac{(\omega^2 LC - 1) * j)}{\omega C}
\end{align*}
\$
Well, that was fun, right?  This is the kind of thing you do once, remember the answer, and then don't worry about it.  What do we know from the last equation?  Consider first the case where \$\omega\$ is small, \$L\$ is small, and \$C\$ is large.  We have, approximately,
\$
\begin{align*}
\frac{(small * small * large - 1) \times j}{small * large}
\end{align*}
\$
which is a negative number (assuming \$small * small * large < 1\$, which it is for practical components). This is familiar as \$Z_C = \frac{-j}{\omega C}\$ - It's a capacitor!
How about, second, your case (High-frequency electrolytic) where \$\omega\$ is large, \$L\$ is small, and \$C\$ is large.  We have, approximately,
\$
\begin{align*}
\frac{(large * small * large - 1) \times j}{small * large}
\end{align*}
\$
which is a positive number (assuming \$large * small * large > 1\$). This is familiar as \$Z_L = j \omega L\$ - It's an inductor!
What happens if \$\omega^2 LC = 1\$?  Then the impedance is zero!?!? Yes!  This is called the resonant frequency - It's the point at the bottom of the curve you showed in your question.  Why isn't it actually zero?  Because of ESR.

TL,DR: Weird stuff happens when you increase the frequency a lot.  Always follow the manufacturers' datasheets for decoupling your ICs, and get a good textbook or take a class if you need to do high speed stuff.

A: Anyone with access to an impedance meter (HP / Venable) can easily tell you that electrolytic capacitors certainly do become inductive at high frequencies.
This is part of the reason why you see a lot of ceramic capacitors used in high-frequency DC-DC converters - electrolytics simply aren't that good up in the hundreds of kilohertz / megahertz.
This is also why ceramic capacitors from 100nF - 1uF are commonly used as IC decouplers - an electrolytic cannot beat a small ceramic can because of its high-frequency impedance.

A: Question was not "if lytics are inductive", but why ? This is quite a puzzle, but comparison to ceramic caps plots for solid state chemistry can give a clue, that something is special for lytic caps only. So the question belongs to chemistry, not to electronics.
Increase of impedance after reaching minimum at high frequencies is caused by energy accumulated in form of rotating (or stretched/displaced) charged mass of large ions or polarized molecules. Each molecule in solution is acting like group of resonators (not just inductance) with sharp phase plot near several resonating frequencies.
There is interesting study about impedance measurement for pure water and metal ions in range of few MHz.
http://commons.emich.edu/cgi/viewcontent.cgi?article=1200&context=theses&sei-redir=1#search=%22ion%20solution%20impedance%20MHz%22

A: The key is that these have the form of a roll, which is similar to a coil, i.e. the current flows in circles.
This causes a relatively high inductance.
Other capacitors have the form of sheets (ceramic) or of two surfaces on a porous material (tantal, supercaps), so they don't show this effect.

A: cool question - generally speaking a capacitor with capacitance C has an complex impedence with magnitude 1/(2*pi*f*C), fwiw. So at high frequencies a capacitor is supposed look like a short circuit (i.e. 0 ohms). I'm unfamiliar with the argument that they start to act like an inductor (which implies that at some point the impedence increases starts to increase with frequency, since an inductor of size L has a complex impedence with magnitude 2*pi*f*L... I guess I don't really buy it, but I have no basis for that.

A: In aluminum electrolytics the foils are not joined the way film caps are.  This has to make induction high.  However, there are always specials, so who knows?


text:
Q: Three channel vs. grayscale image input to a CNN I am trying to mimic and build an image classification model described in a paper. At first I was using 100x100x3 images as input to the neural network. The model was giving very good accuracy (~95%) in training phase, but producing very poor predictions, resulting in a confusion matrix that had same values in all cells. But when I trained the model with single band grayscale images as input, as done in the paper itself, the accuracy reduced to ~84% but the model made good predictions with good confusion matrix. I am building the CNN model with keras and using ImageDataGenerator for flowing images.
This is how I create image augmentation.(same as described in the paper):
# Flip image along y=x line: returns flipped image as an integer array
def flip_xy(img):
    img_flip = tfimg.rot90(np.flipud(PIL.Image.fromarray(img).resize((100,100))))
    return np.array(img_flip)

# Rotate img thrice by 90 degrees: returns 3 rotated images as integer arrays
def rotate90(img):
    img90 = tfimg.rot90(np.array(img.resize((100,100))))
    img180 = tfimg.rot90(np.array(img90))
    img270 = tfimg.rot90(np.array(img180))
    return np.array(img90), np.array(img180), np.array(img270)

# Crop image once from each corner and once from centre: return image object
def getCrops(img):
    upper_left = img.crop((10,10,110,110))
    upper_right = img.crop((0,10,100,110))
    lower_left = img.crop((10,0,110,100))
    lower_right = img.crop((0,0,100,100))
    centre = img.crop((5,5,105,105))
    return upper_left, upper_right, lower_left, lower_right, centre

# Create 40 copies from single image: data augmentation
def createCopies(img_path, target_folder):
    img = image.load_img(img_path, target_size = (110,110))
    img_file = img_path.split("\\")[-1].split(".")[0]
    k = 1
    ul, ur, ll, lr, ctr = getCrops(img)
    for image0 in [ul, ur, ll, lr, ctr]:
        i90, i180, i270 = rotate90(image0)
        for image1 in [i90, i180, i270, np.array(image0)]:
            flip = flip_xy(image1)
            PIL.Image.fromarray(image1).save(os.path.join(target_folder, f"{img_file}({k}).jpg"))
            PIL.Image.fromarray(flip).save(os.path.join(target_folder, f"{img_file}({k+1}).jpg"))
            k += 2

I then iterate over all the original images, creating augmentations.
Here is the code for model training:
Model training. Ignore the fact that the training phase is not completed in the notebook. It is from a later run. In the original run, the training ran for all 30 epochs.
Here is the code for model evaluation:
Model evaluation. Here I have a second doubt. Why does predicting each image individually and predicting the generator object produce different results?
Can anyone explain why this happens? Shouldn't three channel images be able to train the model better? And why is there a discrepancy between model accuracy while training and actual predictions?


text:
Q: How do I mock Directory.GetFiles? I am trying to figure out how or if it is possible to do the following with Moq
public class Download
{
    private IFoo ifoo;

    public Download(IFoo ifoo)
    {
        this.ifoo = ifoo;
    }

    public void Download()
    {
        var files = Directory.GetFiles("filepath"); //<<<===

        foreach (var item in files)
        {

            // do something

        }
    }
}

In unit test.
// Arrange

var mockFoo = new Mock<IFoo>();
mockFoo.setup( s => s.Bar()).returns(true);

var foo = new Foo(mockFoo.Object);

// Act
foo.Download()

How can I mock the files variable, so the method uses the mock version. Is this even the correct approach? As I am not mocking the class, and rather mocking the dependency how do I go about settings the files variable so it looks at mocked file string[].

A: You would need to depend on an abstraction to get your files instead of having a hard dependency on System.IO.Directory:
public interface IFileProvider
{
    string[] GetFiles(string path);
}

public class PhysicalFileProvider : IFileProvider
{
    public string[] GetFiles(string path)
    {
        return Directory.GetFiles(path);
    }
}

You would inject the abstraction in exactly the same way as you're injecting IFoo.
Now you can mock IFileProvider using Moq, creating a mock that returns exactly the strings that you want it to return.
var fileProvider = new Mock<IFileProvider>();
fileProvider.Setup(x => x.GetFiles(It.IsAny<string>()))
    .Returns(new[] {"file1.txt", "file2.txt"});

You can also use Microsoft.Extensions.FileProviders.Physical which provides both the file system access and the abstraction.
public class Download
{
    private readonly IFoo _foo;
    private readonly Microsoft.Extensions.FileProviders.IFileProvider _fileProvider;

    public Download(IFoo foo, IFileProvider fileProvider)
    {
        _foo = foo;
        _fileProvider = fileProvider;
    }

    public void SomethingWithFiles()
    {
        var files = _fileProvider.GetDirectoryContents("filepath")
            .Where(item => !item.IsDirectory);

        foreach (var item in files)
        {
            // something
        }
    }
}

The concrete implementation would be PhysicalFileProvider.

One more variation. Instead of injecting an interface, inject a delegate:
public delegate string[] GetFilesFunction(string path);

public class Download
{
    private readonly IFoo _foo;
    private readonly GetFilesFunction _getFiles;

    public Download(IFoo foo, GetFilesFunction getFiles)
    {
        _foo = foo;
        _getFiles = getFiles;
    }

...

That's even easier to mock. You don't even need Moq.
var subject = new Download(mockedFoo, path => new []{"file1.txt","file2.txt"} );


text:
Q: Check if user's input is of a determinated type (C++) I'm writing a program that gets a number from the user and print it, I want to check if the user's input is a number or not.
#include <iostream>

int main(){

    int x;

    std::cout << "Enter a number: ";
    std:;cin >> x;

    /*
    Here's what I want to do
    if (isInteger(x)){

        std::cout << "\nYour number is " << x << ;

    } else if (isNotInteger()){
        std::cout << "\nInvalid value\n\n";
    }
    */

    return(0);
}

A: The stream's error state is set to failbit if operator>> fails to read a value. You can test for that condition, eg:
if (std::cin >> x) {
    std::cout << "\nYour number is " << x << ;
} else {
    std::cout << "\nInvalid value\n\n";
}

If you want to continue reading about a failure, you have to first call the stream's clear() method to reset the error state, and also read/remove the invalid data from the buffer, such as with the stream's ignore() method, eg:
if (std::cin >> x) {
    std::cout << "\nYour number is " << x << ;
} else {
    std::cout << "\nInvalid value\n\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_liimits<std::streamsize>::max(), '\n');
}


text:
Q: PHP: how to open a zip is there an easy way to open and create a zip with PHP?

A: Have a look at the PHP Zip library.
Here are a few tutorials on the subject:

*

*Devzone.zend.com

*net.tutsplus.com

A: Something like the zip library ?

A: Take a look at the documentation for ZipArchive, particularly the open method.
You use it like this:
<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>


text:
Q: Server-side python script with long execution time in the context of a website I have website project that requires this :
The user can prompt the website to launch a python script (basically a trained AI that will operate on some data given by the user).
Unfortunately, the execution time of such a script is a bit long, (approximately 1min30) because it involves scrapping web pages, analyzing them, it's a slow process.
I am not well informed in this specific field and here are my questions :

*

*What happens if a lot of different users prompt at the same time ? What sort of solution would you use in order to avoid this ? Do I need to program a task manager or something like this ?

*Is this dangerous ?

*Is translating the AI into js and running the script client-side possible ?
Thanks in advance for your input.
This is my first post, I'm sorry if this doesn't belong here.


text:
Q: Eigen 3x3 matrix inverse wrong result problem description
I'm using Eigen for some matrix task. Say I have matrix A whose size is 4x3, then its transpose A^T is 3x4 size, then A^T * A is 3x3 size, thus the inverse, (A^T * A)^(-1), is also 3x3 size.
I would like to get (A^T * A)^(-1). By using the mentioned formula, and by manually defining A^T * A matrix then do inverse, I got different result for (A^T * A)^(-1) matrix. Curious why this two results mismatch and differs very much.
Reproduce
Eigen version: git commit 972cf0c28a8d2ee0808c1277dea2c5c206591ce6
System: Ubuntu 20.04
Compiler: Clang++, 10.0.0
Code:
#include <iostream>
#include <Eigen/Dense>

int main() {
    {
        printf("----- A^T * A by calculate\n");
        Eigen::MatrixXd A(4, 3);
        A << 1.70023e+06, 1303.93, 1,
             1.99113e+06, 1411.07, 1,
             1.97211e+06, 1404.32, 1,
             1.69433e+06, 1301.67, 1;

        std::cout << "A:" << std::endl << A << std::endl;

        Eigen::MatrixXd AT = A.transpose();
        std::cout << "A^T:" << std::endl << AT << std::endl;

        Eigen::MatrixXd ATA = AT * A;
        std::cout << "A^T * A:" << std::endl << ATA << std::endl;
        std::cout << "(A^T * A)^(-1):" << std::endl << ATA.inverse() << std::endl;
    }

    {
        printf("----- A^T * A by define\n");
        Eigen::MatrixXd ATA(3, 3);
        ATA << 1.36154e+13, 1.00015e+10, 7.3578e+06,
               1.00015e+10, 7.3578e+06,     5420.99,
               7.3578e+06,    5420.99,           4;
        std::cout << "A^T * A:" << std::endl << ATA << std::endl;
        std::cout << "(A^T * A)^(-1):" << std::endl << ATA.inverse() << std::endl;
    }

    return 0;
}

The actual outputs:
----- A^T * A by calculate
A:
1.70023e+06     1303.93           1
1.99113e+06     1411.07           1
1.97211e+06     1404.32           1
1.69433e+06     1301.67           1
A^T:
1.70023e+06 1.99113e+06 1.97211e+06 1.69433e+06
    1303.93     1411.07     1404.32     1301.67
          1           1           1           1
A^T * A:
1.36154e+13 1.00015e+10  7.3578e+06
1.00015e+10 7.35781e+06     5420.99
 7.3578e+06     5420.99           4
(A^T * A)^(-1):
3.49282e-06 -0.00946871     6.40758
-0.00946871     25.6689    -17370.5
    6.40758    -17370.5 1.17549e+07
----- A^T * A by define
A^T * A:
1.36154e+13 1.00015e+10  7.3578e+06
1.00015e+10  7.3578e+06     5420.99
 7.3578e+06     5420.99           4
(A^T * A)^(-1):
  6.1435e-09 -1.66513e-05    0.0112659
-1.66513e-05    0.0452221      -30.658
   0.0112659      -30.658      20826.4

A: This is just a matter of numerical accuracy. As pointed out by @Damien in the comment, the matrix is ill-conditioned, and thus a small difference in the input can lead to a large change in the results. By copying from the output only the first five digits and using them to manually define the second matrix, a significant part is discarded that is handled internally but not displayed with the standard accuracy of std::cout.
Take for instance the entry ATA(0,0). By using is ATA << 1.36154e+13,..., any value of the order of 1.e7 or lower is not considered. This is, however, the order of the other entries in the matrix.
In short, both results are correct, but your manually defined matrix ATA is not the same as the one that is calculated in the first part. (You can take the difference between the two to verify this).

A: My today practice for inverse matrix 3x3 is using
template<typename Derived>
template<typename ResultType>
inline void MatrixBase<Derived>::computeInverseAndDetWithCheck(
    ResultType& inverse,
    typename ResultType::Scalar& determinant,
    bool& invertible,
    const RealScalar& absDeterminantThreshold
  ) const

Set manual absDeterminantThreshold is default:
1)for float 1e-5
2)for double 1e-12
3)for long double 1e-15
For example your CODE:
Eigen::Matrix3d ATA_inv;
bool invertible = false;
double determinant = 0.;
double Threshold = abs(ATA.diagonal().prod());//maybe any test
ATA.computeInverseAndDetWithCheck(ATA_inv,determinant,invertible,Threshold<1e-12?Threshold*0.1:1e-12);


text:
Q: how to specalize class-member function template without class specialization For example, i have such code:
.h-file:
template <typename T1>
class Templ
{
    public:
    template <typename T>
    T foo (T t);
};

.cpp-file:
template <typename T1>
template <typename T>
T Templ<T1>::foo (T t)
{
    qDebug() << "Non-specialised template";
    return t;
}

template <>
template <>
int Templ<void>::foo (int t)
{
    qDebug() << "Specialised class template void> & method template <int>";
    return t;
}

if I call something like that:
Templ <void>t;
int i = t.foo<int>(1);

I will get expected "Specialised class template void> & method template " message, but if i want to call unspecialized function like that:
Templ <float>t;
int i = t.foo<bool>(1);

I will get undefied reference linker error. How do I call unspecialized function?
Also, how do I define specialized function of unspecialized class? I want to do something like
template <typename T1>
template <>
int Templ<T1>::foo (int t)
{
    qDebug() << "Specialised class template void> & method template <int>";
    return t;
}

but, obviosly, it will not compile.


text:
Q: How do I allow filter booleans to be non-mutually exclusive? I'm trying to filter my results using an object with values that are either true or false. However, these filters are not mutually exclusive, meaning more than one can be true.
The code shown only allows one filter to work, I assume I need to figure out a way to make showData dynamic but I'm not too sure how.
const filters = {
  letter: {
    A: false,
    B: false,
    C: false,
    D: false,
    E: false
  },
  number: {
    1: false,
    2: false,
    3: false,
    4: false
  },
  //...
};

const data = [
  {
    letter: "A",
    number: "1",
  },
  {
    letter: "B",
    number: "1",
  },
  {
    letter: "B",
    number: "2",
  },
  //...
],

const results = data.map((result, index) => {
  let showData = true;

  if (filters.letter.A) showData = result.letter === "A";
  if (filters.letter.B) showData = result.letter === "B";
  //...

  return (showData && result)
})}

An example of expected output is if both filters.letter.A and filters.letter.B were true, then results would return an array of objects matching these two filters.

A: Construct an array of the truthy keys in filters.letter in advance, and then you can set showCard based on whether the .letter of the current card being iterated over is included in that array:
const trueLetterKeys = Object.entries(filters.letter)
  .filter(([, val]) => val)
  .map(([key]) => key);
// ...
{data.map(({ letter }, index) => {
  const showCard = trueLetterKeys.includes(letter);
  // ...

Doesn't matter when there aren't many items, but to reduce complexity you could use a Set of truthy keys instead of an array, since a Set's .has is quicker than an array's .includes:
const trueLetterKeys = new Set(
  Object.entries(filters.letter)
    .filter(([, val]) => val)
    .map(([key]) => key)
);
// ...
{data.map(({ letter }, index) => {
  const showCard = trueLetterKeys.has(letter);
  // ...

A: You probably need that any condition should set showDara, but not clear it.
Simple solution:
//...
if (letter.A) showData = showData || data.letter ==='A';
if (letter.B) showData = showData || data.letter ==='B';
//...

Advanced:
If I correct in guessing your data, you may simplify the code.
This code will work in case data.letter and data.number is reasonable sanitized values that not interfere with build in or inherited properties:
//...
if(letter[data.letter] === true) showData = true;
if(number[data.number] === true) showData = true;
//...

More advanced:
This code looks more correct, but bit more complex:
(Using hasOwnProperty method to check that property defined in object itself and not inherited from parent object):
//...
if(letter.hasOwnProperty(data.letter) && letter[data.letter] === true) showData = true;
if(number.hasOwnProperty(data.number) && number[data.number] === true) showData = true;
//...


text:
Q: Mixed-ANOVA Design - Assumption 1) In a Mixed-ANOVA design, with one-between subjects (2 levels) and one within-subjects test (2 levels), do we normally check the Levene's output to ensure that we are not violating the assumption of homogeneity of variance in a Mixed-ANOVA? In this case, Mauchly's Test of Sphericity is not possible with 2 levels each.
2) Another way to verify that we are not violating the assumption of homogeneity of variances is to check if the ratio of the largest variance is not more than 4 times the smallest variance. Does this rule apply in a mixed-ANOVA design test, with a between-subjects and one within subjects test? For example, referring to the attached Table, in the case of a Mixed-ANOVA design, do I need to check the ratio of D/C and B/A (as they are two different groups)?


text:
Q: Campaign ID and Audience ID in SFMC? Where can I find the campaign ID and audience ID in SFMC?

A: You have to ask it opening a ticket to Support in order to create for you a custom data view with that information. The way Campaigns work in SFMC is totally different as in Sales Cloud.


text:
Q: UIButton set touch handler in code I want to accomplish touching a UIButton and having code run in a different class than the owner.
I realize I can do a touchUpInside to the button's owner (ClassA) and then call the method inside ClassB that I want called, but is there any way to expedite this?
ideas:

*

*have ClassB be the delegate for the ClassA->UIButton

*set the touchUpInside call in programming to used the function inside ClassB
I'm not sure how to accomplish either of these ideas :( Input is mas appreciated!

A: One option is to set the button up using
[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];

but this is a bit dangerous because target is not retained so you could send the message to a deallocated object.
You could instead set up a protocol
MyController.h

@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

Then in your implementation
MyController.m

- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}

As the method defined in the protocol was not optional I could have instead done a check for (self.delegate) to make sure it is set instead of respondsToSelector.


text:
Q: when to use AKNodeRecorder and AKClipRecorder I don't have much of experience with sound processing or producing or tools that people use when dealing with sound processing, and this is the reason why I reached AudioKit. Some of the classes doesn't have a brief description about the intention of them, why are they here of when should I use each of them as opposed to other closely related classes.
My concrete question is about the difference between AKClipRecorder and AKNodeRecorder. Why do we need to separate between the two of them? When to use each one of them?
Personally I use the AKClipRecorder only because I have a callback function that triggered when recording is done, and for example from looking into the source code I didn't understand why the removeTap function is located in the deinit function and not in stop function as the regular AKNodeRecorder.

A: The clip recorder has a few extra timing facilities for recording with a much higher degree of accuracy.
So if you wanted to record audio, play it, then record more audio that will be layered "on top" of the first recording, you'd need to use the clip recorder to achieve the accuracy needed to synchronize the second recording with the playback of the first.
The reason that the tap remains active after a clip is recorded is that you can record multiple (even overlapping) clips at a time.


text:
Q: Every Intermediate Field of Abelian Galois Field Extension is Splitting Field of a Separable Polynomial This is my question: Suppose the $K/F$ is a Galois extension with an abelian Galois group $G$. Prove that every intermediate field $L: F \subseteq L \subseteq K$ is the splitting field (over $F$) of some separable polynomial $f \in F[x]$.
I would like help in identifying which facts or theorems to use. Namely, I was thinking that I could prove that $L/F$ is Galois, thus a splitting field. I would use the FTGT in order to do so. Such $L$ (should it exist) must correspond to an abelian subgroup because $G$ is abelian. But, beyond that, I am not sure how abelianity helps at all (especially with the separability of $f$), or how even best to organize these thoughts into a coherent proof. Even an ordered list of properties and consequences would be nice.

A: (Below, "extension" means "finite extension".)
(1) Yes, $L/F$ is Galois. Intermediary extensions of a Galois extension correspond to subgroups of the Galois group, and those sub-extensions which are themselves Galois over the base $F$ correspond to normal subgroups. In an abelian group, every subgroup is normal.
(2) An extension is Galois if and only if it is normal and separable. In particular, $L/F$ is separable. By the primitive element theorem, there exists an $\alpha\in L$ such that $L=F(\alpha)$.
(3) Show that $L$ is the splitting field of the minimal polynomial of $\alpha$ over $F$.


text:
Q: Make js.erb file to work without ajax Ruby on Rails 4 I have a view
index.html.erb ->
link_to "click me " , 'customers/index' , :remote => true .
controller -> customers
def index
end

index.js.erb
alert('in js file');

alert works absolutely fine . but what if i don't want to make ajax and i just want js.erb file to work every time customers/index is loaded . I'm new to rails development and my question may very basic but i could not find a solution . I know that we specify the following when we want specific type . but as far i know my case is differenct
respond_to do |format|
format.js
format.html
end

A: You could simply move the code from index.js.erb to index.html.erb.
If you want to keep it separately then you could move js code to a partial and render it inside index.html.erb. See docs here.
Update
How to do this with partial:

*

*Create _yourpartial.js.erb and fill with js code

*To render the code inside 'index.html.erb' add this: <%= render partial: 'yourpartial', formats: [:js] %>
(But of course you would still need the script tag around the js code)

A: I'd try to help you. You can put your ajax into your application.js. For make it clean, you have to create one function into document ready. Document ready function will be active when the page have already done to load.
$( document ).ready(function() {
    callAjaxCustomerIndex(location.pathname);
});

function callAjaxCustomerIndex(current_url) {
  if (current_url == "/customers")
    $.ajax({
        url: "/customers",
        async: false,
        method: "GET",
        data: { "place_id" : place["place_id"] },
        success: function(data){
                 alert('success');
             }
         });
         infoWindow.open(map, marker);
         buildIWContent(place);
    });
}

This ajax request will be send when location.pathname is "customers". I hope this help you.


text:
Q: where does the t0000z come from? { "_id" : 1, "date" : ISODate("2019-06-23T00:00:00Z"), "tempsF" : [ 39.2, 53.6, 62.6 ] }
{ "_id" : 2, "date" : ISODate("2019-07-07T00:00:00Z"), "tempsF" : [ 57.2, 75.2, 51.8 ] }
{ "_id" : 3, "date" : ISODate("2019-10-30T00:00:00Z"), "tempsF" : [ 64.4, 42.8, 46.4 ] }

Where does the "T00:00:00Z" in "ISODate" come from?
to understand where did this come from in MongoDB database documents.

A: ISODate() is a helper function that's built into MongoDB and it provides output in global standardised ISO 8601 date format that is "YYYY-MM-DDTHH:mm:ssZ". Here "T" separates the date portion from the time-of-day portion. The Z on the end means UTC 11 (that is, an offset-from-UTC of zero hours-minutes-seconds). Also, that these default to 00:00:00 because time was not defined.


text:
Q: jQuery not changing the image source attribute on dynamically created image I am dynamically creating elements on click on my page:
                first()->image  }}"
                  onclick="magazineDetail(
                    '{{ $issue->first()->magazine->id }}',
                    '{{ $issue->first()->magazine->name }}',
                    '{{ $issue->first()->magazine->summary ?: '' }}',
                    '{{ $issue->first()->magazine->image ?: '' }}',
                    '{{ $issue->first()->image  }}'
                    )"
                  >

I call this script with the click:
function magazineDetail(id, name, summary, issueImage, magazineImage){
    images = [];
    nextImage = 0;
    loadedImages = [];

    $('#magazine-detail')[0].innerHTML = '

Neste utgivelse

Forrige utgivelse

<button class="button primary expand">Kjøp abonnement - 1 måned gratis</button><button class="button secondary expand">Bla igjennom arkivet</button>

';

    $('#image').attr({"src" : '/imagecache/cover/' + magazineImage, "alt" : name});
    $('#name').text(name);
    $('#summary').text(summary);

    if (issueImage != '') {
      $('#issueImage').html('');
    }

    $('html, body').animate({
        scrollTop: $("#magazine-detail").offset().top + 1500
    }, 1700);

    $.getJSON("issue/images",
        { id: id },
        function(result){
          if (result.length < 2){
              $('.magazine-preview-nav').hide();
          } else {
              $('.magazine-preview-nav').show();
          }
          $.each(result, function(i, value){
              images.push(value);
          });
          function imagePreload() {
              preload();
          };
    });

    console.log(images);
}

There I have
 that I am creating in $('#magazine-detail')[0].innerHTML.
Then I have a function that should change the src of that element with the id="image"  that is being created on click.
This is the script that takes care of that:
$(document).ready(function () {
    imagesIndex = 0;
    nextImage = 0;
    loadedImages = new Array();

    function preload() {
      console.log('entered');
        for (i = 0; i < 2; i++) {
            if (nextImage < images.length) {
                var img = new Image();
                img.src = '/imagecache/cover/' + images[nextImage];
                loadedImages[nextImage] = img;
                ++nextImage;
            }
        }
    }

    $('#magazine-detail').on('click','#forward', function() {
      imagesIndex++;
      preload();

      if (imagesIndex > (loadedImages.length - 1)) {
          imagesIndex = loadedImages.length - 1;
      }
console.log(loadedImages.length);
console.log(loadedImages[imagesIndex].src);
      $('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
    });

    $('#magazine-detail').on('click','#forward', function() {
        imagesIndex--;

        if (imagesIndex < 0) {
            imagesIndex = 0;
        }

        $('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
    });
});

On inspecting the console.logs I see that the new images are being created with the preload function, and that the correct image src is being passed to:
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
But the image on page is not being changed. I should also maybe mention that everything worked fine when I wasn't creating those elements after the page has loaded but had them hiddden.

A: It seems that there is a minor bug in the $(document).ready(function(){   }); .
The code has 2 click events for same button #forward. Probably one should be assigned to #back button.


text:
Q: Open new window with Javascript window.open I'm trying to open a new window when a form is submitted, I have the following code:
var action = window.open("http://myurl.com" + code + "&rp=" + window.rp + "23-421B-A4A2-";)

$('#theForm').attr("action", action);

However that causes an error, how do I append window.open correctly? Thanks.

A: I think what you are looking for is this:
$('#theForm').click(function(event) { // or $('#theForm').submit(function(event) {
    event.preventDefault();
    window.open("http://myurl.com" + code + "&rp=" + window.rp + "23-421B-A4A2-", windowHandle);
});

More info on window.open.

A: this should be something like:
<form id="theForm" action="http://myurl.com/.../...?..." target="_blank"></form>

A: There are two ways of solving this:

*

*Using "action" + "target=_blank"
var action = "http://myurl.com" + code + "&rp=" + window.rp + "23-421B-A4A2-";
$("#theForm").attr("action", action).atrr("target", "_blank");

*Using "onsubmit" event
$("#theForm").on("submit", function(e) {
    e.preventDefault();
    window.open("http://myurl.com" + code + "&rp=" + window.rp + "23-421B-A4A2-");
}

EDIT:
After you showing your HTML, there are other problems there:

*

*You're not using a submit button, you're using a image input instead.

*You have this code in your JS:
$('#submit').click(function($e) {
    $e.preventDefault(); //Don't want button submitting the form because the action is not correct
    if (window.console) console.log($('#theForm').attr("action"));
    window.parent.location = ($('#theForm').attr("action"));
});

*So, you need to modify this code to (or something like that):
$('#submit').click(function($e) {
    $e.preventDefault(); //Don't want button submitting the form because the action is not correct
    if (window.console) console.log($('#theForm').attr("action"));
    window.open($('#theForm').attr("action"));
});


text:
Q: Are $L_p$ norm and discrete $L_p$ norm comparable? Are there any estimates on how a $L_p$ norm (say for a compact set in $\mathbb{R}$) is related to a discrete $L_p$ norm, where we could for example consider the Jackson integral on this compact set. If necessary, we could for example work on the interval $[0,1]$ and then we are looking for any relationship between the integral \begin{equation} \left(\int\limits_0^1 |f(x)|^p dx \right)^{1/p} \end{equation} and the integral \begin{equation} \left(\int\limits_0^1 |f(x)|^p d_q x \right)^{1/p} := \left(\frac{1}{q-1}\sum\limits_{i=0}^\infty q^i |f(q^i)|^p \right)^{1/p}. \end{equation}

A: Let $f(x) = k \sin(\pi x)$, where $k \in \mathbb{C}\smallsetminus \{0\}$.  Then $\ell_p(f) = 0$ and $L_p(f)$ can be as large as you like by adjusting $k$.  On $[0,1]$, use $k \chi_{[0,1] \smallsetminus \mathbb{Q}}$ (since $\chi_S$ is the indicator function for the set $S$, this is $0$ on rationals, $k$ on irrationals).
To reverse the inequality, let $f$ be bumps of height $k$ and width $\mathrm{e}^{-n}$ for all $n \in \mathbb{Z}$ and zero otherwise.  (Isosceles triangles are fine bumps, as is any other bump with compact support.  It really doesn't matter how you deal with the overlaps near $n=0$.)  On $[0,1]$, reverse the inequality with $f = k \chi_\mathbb{Q}$.
In other words, we can always arrange for a function to be zero on whatever set you like and nonzero off of it, so we can always "fool" the discrete norm, no matter what (uncountable) set you take as your domain, since that norm can only sample countably many points.  (This requires the quantifiers of our game to be in the order "you tell me your norm(s), then I get to construct a function to fool it/them.")


text:
Q: Issue with items of listview i don't know why but when i add items to listview i get only the last item. E.G. if i write apple and than pear i get only pear and not apple and pear.
Why?

CODE:
 holder.button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                System.out.println("IDDD:"+iddd);
                System.out.println("IDDD:"+video2.getPic());

                //holder.lw.setA

                String commento= (holder.tw.getText().toString());
               // holder.lw.setAdapter(adapter);
                 ArrayList<String> arrayList= new ArrayList<String>();
                final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrayList);
                arrayList.add(commento);
                // next thing you have to do is check if your adapter has changed
                holder.lw.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                System.out.println("LISTVIEW:"+arrayList);

            }

        });

A: You are creating new list and adapter during every click so move the declaration and initialization of both, outside that function

*

*Declare them outside getView(if Base or ArrayAdaoter) or createViewHolder (RecyclerAdapter)

*initialize them inside constructor

*add data to list and notify adapter

A: in every click you decalre new list ArrayList<String> arrayList= new ArrayList<String>(); and it's false
you need to declate it out of the listener and in your listener just add the new items and use adapter.notifyDataSetChanged();

A: Better use view holder pattern in here where you use Existing instance of listview rather than recreating the new one all the time.

A: You don't need to do anything special, inside of onClick you need to get a reference to your ArrayAdapter and call the method add(T...) on it.
holder.button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                System.out.println("IDDD:"+iddd);
                System.out.println("IDDD:"+video2.getPic());

                String commento= (holder.tw.getText().toString());
                ArrayAdapter adapter = (ArrayAdapter) holder.lw.getAdapter();
                adapter.add(commento);
            }
        });

No need to even call notifyDataSetChanged because add already does that internally.

A: if you use this you can solve your problem
yourAdapter.(getCount()-1-position);

and this if you want to see the last items in front
  public yourPoJo getItem(int position) {
                return super.getItem(getCount()-1-position);
            }


text:
Q: Which directory to put mocks? I've been most recently experimenting with GoMock, the test mocking framework supported by the official creators of the Go language. I was wondering where is the most reasonable place to put these mocked files.
My current directory structure is as follows. Is this how Go projects should be structured?
appname
|-- gateways
    |-- gateway1.go
    |-- gateway1_test.go
    |-- gateway2.go
    |-- gateway2_test.go
    |-- mocks
        |-- gateway1.go
        |-- gateway2.go

This is slightly influenced by Ben Johnson's talk here.

A: I tend to follow this article also by Ben Johnson
Link to article
In general this approach of having a package for your shared mocks is a good one. One thing worth pointing out here is that if you don't define your models outside of the gateways package you could get an import cycle.

*

*gateways defines models

*mocks imports gateways.Model

*gateways imports mocks for tests

There are 2 ways to fix this; the first is just to move your models into domain, a root package outside gateways (see article for examples). Or only test the public interface of your gateways package by using gateways_test as the package in your test files.


text:
Q: where is pageProps in nextjs v13? in earlier version of next, we have this file pages/_app.js which by default gives us this :

we have pageProps key in this react component. when i tried nextjs v13, i can't seem to find it.
my question is where is that (in this case, in which file) pageProps existed in nextjs v13?
and the other related question is, in the earlier version of nextjs we can do something like
<p.Component {...p.pageProps} /> in the pages/app.js
notice we can pass the pageProps because we're using a tag.
but in the latest version, you can only use something like
{p.children} which means you cannot pass props anything.
i tried to make it <p.children /> but it doesn't work.


text:
Q: kube-state-metrics - Failed to list *v1.Pod: serializer for text/html; charset=utf-8 doesn't exist I'm trying to setup a monitoring of our Kubernetes cluster but it's not that easy. In the first time I tried on a dedicated VM to scrap all metrics following configs I can find on Internet and prometheus.io but I read several time it's not the best way to do it. I found a suggestion to use kube-state-metrics, it's done, the pod is running and metrics are reachable from outside (Azure infra). so http://xxx.xxx.xxx.xxx:8080/metrics is showing me a correct result.
When I add this to the config:
- job_name: 'Kubernetes-Nodes'
  scheme: http
  #tls_config:
    #insecure_skip_verify: true
  kubernetes_sd_configs:
  - api_server: 'http://xxx.xxx.xxx.xxx:8080'
    role: endpoints
    namespaces:
      names: [default]
    #tls_config:
      #insecure_skip_verify: true
    bearer_token: %VERYLONGLINE%
  relabel_configs:
  - action: labelmap
    regex: __meta_kubernetes_service_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_service_name]
    action: replace
    target_label: kubernetes_name

The log I can find is :
Sep 25 06:53:59 monitoring001 prometheus[59005]: level=error ts=2018-09-25T06:53:59.636669498Z caller=main.go:234 component=k8s_client_runtime err="github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go:288: Failed to list *v1.Pod: serializer for text/html; charset=utf-8 doesn't exist"

Anyone has an idea ?
Thank you,

A: Finally found the issue ! My Prometheus is located on a dedicated VM outside Kubernetes cluster.
Kube-state-metrics is exposing metrics from an IP outside of the cluster,because of this, it's not necessary to scrap metrics like a kubernetes object, it's just necessary to scrap metrics like a simple target


text:
Q: Can context change how a wish clause will be formed? I know that for present wishes, I can say:
I wish I were young.
However, what if this is my "birthday" wish?
Could I say:
I wish I would be young.
to express I want this to happen somehow, like magically for example?

A: So, by "birthday" wish, I take it you mean similarly to having a genie or a wishing ring - expressing something that might be granted magically. As opposed to "present wish", which from how you phrase it sounds like expressing an idle desire, possibly impossible to fulfil.
In that case, I would probably express it as "I wish to be young". Possibly "I wish to be young again", as one assumes that most people were. Though if I had an actual genie or wishing ring, I'd be a lot more precise with that wish.


text:
Q: Overview (List) off Organizations with the same Domain Name within one subscription I want to have a list off all the organizations within one subscription.
Some people have made their own organizations and i can see them

A: You can download a complete list of organizations backed by an Azure Active Directory (Azure AD) tenant. Check the following link:
https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/get-list-of-organizations-connected-to-azure-active-directory?view=azure-devops

Using any organization backed by your Azure AD, complete the following
  steps.

*

*Sign in to your organization (https://dev.azure.com/{yourorganization}).

*Select Organization settings.

*Select Azure Active Directory, and then Download.


text:
Q: R-tree - Remove algorithm using reinsertion I am trying to implement an R-tree in scala following the guidelines from the original paper about the R-tree structure. In the deletion algorithm section is stated:

Reinsert all entries of nodes in set Q. Entries from eliminated leaf nodes are reinserted in tree leaves as described in Insert, but entries from higher level nodes must be placed higher in the tree, so that leaves of their depedent subtrees will be on the same level as leaves of the main tree.

I can't wrap my head around the last part. What is meant by higher level nodes must be placed higher in the tree? How is that implemented? My idea was that I remove nodes that underflow add them to the set Q (their entries) and in the end I reinsert their entries using Insert. Is this incorrect or partially correct that requires something extra? If you can explain using examples as well that would be great.

A: Nodes must be reinserted in the correct height, or the tree will become invalid. Remember that all leaves must be at the same level.

A: Inserting and removing values in R-Tree is a quite expensive operation when you need to keep it optimally balanced for fast window or nearest requests, especially in a multi-thread environment.
A more efficient approach is using one writer (actor or thread) which gathers updates in batches, packs a new R-Tree instance and publishes it in some volatile variable for reading.
Here is a comparison of some R-Tree implementations that can be used in such a way from Scala.


text:
Q: Guardar Excel en Base 64 A Excel Angular6 Tengo un servicio de Springboot que envía al front un Excel en base64, no puedo enviar el Excel directamente por políticas de empresa...
Mi servicio envía:
{
 "file": "UEsDBBQACAAIAE6ROU/kSK2vGAEA.........etc"
}

Y con Angular6 recojo, decodifico la base64 y lo guardo en formato Excel:
this.data.getFile(endPoint).subscribe(
          data => {
                     const myfile= atob(data.file);
                     const blob = new Blob([myfile], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                     saveAs(blob, 'myfile.xlsx');
                  } );

El contenido de myfile después de atob es:

Después se guarda el fichero. Finalmente cuando voy abrirlo me da error, dice que el fichero está corrupto.
¿Alguien puede ayudarme ? muchas gracias desde ya.

A: Solución :)
public base64ToBlob(b64Data, sliceSize=512) {
let byteCharacters = atob(data.file);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    let slice = byteCharacters.slice(offset, offset + sliceSize);

    let byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
    }
    let byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
}


text:
Q: How much health do the turrets and drill have? Since you can tell numerically how much damage you do per attack from the numbers that pop up above the enemy, how much total damage needs to be done to turrets and drills in order to destroy them?

A: According to awesomenauts.wikia, turrets have 1200 health and the Solar Drill also have 1200 Health.

A: As of Patch 2.7 (released October 23, 2014), all damage and health numbers were multiplied by 10, to allow for more fine-tuning of damage numbers, which is why my numbers will be so different from the ones of the other answer currently present.
The Solar Drill always has 12,000 health, but the amount of health a Turret has varies between individual turrets. Generally, a front turret will have 7,650 health, and a back turret will have 11,900 health. Exceptions are as follows.
Sorona - front bottom: 5,300 health
AI Station 404 - front: 10,200 health
AI Station 404 - back bottom: 7,650 health
Note that unlike the health bars of 'Nauts, the health bars for turrets and drills always have 14 blocks when full, no matter what their max health is, so you can't figure out absolute values from that.


text:
Q: flex adaptative textinput function of maxchars I want to build a textinput that adapts itself from the maxchars value of its textdisplay.
I tried to override the init function of the component like this:
override protected function initializationComplete():void{
   if(this.textDisplay.maxChars != 0){
      this.maxWidth = this.textDisplay.maxChars*10;
      super.initializationComplete();
   }
}

But it doesn't work at all. How can I code this?

A: Thats already there in s:textinput property named widthInChars
set that value to maxChars value like this
Im mxml
<s:TextInput id="txtName" widthInChars="{txtName.maxChars}" maxChars="23" />

In as
txtName.widthInChars = txtName.maxChars;

Try this
I hope this might help you.


text:
Q: Is base method able to use derived base data members? Lets assume we have the following code:
abstract class Base1 {
    protected int num;
}

class Der1:Base1 {
    protected Color color;
    protected string name;
}

class Der2:Base1 {
    protected DateTime dthen;
}

and so on. An array of base1 type exists and includes many objects created out of classes that are derived from base1.
Is it possible to define the toString() method in the base class only?
something like:
public override string toString()
{
    if (this is Der1)
        return "num = " + this.num + "color = " + this.color.toString() + " name = " this.name;
    if (this is Der2)
        return "num = " + this.num + "dthen = " + this.dthen.toString();
    // and so on ...
}

Thank you very much :)
P.S. This is not an homework question. I've just wondered about.

A: The only way to do this is to cast this to each derived type.  (And even that will only work if the members are public)
However, you really should override the method instead.

A: No, this is impossible unless you change all members' fields access modifier to public.
And generally speaking: this is a bad practice. Base classes should not know anything about derived classes.

A: It is possible, but

*

*derived classes members should be public

*you are missing an explicit cast:
public override string toString()
{
    if (this is Der1)
        return "num = " + ((Der1)this).num + // etc...
And by the way, this is very bad, as you should override ToString in derived classes Der1 and Der2 - that's what polimorphism is for.

A: You should let the derived classes handle how their version of ToString should behave.
Letting the base class depend on all the derived classes makes for a really fragile design.

A: It looks like what you're trying to avoid is replicating the code in the abstract base class that prints its information in ToString().  You can solve this using a virtual method in the base class like GetExtraString(), which is overridden in descendant classes to only return the extra information you'd like in your base ToString().


text:
Q: how to make terminal remember ssh passphrase I have always to enter my ssh passphrase (I use ubuntu), I used ssh-add :
ssh-add /home/ismail/.ssh/id_rsa

but this makes terminal remember my passphrase till I reboot.
Is there a way to make my terminal remember my passphrase FOREVER ?

A: I'm not sure if this is possible. Probably not, because it woudn't make much sense. Making your terminal remember your passphrase forever would in some extend mean that the passphrase has to be stored on your hard drive somewhere. This is just as secure as not having a passphrase at all, so I'd suggest you just remove your passphrase. You just have to make sure that your account is secured, so that nobody can steal your private key.


text: Q: Where to set php module version in apache 2.4.7 Having looked in /etc/php/apache2/php.ini, /etc/apache2/apache.conf /etc/apache2/mods-available/php.conf I cannot locate where to load my newly built php? There are no LoadModule directives anywhere, and I can't find any answers on the web. Has something new changed in 2.4.7?


text:
Q: Translating normal code to 3AC - Three address code I am trying to make an algorithm that will transcribe certain input, such as:
(a * b) / (c * d)

and will print out input like this in 3AC:
t1: a * b
t2: c * d
t3= t1/t2

Has anyone any suggestions?

A: Algorithm for transcribing such equations is pretty straightforward.
Obviously first task would be to convert given equation to reverse polish notation. From here you already have perfectly defined order of execution.
You now have to prepare stack for operands. At this point you just do it like normal RPN, except instead of performing operation and putting result back on operands stack, you have to print new TAC instruction with new number, and put that symbol back on stack instead of result.
In your example RPN will be : a b * c d * /
So a and b go on the stack. When we encounter * we pop 2 items from stack, print t1 := a * b and put t1 on stack. Now we traverse RPN more and put c and d on stack. Now we come to encounter another *, so again lets pop 2 items from stack, print them with new TAC symbol t2 := c * d and put our new symbol t2 back on stack.
lastly we encounter / so again we pop 2 items from stack, create new symbol and print it :) t3 := t1 / t2.
This is much simpler than standard RPN calculator.

A: One way you could do this is to first turn this into an AST
then traverse the AST by recursive function to make your code.
for your example your code will be turned into something like this
("/", ("*", "a", "b"), ("*", "c", "d")
traverse with said function and turn it into this
t0 = a * b
t1 = c * d
t2 = t0 / t1


text:
Q: UBUNTU SPHINX FATAL: failed to open log file '/var/log/sphinxsearch/searchd.log': Permission denied, как исправить? у меня при вводе команды вылезает следующая ошибка.
/etc/init.d/sphinxsearch restart
Restarting sphinxsearch: Sphinx 2.2.11-id64-release (95ae9a6)
Copyright (c) 2001-2016, Andrew Aksyonoff
Copyright (c) 2008-2016, Sphinx Technologies Inc (http://sphinxsearch.com)

using config file '/etc/sphinxsearch/sphinx.conf'...
WARNING: key 'max_matches' was permanently removed from Sphinx configuration. Refer to documentation for details.
WARNING: key 'enable_star' was permanently removed from Sphinx configuration. Refer to documentation for details.
WARNING: key 'charset_type' was permanently removed from Sphinx configuration. Refer to documentation for details.
FATAL: failed to open log file '/var/log/sphinxsearch/searchd.log': Permission denied

Я так понимаю, что у Сфинкса нет прав на запись.
Какие права нужно установить на папки
log = /var/log/sphinxsearch/searchd.log
query_log = /var/log/sphinxsearch/query.log
pid_file = /var/run/sphinxsearch/searchd.pid
binlog_path = /var/lib/sphinxsearch/data/
path = /var/lib/sphinxsearch/data/bitrix

чтобы сфинкс коррекно работал?
Я так понимаю, нужно создать пользователя сфинкс, верно?


text:
Q: sshpass throwing error 'Failed to get a pseudo terminal: Success' I am trying to run the sshpass tool to automate an sftp action.
On another server, the command works, but on this server it just returns one line of error mesage.
Here is the command I am using:
sshpass -p Password sftp Uname@Host

And I get the error:
Failed to get a pseudo terminal: Success

I've tried it with lots of different hosts and as the root user, and I can sftp in without a problem so I am pretty sure it is either a sshpass or pseudo terminal issue.
I don't know a whole lot about pseudo terminals and can't seem to find anything on the error.
The folder /dev/pts is empty and cat /proc/sys/kernel/pty/nr is 0, which I think means that there aren't any running. There are 256 pty** items, from ptya0 through to ptyzf which makes me believe that I may have reached a limit for the number of pseudo terminals. I think my max terminals (by looking at cat /proc/sys/kernel/pty/max) is 4096.
Has anyone else experienced this error or know what may be wrong? It is a production server so I can't afford for it to be down. Any help on this would be greatly appreciated.

A: Figured it out. To anyone who has a similar error, the pts directory was unmounted for some reason. Doing the following did the trick:
rm -rf /dev/ptmx
mknod /dev/ptmx c 5 2
chmod 666 /dev/ptmx
umount /dev/pts
rm -rf /dev/pts
mkdir /dev/pts
vim /etc/fstab
    (added: none  /dev/pts  devpts  defaults 0 0)
mount /dev/pts


text:
Q: Text looks odd on certain places in google chrome after upgrade to Ubuntu 18.04 I just upgraded to Ubuntu 18.04 from 17.10 and suddenly the font rendering on google chrome looks very strange. There appear to be additional marks on it. I attempted to restore all chrome settings to default, but it did not appear to fix the issue.

Any thoughts on how to resolve? The issue is not present on any other applications on my system, so it appears to be a chrome specific issue.

A: I encountered this with version 54 of Chrome. Upgrading to 67 sorted it out


text:
Q: Fixed currency prices, websites, single domain We have a client who has an existing Magento website. It is one website, one store, and one store view. The base currency is GBP.
They have recently raised a question about adding the option of offering their products at USD prices as well. They would like to specify the USD prices (ie. not use conversion rates). The background is that they currently have a US distributor of their products which is not currently being utilized on the GBP site, and all US customers are having to pay pricing to ship from UK to US, using the UK-based distributor.
In the past, when we've had clients with the need for multi-currency, we have set up each currency in separate store views, and installed InnoExt Advanced Pricing module  http://innoexts.com/promotion/advanced-pricing/ to allow setting of fixed prices per currency. But we've found issues with Magento reporting and credit memos with orders placed in "other" currencies as Magento still uses its currency rates for these areas and still takes one currency as the "base currency".
Due to these issues, I'd like to rethink what our setup should be. I'd like to stick to Magento's default behaviour as much as possible, with minimum requirement for third party modules. My feeling is that we should build another Website (the US website), set USD as the base currency for that website.
The specs are:

*

*Products should be shared between US and UK distribution.

*Customers are shared between the US and UK distribution.

*Other content like pages/blog posts (aheadWorks blog) should be shared between US and UK.

*The whole environment exists on a single domain (is this possible with multi-website)?

*There may be different tax rates for the US and UK distribution.

*There may be different shipping methods for the US and UK distribution.

*There may be different payment accounts or gateways for the US and UK distribution.

Am I right in thinking baskets cannot be shared between websites? For example, if someone is in the UK store but they want to ship to the US and enter that address on checkout, switching them to US website would not be as simple as switching store views is?
I know of course we need to investigate and test this, but I would like thoughts from the Magento community on the best strategy for how to set this up. Are we right to go down the multi-website route?
Thank you so much for any advice in advance, and for reading this!

A: You are not completely right about baskets not being shared between websites. The reason is that normally Magento uses a specific Website scope (so Magento terminology) to refer to a specific website (so common web terminology). A website is bound to a domain, so this also implies each Website scope has its own domain. And because cookies can't be shared across domains, Magento sessions can't be shared across domains and the shopping cart can not be shared either. But this is the default setup. If you are using multiple Website scopes that are all part of the same website (www.example.com), the same cookie (for instance, the frontend cookie) is shared across all Website scopes (Magento terminology), because they are technically part of the same "website" (web terminology).
Unfortunately, there are still some parts in Magento that lock a carts content to the Magento Website-scope. You might be interested in this post here:
http://turnkeye.com/blog/share-magento-cart-between-multistores/
Does this help you a bit further?


text:
Q: Mathematica function defining problem
The "F" function is defined as mentioned, but when I call the function F inside the code, "F" can't compute value using the function F, just give F_0, F_1, etc. Can somebody guide me what is the problem with the definition?
Thank you in advance!

A: Here is your code with correct syntax:
z[0] = 1;
z[k_] := (1 - (1 + a)/k) z[k - 1];
f[k_] := (3/2)^
    a (Sum[z[k] z[k - t + 1], {r, 2, k}] + (1/2^(k + 1) z[k + 1]));
m0 = 1/(25 f[0]/36 + 10  s1/3)
m1 = -5 f[0]/72 + 2 s1/3
m2 = -f[0]/144 + s1/6


text:
Q: How can I TGA file format to DDS format? I have a question. Could you help me, please?
import os
import sys

def prozess_start(programmName, parameter):

    return os.execv(programName, parameter)

def read_files(pfad):

    TGA_files = []

    name_file = os.listdir(pfad)

    t = []

    for i in name_file:

        if i.endswith(".TGA"):

            TGA_files.append(i)

    return TGA_files

input_path = "..."

outut_path = "..."

parameter = ["input_file", "output_file", "1", "2", ..]

l = read_files(pfad)

for i in l:

    parameter[0] = input_path + i

    parameter[1] = outut_path + i[:-4] + ".DDS"

    prozess_start("...exe", parameter)

The Code doesn't work.
I have files with ending .TGA and I would like to format it to .DDS.
Maybe You see  mistakes?
Thank you very much!


text:
Q: Guest user causes 'Shell Infrastructure Host has stopped working' messages I'm running Windows 10, 64 bit, and whenever someone tries to use the guest account, nothing loads and the following error is displayed on the screen: Shell Infrastructure Host has stopped working
I logged in as an Administrator and checked the event viewer to find out what is going on, this is what comes up:

The application that matches {8BC3F05E-D86B-11D0-A075-00C04FB68820} is Windows Management and Instrumentation.
I tried to look it up on Google but nothing seems relevant.


text:
Q: Is there any reason to continue reading InputStream if number of read byte is 0? Usually, when I deal with InputStream, and condition of stop reading is when the number of read byte is less than or equal to 0
For instance,
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
}

However, when I look at the documentation of InputStream
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[])
Only I notice that

-1 if there is no more data because the end of the stream has been reached.

I was wondering, should I refactor my code to
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
    if (len > 0) {
        out.write(buf, 0, len);
    }
}

Will there be any edge case checking for while ((len = in.read(buf)) > 0) is going to cause any unwanted bug?

A: Since read is specified to block until data is available, the only way that it returns 0 is if the buffer you input into is is of length 0 (which would be a pretty useless buffer).
See the JavaDoc:

This method blocks until input data is available, end of file is detected, or an exception is thrown.

and

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte.

So the four possible cases are:

*

*b is a byte[] of length 0, so 0 is returned

*input data is available: non-zero bytes will be read into b and that number returned.

*end of file is detected: -1 will be returned

*an exception thrown: no value is returned, when a method returns abnormally with an exception.

A: You don't need to check if (len > 0) as out.write(buf, 0, len) handles condition when len is 0.
Save time typing the while loops in future by refactoring your code to this one liner which does the equivalent copy from in to out using a buffer and loop condition while ((len = in.read(buf)) != 0):
in.transferTo(out);


text:
Q: Strange wm_keydown behaviour with THtmlEdit This is a strange one: This is the situation
The application builds an edit form at run-time from an XML document. The UI/UX design is such that there are three levels of nested TTabControls and for the final (lowest) level the TTabItem is created at run-time. This has a TVertScrollBox which itself contains a column-grid control of mine and that (at last!) contains the THtmlEditor.
The problem is that when the controls are built and the content loaded, the THtmlEdit initially ignores keydown. It will respond to mouse events, the caret can be positioned. Switching to a different top-level tab, or away from the whole application and back, then cures the issue and the editor responds to keydown messages.
I have tried putting a breakpoint in procedure THtmlEditor.KeyDown() ... and then tracing back up the call-chain. There doesn't seem to be anything behaving differently. I've paid particular attention to input focus, explicitly calling Editor.SetFocus even though that is apparently already called ...
I have tried putting a conditional breakpoint in function TPlatformWin.HandleMessage: Boolean; ... and my only observation is that when in non-working mode, the call to DispatchMessage(Msg) doesn't arrive at the editor, or its parent form.
I have tried to build a MDC for this, replicating the structure outlined above but ... that always works!
What can I try next?
Has anyone seen this behaviour (and fixed it)?
EDIT:
The detail I didn't mention -- didn't think about it -- is that for the error condition to show, the control focused before the THmtlEditor is a TWebBrowser. If I set focus on a TEdit after TWebBrowser and then to THtmlEditor it seems to work.
Grrr!

A: This is only half an answer, but for future reference, this is what I've done:
It's a bodge :-(
I've put a TEdit on the main form and set it invisible. I've then added a handler to the MainForm OnFocusChanged which sets a boolean trap-flag to track if TWebBrowser has previously been focused.
For the instances of THtmlEditor I've added an OnClick handler which checks the trap-flag and makes the TEdit visible, calls SetFocus on it, re-hide the TEdit and return True so that the THtmlEditor can re-set focus to itself. The trap-flag is to avoid unnecessarily losing focus if the user is just clicking in the THtmlEditor.
The next step -- which I may never get to -- would be to trace through the focus code for TEdit. My suspicion is that it all relates ITextInput which TEdit supports and THtmlEditor doesn't.


text:
Q: Angular UI - ui-select custom styling So I am using ui-select with angularjs to create a configurable directive. The functionality on the backend is almost done but our prototype has very specific styles and I need to adhere to those styles.
I would like to simply re-style the ui-select as I see fit but I can't seem to find a single tutorial online on how to do so. I have found a few examples on overriding the template that angular ui uses using $templateCache. Is there a way to simply have a css file somewhere that it uses instead of its default? Or is there a way to override the current classes without a bunch of !important tags.

A: Of course, you can change the entire style of the UI-select directive by our own CSS. There is no restriction for that, take a look at sample CSS changes in the link.
.ui-select-container {
  width:  200px;
}
.ui-select-bootstrap .ui-select-choices-row.active>a {
  background: #000;
  color: #fff;
}
.ui-select-container input {
    border: none;
    border-bottom: 1px solid #ccc;
    box-shadow: none;
}


text:
Q: php mysql best practice show selected in dropdown I have a fairly simple problem.  I have a select dropdown with values 1 to 10.  This is an edit screen so users have already chosen a value that should be selected.  I am giving them the chance to change it.  So all I need to do is insert the word selected in the option value.  To accomplish this simple task, I have been doing a bunch of inelegant if thens.  Is there a best practice or simple way to do this.  It seems unnecessary overhead to do all these if thens and create 10 new variables.  Note for reasons of keeping html separate from php logic, I do not want to write the option values out sequentially  I have the html in a separate area and just need to set the variable selected in the appropriate places.
if ($row['points']==1){
$select1 = "selected"}
if ($row['points']==2){
$select2 = "selected"}
//values 3 through 9
if ($row['points']==2){
$select2 = "selected"}

echo '<select name="points">';
echo '<option value = 1'. $select1.'>1</option>';
echo '<option value=2'. $select1.'>2</option>';
//values 3 through 9
echo '<option value=10'.$select10.'>10</option>';
echo '</select>';

A: for ($x = 1; $x <= 10; $x++) {
   echo "<option value=$x" . ($row['points'] == $x ? ' selected' : '')
      . ">$x</option>';
}

A: a for loop is good for this, with an inline if else statement to test the selected case
echo '<select name="points">';
for ($i=1; $i<=10; $i++) {
   echo "<option value='{$i}'".($row['points']==$i ? ' select="selected"':'').">{$i}</option>";

}
echo '</select>';

A: Because you are using single selectable list (no multiple selected allowed) i.e. so only one can be selected at once.. look for http://fi.php.net/str_replace
echo str_replace("value='".$selected_value."'", "value='".$selected_value."' selected", "<option value='1'>1</option><option value='2'>2</option> ....");

A: I do it with jquery and a hidden field that inidcates the selected value of a <select>.
html:
<input type=hidden name=points value=1>
<select name="points">
  <option value=1>1</option>
  <option value=2>2</option>
</select>

js:
$('input[type=hidden]').each(function(){
            var e = $(this);
            var name = e.attr("name");
            var val = e.val();
            if(name!="")
            {
                e.parent().find('select[name='+name+']').val(val);
            }
        });

example


text:
Q: Display a programmable field several times on the screen I am a newbie. Can anyone help me?
I have made a function with a programmable input field. I want to call this function several times and display the results at different coordinates on the screen.
What do I wrong and how should I solve it?
// inputName function

NSString* inputName (
       int controlX,
       int ControlY,
       int controlWidth,
       int controlHeight,
       NSString* myQuestion)
{

  // *********************** Inputfield **********************
  UITextField *inlogName=[[UITextField alloc] initWithFrame:CGRectMake(controlX,controlY,controlWidth, controlHeight)];

  [inlogName setBorderStyle:UITextBorderStyleRoundedRect];
  [inlogName setPlaceholder: myQuestion];

  [inlogName setDelegate:self]; // HERE I GET AN ERROR ???????

  [inlogName text];
  NSString *anwser= @"This is a dummy anwser";

  [self.view addSubview:inlogName];  // HERE I GET ALSO AN ERROR ??????

  return anwser;
}

A: You have created a C function and have no reference to self in it.  I would suggest making it a method on your view controller and invoke it from there.


text:
Q: Parsing a file with repeating sections in Perl I'm trying to use Perl to parse a file that has repeating sections like this:

System:      server1.domain.com
Start Time:  20121021T01:00:56
Stop Time:   20121021T01:00:56
Return Code: 0

Output
------
user1
user2
user3

##############################

System:      server2.domain.com
Start Time:  20121021T01:00:56
Stop Time:   20121021T01:00:56
Return Code: 0

Output
------
user1
user4
user5
user6

I'm able to set the input record separator to "##############################" which will give me each block as a separate record.
But I need to be able to populate a hash with the usernames as keys for each server.
What's the best way to accomplish this?

A: Try doing this :
use strict; use warnings;
use Data::Dumper;          # one of the top 5 modules you should know

my $hash_of_hashes = {};   # a reference to a void HASH

my $current;

while (<>) {
    chomp;
    if (/^System:\s+(.+)/) {
        $current = $1;
    }
    elsif (/^([^:]+):(.+)/) {
        $hash_of_hashes->{$current}->{$1} = $2;
    }
}

print Dumper $hash_of_hashes; # Dumper is a function of Data::Dumper module
# it prints all the data structure in a human readable way

To use it :
perl script.pl input_file.txt

NOTE
I make the assumption that System: line is all the time matching the first line of the current host.

A: You should look into Perl references.
In Perl pre release 5.0, you had three types of data structures, and you could only store scalar data in them. For example, I could have a hash, but each value of the hash could be a string or number.
Perl 5.0 introduced references. A reference is a piece of data that points to another data structure. For example, you could have a hash which represents the servers. Each member of the hash points to another hash that contains users (or a list of users if you'd like).
For example, you have a hash that looks like this:
$system{server1.domain.com}  --->  $anon_array[0] = "user1"
                                   $anon_array[1] = "user2"
                                   $anon_array[2] = "user3"

$system{server2.domain.com}  ----> $another_anon_array[0] = "user1"
                                   $another_anon_array[1] = "user2"
                                   $another_anon_array[2] = "user3"
                                   $another_anon_array[3] = "user4"

You can see in the above that the key of your %system hash actually points to some array in memory that contains the list of users. These arrays don't have a name such as @foo or @bar. The only way you can access them is though your %system hash. Thus, they're known as anonymous arrays.
To create a reference, you put a backslash in front of the variable:
$my_reference = \%my_hash

Now, $my_reference points to the members of the hash %my_hash. If I want to make the reference into a hash again, I precede it with the hash sigil (the %):
%bar = %{$my_reference};

You can use the -> syntax to show that something points to a reference:
$foo->[0];   Points to the first member of an anonymous array.

$bar = [];    #Sets $bar to be a reference to an anonymous array
$foo = {};    #Sets $foo to be a reference to an anonymous hash.

Now, the real fun can begin! Instead of storing individual values, you can now store whole data structures.
Imagine something like this:
my %system;   #Normal hash keyed by domain name

$system{server1} = {};  # This points to an anonymous hash!
$system{server1}->{START}  = "20121021T01:00:56";
$system{server1}->{STOP}   = "20121021T01:00:56";
$system{server1}->{RETURN} = 0;
$system{server1}->{USERS} = [];  #This hash entry points to an anonymous array
$system{server1}->{USERS}->[0] = "user1";
$system{server1}->{USERS}->[1] = "user2";
$system{server1}->{USERS}->[2] = "user3";

And so on with server2. You have one hash %system that is keyed by the domain name. Each domain in your %system hash has a START time a STOP time, a RETURN value, an a list of USERS on that system. What is the start time for server1? It's $system{server1}->{START}. What is the list of users on system2? It's @{ $system{server2}->{USERS} }(a dereference of the array stored in $system{server2}->{USERS}).
It takes some getting use to this new way of thinking, but you can see that it helps keep your data together as a single structure.
Of course, with complex data structures comes problems keeping it straight. For example:
use strict;
use warnings;

my %server;
$servre{domain1} = "10.10.1.20";

Will fail because I never declared $servre. However:
use strict;
use warnings;
my $hash = {};
$hash->{SERVRE}->{domain1} = "10.10.1.20";

Will work just fine. In this case, SERVRE is a key to a hash reference and not a variable. The use strict; pragma won't detect my poor spelling in this case. This leads you to the next step: Object Oriented Perl. However, first understand these new complex data structures and how they work. After you get more comfortable using them in your programs, you can start looking into how object oriented programming will help tame the mess they cause.

A: A fun problem, which makes me want to use paragraph mode. Using ####... as input record separator is an idea, surely, but it is a bit wonky and not so flexible. For example, $/ must be literal, meaning you have to have the exact number of characters.
If you can rely on double newlines as demonstrated in your input, paragraph mode will read each "set" in two parts, then the ####... delimiter as an easily discarded third part, and also the signal to start a new data set. Also, in this way, we have easier access to the "user" part, which may be somewhat random and its only determining feature being that it is preceded by the header "Output\n------".
use strict;
use warnings;
use Data::Dumper;

$/ = "";                             # use paragraph mode
my @data = [];                       # first element must be array ref
while (<DATA>) {
    unless (/^#+\s*$/) {             # if not delimiter
        push @{ $data[-1] }, $_;     # save data in the arrays last element
    } else {
        push @data, [];              # start new array (which becomes the last)
    }
}
my %hash;
for (@data) {
    my ($sys, $out) = @$_;                  # $_ is an array ref w two elements
    my ($server) = $sys =~ /System:\s*(\S+)/;   # extract server name
    my @users = split /\n+/, $out;          # easy extraction of users
    splice @users, 0, 2;                    # remove header
    $hash{$server}{$_} = undef for @users;  # add key w undef value
}

print Dumper \%hash;
__DATA__
System:      server1.domain.com
Start Time:  20121021T01:00:56
Stop Time:   20121021T01:00:56
Return Code: 0

Output
------
user1
user2
user3

##############################

System:      server2.domain.com
Start Time:  20121021T01:00:56
Stop Time:   20121021T01:00:56
Return Code: 0

Output
------
user1
user4
user5
user6

Output:
$VAR1 = {
          'server1.domain.com' => {
                                    'user1' => undef,
                                    'user3' => undef,
                                    'user2' => undef
                                  },
          'server2.domain.com' => {
                                    'user5' => undef,
                                    'user1' => undef,
                                    'user4' => undef,
                                    'user6' => undef
                                  }
        };

Some notes about the finer points:

*

*$data[-1] is the same as $data[$#data], I just think it looks a bit more readable.

*Pushing an empty array ref onto @data means we start collecting a new set. This works in conjunction with the note above.

*Saving the data in a two-dimensional array saves us some trouble in separating the "can-be-unpredictable" user names from the other data.

*Splitting the Output block on multiple newlines strips our data of any troublesome trailing newlines, which is handy, since chomp only strips double newlines in paragraph mode (unless we change $/ again).

*Adding undef as a value to the user name keys is merely a placeholder for any other value you may wish to put there.

*Changing <DATA> to <>, and replacing the Dumper output will allow you to use file name args, or stdin with the script. These features are only for demonstration. Usage would be:

some_command | perl script.pl > output.txt
perl script.pl input.txt > output.txt


text:
Q: How to show a bootstrap Modal Window on form submit using "submit handler" of jQuery Validate method? I have a form and am using the .validate method for validation of fields and form submission. I want to display a Bootstrap Modal Window on submit. Can some one please help me achieve this? Here is the code:
<form action="" method="post" id="registration" novalidate="novalidate" enctype="plain/text">

...

</form>

             ... Modal Window Content..

$("#registration").validate({

        rules: {
            .....
        },

        messages: {
            ......
        },

        submitHandler: function(form){
            //alert("Thank you for registration..!");
            form.submit();
        }

    });

A: You have to submit form in async request, and on success show the modal. eg
$("#registration").validate({

    rules: {
        .....
    },

    messages: {
        ......
    },

    submitHandler: function(form){
        $.ajax({
            url: $(form).action,
            method: $(form).method,
            data: $(form).serialize(),
            success: function() {
               $("#myModal").modal("show");
            }
        })
    }

});